blob: 3daa3105862211aabe0df12baa35506a6f3c51e0 [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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/STLExtras.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000026#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000027#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000028#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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000054#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000055#include "llvm/IR/Instruction.h"
56#include "llvm/IR/Instructions.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000057#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000058#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"
Craig Topperd0af7e82017-04-28 05:31:46 +000070#include "llvm/Support/KnownBits.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000071#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000072#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000073#include "llvm/Target/TargetCallingConv.h"
74#include "llvm/Target/TargetInstrInfo.h"
75#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000076#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000077#include <algorithm>
78#include <bitset>
79#include <cassert>
80#include <cctype>
81#include <cstdint>
82#include <cstdlib>
83#include <iterator>
84#include <limits>
85#include <tuple>
86#include <utility>
87#include <vector>
88
Tim Northover3b0846e2014-05-24 12:50:23 +000089using namespace llvm;
90
91#define DEBUG_TYPE "aarch64-lower"
92
93STATISTIC(NumTailCalls, "Number of tail calls");
94STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000095STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000096
Tim Northover3b0846e2014-05-24 12:50:23 +000097static cl::opt<bool>
98EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000099 cl::desc("Allow AArch64 SLI/SRI formation"),
100 cl::init(false));
101
102// FIXME: The necessary dtprel relocations don't seem to be supported
103// well in the GNU bfd and gold linkers at the moment. Therefore, by
104// default, for now, fall back to GeneralDynamic code generation.
105cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106 "aarch64-elf-ldtls-generation", cl::Hidden,
107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000109
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000110static cl::opt<bool>
111EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112 cl::desc("Enable AArch64 logical imm instruction "
113 "optimization"),
114 cl::init(true));
115
Matthias Braunaf7d7702015-07-16 20:02:37 +0000116/// Value type used for condition codes.
117static const MVT MVT_CC = MVT::i32;
118
Eric Christopher905f12d2015-01-29 00:19:42 +0000119AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120 const AArch64Subtarget &STI)
121 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123 // we have to make something up. Arbitrarily, choose ZeroOrOne.
124 setBooleanContents(ZeroOrOneBooleanContent);
125 // When comparing vectors the result sets the different elements in the
126 // vector to all-one or all-zero.
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129 // Set up the register classes.
130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132
133 if (Subtarget->hasFPARMv8()) {
134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138 }
139
140 if (Subtarget->hasNEON()) {
141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143 // Someone set us up the NEON.
144 addDRTypeForNEON(MVT::v2f32);
145 addDRTypeForNEON(MVT::v8i8);
146 addDRTypeForNEON(MVT::v4i16);
147 addDRTypeForNEON(MVT::v2i32);
148 addDRTypeForNEON(MVT::v1i64);
149 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000150 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000151
152 addQRTypeForNEON(MVT::v4f32);
153 addQRTypeForNEON(MVT::v2f64);
154 addQRTypeForNEON(MVT::v16i8);
155 addQRTypeForNEON(MVT::v8i16);
156 addQRTypeForNEON(MVT::v4i32);
157 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000158 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000159 }
160
161 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000162 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000163
164 // Provide all sorts of operation actions
165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167 setOperationAction(ISD::SETCC, MVT::i32, Custom);
168 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000169 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000170 setOperationAction(ISD::SETCC, MVT::f32, Custom);
171 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000172 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
173 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000174 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
175 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
176 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000177 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000178 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
179 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
180 setOperationAction(ISD::SELECT, MVT::i32, Custom);
181 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000182 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000183 setOperationAction(ISD::SELECT, MVT::f32, Custom);
184 setOperationAction(ISD::SELECT, MVT::f64, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
186 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000187 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000188 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
189 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
190 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
191 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
192
193 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
194 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
195 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
196
197 setOperationAction(ISD::FREM, MVT::f32, Expand);
198 setOperationAction(ISD::FREM, MVT::f64, Expand);
199 setOperationAction(ISD::FREM, MVT::f80, Expand);
200
201 // Custom lowering hooks are needed for XOR
202 // to fold it into CSINC/CSINV.
203 setOperationAction(ISD::XOR, MVT::i32, Custom);
204 setOperationAction(ISD::XOR, MVT::i64, Custom);
205
206 // Virtually no operation on f128 is legal, but LLVM can't expand them when
207 // there's a valid register class, so we need custom operations in most cases.
208 setOperationAction(ISD::FABS, MVT::f128, Expand);
209 setOperationAction(ISD::FADD, MVT::f128, Custom);
210 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
211 setOperationAction(ISD::FCOS, MVT::f128, Expand);
212 setOperationAction(ISD::FDIV, MVT::f128, Custom);
213 setOperationAction(ISD::FMA, MVT::f128, Expand);
214 setOperationAction(ISD::FMUL, MVT::f128, Custom);
215 setOperationAction(ISD::FNEG, MVT::f128, Expand);
216 setOperationAction(ISD::FPOW, MVT::f128, Expand);
217 setOperationAction(ISD::FREM, MVT::f128, Expand);
218 setOperationAction(ISD::FRINT, MVT::f128, Expand);
219 setOperationAction(ISD::FSIN, MVT::f128, Expand);
220 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
221 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
222 setOperationAction(ISD::FSUB, MVT::f128, Custom);
223 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
224 setOperationAction(ISD::SETCC, MVT::f128, Custom);
225 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
226 setOperationAction(ISD::SELECT, MVT::f128, Custom);
227 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
228 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
229
230 // Lowering for many of the conversions is actually specified by the non-f128
231 // type. The LowerXXX function will be trivial when f128 isn't involved.
232 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
233 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
234 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
235 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
236 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
237 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
238 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
239 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
240 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
241 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
242 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
243 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
244 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
245 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
246
247 // Variable arguments.
248 setOperationAction(ISD::VASTART, MVT::Other, Custom);
249 setOperationAction(ISD::VAARG, MVT::Other, Custom);
250 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
251 setOperationAction(ISD::VAEND, MVT::Other, Expand);
252
253 // Variable-sized objects.
254 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
255 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
256 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
257
Tim Northover3b0846e2014-05-24 12:50:23 +0000258 // Constant pool entries
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
260
261 // BlockAddress
262 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
263
264 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
265 setOperationAction(ISD::ADDC, MVT::i32, Custom);
266 setOperationAction(ISD::ADDE, MVT::i32, Custom);
267 setOperationAction(ISD::SUBC, MVT::i32, Custom);
268 setOperationAction(ISD::SUBE, MVT::i32, Custom);
269 setOperationAction(ISD::ADDC, MVT::i64, Custom);
270 setOperationAction(ISD::ADDE, MVT::i64, Custom);
271 setOperationAction(ISD::SUBC, MVT::i64, Custom);
272 setOperationAction(ISD::SUBE, MVT::i64, Custom);
273
274 // AArch64 lacks both left-rotate and popcount instructions.
275 setOperationAction(ISD::ROTL, MVT::i32, Expand);
276 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000277 for (MVT VT : MVT::vector_valuetypes()) {
278 setOperationAction(ISD::ROTL, VT, Expand);
279 setOperationAction(ISD::ROTR, VT, Expand);
280 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000281
282 // AArch64 doesn't have {U|S}MUL_LOHI.
283 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
284 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
285
Tim Northover3b0846e2014-05-24 12:50:23 +0000286 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
287 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
288
289 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
290 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000291 for (MVT VT : MVT::vector_valuetypes()) {
292 setOperationAction(ISD::SDIVREM, VT, Expand);
293 setOperationAction(ISD::UDIVREM, VT, Expand);
294 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000295 setOperationAction(ISD::SREM, MVT::i32, Expand);
296 setOperationAction(ISD::SREM, MVT::i64, Expand);
297 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
298 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
299 setOperationAction(ISD::UREM, MVT::i32, Expand);
300 setOperationAction(ISD::UREM, MVT::i64, Expand);
301
302 // Custom lower Add/Sub/Mul with overflow.
303 setOperationAction(ISD::SADDO, MVT::i32, Custom);
304 setOperationAction(ISD::SADDO, MVT::i64, Custom);
305 setOperationAction(ISD::UADDO, MVT::i32, Custom);
306 setOperationAction(ISD::UADDO, MVT::i64, Custom);
307 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
308 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
309 setOperationAction(ISD::USUBO, MVT::i32, Custom);
310 setOperationAction(ISD::USUBO, MVT::i64, Custom);
311 setOperationAction(ISD::SMULO, MVT::i32, Custom);
312 setOperationAction(ISD::SMULO, MVT::i64, Custom);
313 setOperationAction(ISD::UMULO, MVT::i32, Custom);
314 setOperationAction(ISD::UMULO, MVT::i64, Custom);
315
316 setOperationAction(ISD::FSIN, MVT::f32, Expand);
317 setOperationAction(ISD::FSIN, MVT::f64, Expand);
318 setOperationAction(ISD::FCOS, MVT::f32, Expand);
319 setOperationAction(ISD::FCOS, MVT::f64, Expand);
320 setOperationAction(ISD::FPOW, MVT::f32, Expand);
321 setOperationAction(ISD::FPOW, MVT::f64, Expand);
322 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
323 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000324 if (Subtarget->hasFullFP16())
325 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
326 else
327 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000328
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000329 setOperationAction(ISD::FREM, MVT::f16, Promote);
330 setOperationAction(ISD::FREM, MVT::v4f16, Promote);
331 setOperationAction(ISD::FPOW, MVT::f16, Promote);
332 setOperationAction(ISD::FPOW, MVT::v4f16, Promote);
333 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
334 setOperationAction(ISD::FCOS, MVT::f16, Promote);
335 setOperationAction(ISD::FCOS, MVT::v4f16, Promote);
336 setOperationAction(ISD::FSIN, MVT::f16, Promote);
337 setOperationAction(ISD::FSIN, MVT::v4f16, Promote);
338 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
339 setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
340 setOperationAction(ISD::FEXP, MVT::f16, Promote);
341 setOperationAction(ISD::FEXP, MVT::v4f16, Promote);
342 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
343 setOperationAction(ISD::FEXP2, MVT::v4f16, Promote);
344 setOperationAction(ISD::FLOG, MVT::f16, Promote);
345 setOperationAction(ISD::FLOG, MVT::v4f16, Promote);
346 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
347 setOperationAction(ISD::FLOG2, MVT::v4f16, Promote);
348 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
349 setOperationAction(ISD::FLOG10, MVT::v4f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000350
351 if (!Subtarget->hasFullFP16()) {
352 setOperationAction(ISD::SELECT, MVT::f16, Promote);
353 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
354 setOperationAction(ISD::SETCC, MVT::f16, Promote);
355 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
356 setOperationAction(ISD::FADD, MVT::f16, Promote);
357 setOperationAction(ISD::FSUB, MVT::f16, Promote);
358 setOperationAction(ISD::FMUL, MVT::f16, Promote);
359 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000360 setOperationAction(ISD::FMA, MVT::f16, Promote);
361 setOperationAction(ISD::FNEG, MVT::f16, Promote);
362 setOperationAction(ISD::FABS, MVT::f16, Promote);
363 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
364 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000365 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
366 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
367 setOperationAction(ISD::FRINT, MVT::f16, Promote);
368 setOperationAction(ISD::FROUND, MVT::f16, Promote);
369 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
370 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
371 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
372 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
373 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000374
375 // promote v4f16 to v4f32 when that is known to be safe.
376 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
377 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
378 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
379 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
380 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
381 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
382 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
383 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
384 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
385 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
386 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
387 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
388
389 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
390 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
391 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
392 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
393 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
394 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
395 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
396 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
397 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
398 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
399 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
400 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
401 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
402 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
403 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000404 }
Oliver Stannardf5469be2014-08-18 14:22:39 +0000405
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000406
Oliver Stannard89d15422014-08-27 16:16:04 +0000407 // v8f16 is also a storage-only type, so expand it.
408 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
409 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
410 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
412 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
413 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
414 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
415 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
416 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
417 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
418 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
419 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
Oliver Stannard89d15422014-08-27 16:16:04 +0000420 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
421 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
422 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
423 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
424 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
425 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
426 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
427 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
428 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
429 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
430 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
431 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
432 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
433 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
434 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
435 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
436 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
437 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
438
Tim Northover3b0846e2014-05-24 12:50:23 +0000439 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000440 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000441 setOperationAction(ISD::FFLOOR, Ty, Legal);
442 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
443 setOperationAction(ISD::FCEIL, Ty, Legal);
444 setOperationAction(ISD::FRINT, Ty, Legal);
445 setOperationAction(ISD::FTRUNC, Ty, Legal);
446 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000447 setOperationAction(ISD::FMINNUM, Ty, Legal);
448 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000449 setOperationAction(ISD::FMINNAN, Ty, Legal);
450 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000451 }
452
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000453 if (Subtarget->hasFullFP16()) {
454 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
455 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
456 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
457 setOperationAction(ISD::FRINT, MVT::f16, Legal);
458 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
459 setOperationAction(ISD::FROUND, MVT::f16, Legal);
460 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
461 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
462 setOperationAction(ISD::FMINNAN, MVT::f16, Legal);
463 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal);
464 }
465
Tim Northover3b0846e2014-05-24 12:50:23 +0000466 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
467
Tim Northovercdf15292016-04-14 17:03:29 +0000468 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
469
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000470 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
471 // This requires the Performance Monitors extension.
472 if (Subtarget->hasPerfMon())
473 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
474
Tim Northover3b0846e2014-05-24 12:50:23 +0000475 if (Subtarget->isTargetMachO()) {
476 // For iOS, we don't want to the normal expansion of a libcall to
477 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
478 // traffic.
479 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
480 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
481 } else {
482 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
483 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
484 }
485
Juergen Ributzka23266502014-12-10 19:43:32 +0000486 // Make floating-point constants legal for the large code model, so they don't
487 // become loads from the constant pool.
488 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
489 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
490 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
491 }
492
Tim Northover3b0846e2014-05-24 12:50:23 +0000493 // AArch64 does not have floating-point extending loads, i1 sign-extending
494 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000495 for (MVT VT : MVT::fp_valuetypes()) {
496 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
497 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
498 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
499 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
500 }
501 for (MVT VT : MVT::integer_valuetypes())
502 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
503
Tim Northover3b0846e2014-05-24 12:50:23 +0000504 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
505 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
506 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
507 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
508 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
509 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
510 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000511
512 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
513 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
514
Tim Northover3b0846e2014-05-24 12:50:23 +0000515 // Indexed loads and stores are supported.
516 for (unsigned im = (unsigned)ISD::PRE_INC;
517 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
518 setIndexedLoadAction(im, MVT::i8, Legal);
519 setIndexedLoadAction(im, MVT::i16, Legal);
520 setIndexedLoadAction(im, MVT::i32, Legal);
521 setIndexedLoadAction(im, MVT::i64, Legal);
522 setIndexedLoadAction(im, MVT::f64, Legal);
523 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000524 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000525 setIndexedStoreAction(im, MVT::i8, Legal);
526 setIndexedStoreAction(im, MVT::i16, Legal);
527 setIndexedStoreAction(im, MVT::i32, Legal);
528 setIndexedStoreAction(im, MVT::i64, Legal);
529 setIndexedStoreAction(im, MVT::f64, Legal);
530 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000531 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000532 }
533
534 // Trap.
535 setOperationAction(ISD::TRAP, MVT::Other, Legal);
536
537 // We combine OR nodes for bitfield operations.
538 setTargetDAGCombine(ISD::OR);
539
540 // Vector add and sub nodes may conceal a high-half opportunity.
541 // Also, try to fold ADD into CSINC/CSINV..
542 setTargetDAGCombine(ISD::ADD);
543 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000544 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000545 setTargetDAGCombine(ISD::XOR);
546 setTargetDAGCombine(ISD::SINT_TO_FP);
547 setTargetDAGCombine(ISD::UINT_TO_FP);
548
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000549 setTargetDAGCombine(ISD::FP_TO_SINT);
550 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000551 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000552
Tim Northover3b0846e2014-05-24 12:50:23 +0000553 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
554
555 setTargetDAGCombine(ISD::ANY_EXTEND);
556 setTargetDAGCombine(ISD::ZERO_EXTEND);
557 setTargetDAGCombine(ISD::SIGN_EXTEND);
558 setTargetDAGCombine(ISD::BITCAST);
559 setTargetDAGCombine(ISD::CONCAT_VECTORS);
560 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000561 if (Subtarget->supportsAddressTopByteIgnored())
562 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000563
564 setTargetDAGCombine(ISD::MUL);
565
566 setTargetDAGCombine(ISD::SELECT);
567 setTargetDAGCombine(ISD::VSELECT);
568
569 setTargetDAGCombine(ISD::INTRINSIC_VOID);
570 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
571 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
572
573 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
574 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
575 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
576
577 setStackPointerRegisterToSaveRestore(AArch64::SP);
578
579 setSchedulingPreference(Sched::Hybrid);
580
Quentin Colombet6843ac42015-03-31 20:52:32 +0000581 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000582
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000583 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000584 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000585 // Set preferred alignments.
586 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
587 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000588
Evandro Menezese45de8a2016-09-26 15:32:33 +0000589 // Only change the limit for entries in a jump table if specified by
590 // the subtarget, but not at the command line.
591 unsigned MaxJT = STI.getMaximumJumpTableSize();
592 if (MaxJT && getMaximumJumpTableSize() == 0)
593 setMaximumJumpTableSize(MaxJT);
594
Tim Northover3b0846e2014-05-24 12:50:23 +0000595 setHasExtractBitsInsn(true);
596
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000597 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
598
Tim Northover3b0846e2014-05-24 12:50:23 +0000599 if (Subtarget->hasNEON()) {
600 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
601 // silliness like this:
602 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
603 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
604 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
605 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
606 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
607 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
608 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
609 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
610 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
611 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
612 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
613 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
614 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
615 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
616 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
617 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
618 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
619 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
620 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
621 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
622 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
623 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
624 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
625 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
626 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
627
628 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
629 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
630 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
631 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
632 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
633
634 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
635
636 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
637 // elements smaller than i32, so promote the input to i32 first.
638 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
639 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
640 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
641 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000642 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
643 // -> v8f16 conversions.
644 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
645 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
646 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
647 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000648 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
649 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
650 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
651 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
652 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000653 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
654 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
655 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
656 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000657
Craig Topperc5551bf2016-04-26 05:26:51 +0000658 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
659 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
660
Craig Topper3b4842b2016-04-28 01:58:21 +0000661 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
662 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
663 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
664 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
665 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
666 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
667 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
668 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
669
Tim Northover3b0846e2014-05-24 12:50:23 +0000670 // AArch64 doesn't have MUL.2d:
671 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000672 // Custom handling for some quad-vector types to detect MULL.
673 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
674 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
675 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
676
Amara Emersonc9916d72017-05-16 21:29:22 +0000677 // Vector reductions
678 for (MVT VT : MVT::integer_valuetypes()) {
679 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
680 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
681 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
682 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
683 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
684 }
685 for (MVT VT : MVT::fp_valuetypes()) {
686 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
687 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
688 }
689
Tim Northover3b0846e2014-05-24 12:50:23 +0000690 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
691 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
692 // Likewise, narrowing and extending vector loads/stores aren't handled
693 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000694 for (MVT VT : MVT::vector_valuetypes()) {
695 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000696
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000697 setOperationAction(ISD::MULHS, VT, Expand);
698 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
699 setOperationAction(ISD::MULHU, VT, Expand);
700 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000701
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000702 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000703
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000704 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000705 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000706 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
707 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
708 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
709 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000710 }
711
712 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000713 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000714 setOperationAction(ISD::FFLOOR, Ty, Legal);
715 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
716 setOperationAction(ISD::FCEIL, Ty, Legal);
717 setOperationAction(ISD::FRINT, Ty, Legal);
718 setOperationAction(ISD::FTRUNC, Ty, Legal);
719 setOperationAction(ISD::FROUND, Ty, Legal);
720 }
721 }
James Molloyf089ab72014-08-06 10:42:18 +0000722
Matthias Braun651cff42016-06-02 18:03:53 +0000723 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000724}
725
Craig Topper18e69f42016-04-15 06:20:21 +0000726void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000727 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000728 setOperationAction(ISD::LOAD, VT, Promote);
729 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000730
Craig Topper18e69f42016-04-15 06:20:21 +0000731 setOperationAction(ISD::STORE, VT, Promote);
732 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000733 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000734 setOperationAction(ISD::LOAD, VT, Promote);
735 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000736
Craig Topper18e69f42016-04-15 06:20:21 +0000737 setOperationAction(ISD::STORE, VT, Promote);
738 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000739 }
740
741 // Mark vector float intrinsics as expand.
742 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000743 setOperationAction(ISD::FSIN, VT, Expand);
744 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000745 setOperationAction(ISD::FPOW, VT, Expand);
746 setOperationAction(ISD::FLOG, VT, Expand);
747 setOperationAction(ISD::FLOG2, VT, Expand);
748 setOperationAction(ISD::FLOG10, VT, Expand);
749 setOperationAction(ISD::FEXP, VT, Expand);
750 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000751
752 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000753 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000754 }
755
Craig Topper18e69f42016-04-15 06:20:21 +0000756 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
757 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
758 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
759 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
760 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
761 setOperationAction(ISD::SRA, VT, Custom);
762 setOperationAction(ISD::SRL, VT, Custom);
763 setOperationAction(ISD::SHL, VT, Custom);
764 setOperationAction(ISD::AND, VT, Custom);
765 setOperationAction(ISD::OR, VT, Custom);
766 setOperationAction(ISD::SETCC, VT, Custom);
767 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000768
Craig Topper18e69f42016-04-15 06:20:21 +0000769 setOperationAction(ISD::SELECT, VT, Expand);
770 setOperationAction(ISD::SELECT_CC, VT, Expand);
771 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000772 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000773 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000774
775 // CNT supports only B element sizes.
776 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000777 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000778
Craig Topper18e69f42016-04-15 06:20:21 +0000779 setOperationAction(ISD::UDIV, VT, Expand);
780 setOperationAction(ISD::SDIV, VT, Expand);
781 setOperationAction(ISD::UREM, VT, Expand);
782 setOperationAction(ISD::SREM, VT, Expand);
783 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000784
Craig Topper18e69f42016-04-15 06:20:21 +0000785 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
786 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000787
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000788 if (!VT.isFloatingPoint())
789 setOperationAction(ISD::ABS, VT, Legal);
790
Hal Finkelcd8664c2015-12-11 23:11:52 +0000791 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000792 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000793 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000794 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000795
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000796 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
797 if (VT.isFloatingPoint() &&
798 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
James Molloyb7b2a1e2015-08-11 12:06:37 +0000799 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
800 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000801 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000802
Tim Northover3b0846e2014-05-24 12:50:23 +0000803 if (Subtarget->isLittleEndian()) {
804 for (unsigned im = (unsigned)ISD::PRE_INC;
805 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000806 setIndexedLoadAction(im, VT, Legal);
807 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000808 }
809 }
810}
811
812void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
813 addRegisterClass(VT, &AArch64::FPR64RegClass);
814 addTypeForNEON(VT, MVT::v2i32);
815}
816
817void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
818 addRegisterClass(VT, &AArch64::FPR128RegClass);
819 addTypeForNEON(VT, MVT::v4i32);
820}
821
Mehdi Amini44ede332015-07-09 02:09:04 +0000822EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
823 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000824 if (!VT.isVector())
825 return MVT::i32;
826 return VT.changeVectorElementTypeToInteger();
827}
828
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000829static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
830 const APInt &Demanded,
831 TargetLowering::TargetLoweringOpt &TLO,
832 unsigned NewOpc) {
833 uint64_t OldImm = Imm, NewImm, Enc;
834 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
835
836 // Return if the immediate is already all zeros, all ones, a bimm32 or a
837 // bimm64.
838 if (Imm == 0 || Imm == Mask ||
839 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
840 return false;
841
842 unsigned EltSize = Size;
843 uint64_t DemandedBits = Demanded.getZExtValue();
844
845 // Clear bits that are not demanded.
846 Imm &= DemandedBits;
847
848 while (true) {
849 // The goal here is to set the non-demanded bits in a way that minimizes
850 // the number of switching between 0 and 1. In order to achieve this goal,
851 // we set the non-demanded bits to the value of the preceding demanded bits.
852 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
853 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
854 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
855 // The final result is 0b11000011.
856 uint64_t NonDemandedBits = ~DemandedBits;
857 uint64_t InvertedImm = ~Imm & DemandedBits;
858 uint64_t RotatedImm =
859 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
860 NonDemandedBits;
861 uint64_t Sum = RotatedImm + NonDemandedBits;
862 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
863 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
864 NewImm = (Imm | Ones) & Mask;
865
866 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
867 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
868 // we halve the element size and continue the search.
869 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
870 break;
871
872 // We cannot shrink the element size any further if it is 2-bits.
873 if (EltSize == 2)
874 return false;
875
876 EltSize /= 2;
877 Mask >>= EltSize;
878 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
879
880 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
881 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
882 return false;
883
884 // Merge the upper and lower halves of Imm and DemandedBits.
885 Imm |= Hi;
886 DemandedBits |= DemandedBitsHi;
887 }
888
889 ++NumOptimizedImms;
890
891 // Replicate the element across the register width.
892 while (EltSize < Size) {
893 NewImm |= NewImm << EltSize;
894 EltSize *= 2;
895 }
896
897 (void)OldImm;
898 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
899 "demanded bits should never be altered");
900 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
901
902 // Create the new constant immediate node.
903 EVT VT = Op.getValueType();
904 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000905 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000906
907 // If the new constant immediate is all-zeros or all-ones, let the target
908 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000909 if (NewImm == 0 || NewImm == OrigMask) {
910 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
911 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000912 // Otherwise, create a machine node so that target independent DAG combine
913 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000914 } else {
915 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
916 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
917 New = SDValue(
918 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
919 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000920
921 return TLO.CombineTo(Op, New);
922}
923
924bool AArch64TargetLowering::targetShrinkDemandedConstant(
925 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
926 // Delay this optimization to as late as possible.
927 if (!TLO.LegalOps)
928 return false;
929
930 if (!EnableOptimizeLogicalImm)
931 return false;
932
933 EVT VT = Op.getValueType();
934 if (VT.isVector())
935 return false;
936
937 unsigned Size = VT.getSizeInBits();
938 assert((Size == 32 || Size == 64) &&
939 "i32 or i64 is expected after legalization.");
940
941 // Exit early if we demand all bits.
942 if (Demanded.countPopulation() == Size)
943 return false;
944
945 unsigned NewOpc;
946 switch (Op.getOpcode()) {
947 default:
948 return false;
949 case ISD::AND:
950 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
951 break;
952 case ISD::OR:
953 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
954 break;
955 case ISD::XOR:
956 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
957 break;
958 }
959 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
960 if (!C)
961 return false;
962 uint64_t Imm = C->getZExtValue();
963 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
964}
965
Tim Northover3b0846e2014-05-24 12:50:23 +0000966/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000967/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000968void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000969 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000970 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000971 switch (Op.getOpcode()) {
972 default:
973 break;
974 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000975 KnownBits Known2;
976 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
977 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
978 Known.Zero &= Known2.Zero;
979 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +0000980 break;
981 }
982 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000983 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000984 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
985 switch (IntID) {
986 default: return;
987 case Intrinsic::aarch64_ldaxr:
988 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000989 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +0000990 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +0000991 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +0000992 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +0000993 return;
994 }
995 }
996 break;
997 }
998 case ISD::INTRINSIC_WO_CHAIN:
999 case ISD::INTRINSIC_VOID: {
1000 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1001 switch (IntNo) {
1002 default:
1003 break;
1004 case Intrinsic::aarch64_neon_umaxv:
1005 case Intrinsic::aarch64_neon_uminv: {
1006 // Figure out the datatype of the vector operand. The UMINV instruction
1007 // will zero extend the result, so we can mark as known zero all the
1008 // bits larger than the element datatype. 32-bit or larget doesn't need
1009 // this as those are legal types and will be handled by isel directly.
1010 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001011 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001012 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1013 assert(BitWidth >= 8 && "Unexpected width!");
1014 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001015 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001016 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1017 assert(BitWidth >= 16 && "Unexpected width!");
1018 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001019 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001020 }
1021 break;
1022 } break;
1023 }
1024 }
1025 }
1026}
1027
Mehdi Aminieaabc512015-07-09 15:12:23 +00001028MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1029 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001030 return MVT::i64;
1031}
1032
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001033bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1034 unsigned AddrSpace,
1035 unsigned Align,
1036 bool *Fast) const {
1037 if (Subtarget->requiresStrictAlign())
1038 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001039
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001040 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001041 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1042 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001043 // See comments in performSTORECombine() for more details about
1044 // these conditions.
1045
1046 // Code that uses clang vector extensions can mark that it
1047 // wants unaligned accesses to be treated as fast by
1048 // underspecifying alignment to be 1 or 2.
1049 Align <= 2 ||
1050
1051 // Disregard v2i64. Memcpy lowering produces those and splitting
1052 // them regresses performance on micro-benchmarks and olden/bh.
1053 VT == MVT::v2i64;
1054 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001055 return true;
1056}
1057
Tim Northover3b0846e2014-05-24 12:50:23 +00001058FastISel *
1059AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1060 const TargetLibraryInfo *libInfo) const {
1061 return AArch64::createFastISel(funcInfo, libInfo);
1062}
1063
1064const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001065 switch ((AArch64ISD::NodeType)Opcode) {
1066 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001067 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1068 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1069 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1070 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1071 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1072 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1073 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1074 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1075 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1076 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1077 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1078 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001079 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001080 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1081 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1082 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1083 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1084 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1085 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1086 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001087 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1088 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1089 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001090 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001091 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1092 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1093 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1094 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1095 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1096 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1097 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1098 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1099 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1100 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1101 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1102 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1103 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1104 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1105 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1106 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1107 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1108 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1109 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1110 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1111 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1112 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1113 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1114 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1115 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1116 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1117 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1118 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1119 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1120 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1121 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1122 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1123 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1124 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1125 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1126 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1127 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1128 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1129 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1130 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1131 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1132 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1133 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1134 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1135 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1136 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1137 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1138 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001139 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1140 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1141 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1142 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1143 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1144 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001145 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1146 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1147 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1148 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1149 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1150 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1151 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001152 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001153 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1154 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001155 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001156 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1157 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1158 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1159 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1160 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1161 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1162 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1163 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1164 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1165 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1166 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1167 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1168 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1169 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1170 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1171 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1172 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1173 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1174 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1175 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1176 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1177 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1178 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1179 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1180 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1181 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1182 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1183 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1184 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001185 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1186 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001187 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001188 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1189 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1190 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001191 }
Matthias Braund04893f2015-05-07 21:33:59 +00001192 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001193}
1194
1195MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001196AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001197 MachineBasicBlock *MBB) const {
1198 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1199 // phi node:
1200
1201 // OrigBB:
1202 // [... previous instrs leading to comparison ...]
1203 // b.ne TrueBB
1204 // b EndBB
1205 // TrueBB:
1206 // ; Fallthrough
1207 // EndBB:
1208 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1209
Tim Northover3b0846e2014-05-24 12:50:23 +00001210 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001211 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001212 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001213 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001214 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001215
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001216 unsigned DestReg = MI.getOperand(0).getReg();
1217 unsigned IfTrueReg = MI.getOperand(1).getReg();
1218 unsigned IfFalseReg = MI.getOperand(2).getReg();
1219 unsigned CondCode = MI.getOperand(3).getImm();
1220 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001221
1222 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1223 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1224 MF->insert(It, TrueBB);
1225 MF->insert(It, EndBB);
1226
1227 // Transfer rest of current basic-block to EndBB
1228 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1229 MBB->end());
1230 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1231
1232 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1233 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1234 MBB->addSuccessor(TrueBB);
1235 MBB->addSuccessor(EndBB);
1236
1237 // TrueBB falls through to the end.
1238 TrueBB->addSuccessor(EndBB);
1239
1240 if (!NZCVKilled) {
1241 TrueBB->addLiveIn(AArch64::NZCV);
1242 EndBB->addLiveIn(AArch64::NZCV);
1243 }
1244
1245 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1246 .addReg(IfTrueReg)
1247 .addMBB(TrueBB)
1248 .addReg(IfFalseReg)
1249 .addMBB(MBB);
1250
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001251 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001252 return EndBB;
1253}
1254
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001255MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1256 MachineInstr &MI, MachineBasicBlock *BB) const {
1257 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001258 default:
1259#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001260 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001261#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001262 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001263
1264 case AArch64::F128CSEL:
1265 return EmitF128CSEL(MI, BB);
1266
1267 case TargetOpcode::STACKMAP:
1268 case TargetOpcode::PATCHPOINT:
1269 return emitPatchPoint(MI, BB);
1270 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001271}
1272
1273//===----------------------------------------------------------------------===//
1274// AArch64 Lowering private implementation.
1275//===----------------------------------------------------------------------===//
1276
1277//===----------------------------------------------------------------------===//
1278// Lowering Code
1279//===----------------------------------------------------------------------===//
1280
1281/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1282/// CC
1283static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1284 switch (CC) {
1285 default:
1286 llvm_unreachable("Unknown condition code!");
1287 case ISD::SETNE:
1288 return AArch64CC::NE;
1289 case ISD::SETEQ:
1290 return AArch64CC::EQ;
1291 case ISD::SETGT:
1292 return AArch64CC::GT;
1293 case ISD::SETGE:
1294 return AArch64CC::GE;
1295 case ISD::SETLT:
1296 return AArch64CC::LT;
1297 case ISD::SETLE:
1298 return AArch64CC::LE;
1299 case ISD::SETUGT:
1300 return AArch64CC::HI;
1301 case ISD::SETUGE:
1302 return AArch64CC::HS;
1303 case ISD::SETULT:
1304 return AArch64CC::LO;
1305 case ISD::SETULE:
1306 return AArch64CC::LS;
1307 }
1308}
1309
1310/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1311static void changeFPCCToAArch64CC(ISD::CondCode CC,
1312 AArch64CC::CondCode &CondCode,
1313 AArch64CC::CondCode &CondCode2) {
1314 CondCode2 = AArch64CC::AL;
1315 switch (CC) {
1316 default:
1317 llvm_unreachable("Unknown FP condition!");
1318 case ISD::SETEQ:
1319 case ISD::SETOEQ:
1320 CondCode = AArch64CC::EQ;
1321 break;
1322 case ISD::SETGT:
1323 case ISD::SETOGT:
1324 CondCode = AArch64CC::GT;
1325 break;
1326 case ISD::SETGE:
1327 case ISD::SETOGE:
1328 CondCode = AArch64CC::GE;
1329 break;
1330 case ISD::SETOLT:
1331 CondCode = AArch64CC::MI;
1332 break;
1333 case ISD::SETOLE:
1334 CondCode = AArch64CC::LS;
1335 break;
1336 case ISD::SETONE:
1337 CondCode = AArch64CC::MI;
1338 CondCode2 = AArch64CC::GT;
1339 break;
1340 case ISD::SETO:
1341 CondCode = AArch64CC::VC;
1342 break;
1343 case ISD::SETUO:
1344 CondCode = AArch64CC::VS;
1345 break;
1346 case ISD::SETUEQ:
1347 CondCode = AArch64CC::EQ;
1348 CondCode2 = AArch64CC::VS;
1349 break;
1350 case ISD::SETUGT:
1351 CondCode = AArch64CC::HI;
1352 break;
1353 case ISD::SETUGE:
1354 CondCode = AArch64CC::PL;
1355 break;
1356 case ISD::SETLT:
1357 case ISD::SETULT:
1358 CondCode = AArch64CC::LT;
1359 break;
1360 case ISD::SETLE:
1361 case ISD::SETULE:
1362 CondCode = AArch64CC::LE;
1363 break;
1364 case ISD::SETNE:
1365 case ISD::SETUNE:
1366 CondCode = AArch64CC::NE;
1367 break;
1368 }
1369}
1370
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001371/// Convert a DAG fp condition code to an AArch64 CC.
1372/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1373/// should be AND'ed instead of OR'ed.
1374static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1375 AArch64CC::CondCode &CondCode,
1376 AArch64CC::CondCode &CondCode2) {
1377 CondCode2 = AArch64CC::AL;
1378 switch (CC) {
1379 default:
1380 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1381 assert(CondCode2 == AArch64CC::AL);
1382 break;
1383 case ISD::SETONE:
1384 // (a one b)
1385 // == ((a olt b) || (a ogt b))
1386 // == ((a ord b) && (a une b))
1387 CondCode = AArch64CC::VC;
1388 CondCode2 = AArch64CC::NE;
1389 break;
1390 case ISD::SETUEQ:
1391 // (a ueq b)
1392 // == ((a uno b) || (a oeq b))
1393 // == ((a ule b) && (a uge b))
1394 CondCode = AArch64CC::PL;
1395 CondCode2 = AArch64CC::LE;
1396 break;
1397 }
1398}
1399
Tim Northover3b0846e2014-05-24 12:50:23 +00001400/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1401/// CC usable with the vector instructions. Fewer operations are available
1402/// without a real NZCV register, so we have to use less efficient combinations
1403/// to get the same effect.
1404static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1405 AArch64CC::CondCode &CondCode,
1406 AArch64CC::CondCode &CondCode2,
1407 bool &Invert) {
1408 Invert = false;
1409 switch (CC) {
1410 default:
1411 // Mostly the scalar mappings work fine.
1412 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1413 break;
1414 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001415 Invert = true;
1416 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001417 case ISD::SETO:
1418 CondCode = AArch64CC::MI;
1419 CondCode2 = AArch64CC::GE;
1420 break;
1421 case ISD::SETUEQ:
1422 case ISD::SETULT:
1423 case ISD::SETULE:
1424 case ISD::SETUGT:
1425 case ISD::SETUGE:
1426 // All of the compare-mask comparisons are ordered, but we can switch
1427 // between the two by a double inversion. E.g. ULE == !OGT.
1428 Invert = true;
1429 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1430 break;
1431 }
1432}
1433
1434static bool isLegalArithImmed(uint64_t C) {
1435 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001436 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1437 DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1438 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001439}
1440
1441static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001442 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001443 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001444 const bool FullFP16 =
1445 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001446
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001447 if (VT.isFloatingPoint()) {
1448 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001449 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001450 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1451 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001452 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001453 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001454 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001455 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001456
1457 // The CMP instruction is just an alias for SUBS, and representing it as
1458 // SUBS means that it's possible to get CSE with subtract operations.
1459 // A later phase can perform the optimization of setting the destination
1460 // register to WZR/XZR if it ends up being unused.
1461 unsigned Opcode = AArch64ISD::SUBS;
1462
Artyom Skrobov314ee042015-11-25 19:41:11 +00001463 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001464 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1465 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1466 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1467 // can be set differently by this operation. It comes down to whether
1468 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1469 // everything is fine. If not then the optimization is wrong. Thus general
1470 // comparisons are only valid if op2 != 0.
1471
1472 // So, finally, the only LLVM-native comparisons that don't mention C and V
1473 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1474 // the absence of information about op2.
1475 Opcode = AArch64ISD::ADDS;
1476 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001477 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001478 !isUnsignedIntSetCC(CC)) {
1479 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1480 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1481 // of the signed comparisons.
1482 Opcode = AArch64ISD::ANDS;
1483 RHS = LHS.getOperand(1);
1484 LHS = LHS.getOperand(0);
1485 }
1486
Matthias Braunaf7d7702015-07-16 20:02:37 +00001487 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001488 .getValue(1);
1489}
1490
Matthias Braunaf7d7702015-07-16 20:02:37 +00001491/// \defgroup AArch64CCMP CMP;CCMP matching
1492///
1493/// These functions deal with the formation of CMP;CCMP;... sequences.
1494/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1495/// a comparison. They set the NZCV flags to a predefined value if their
1496/// predicate is false. This allows to express arbitrary conjunctions, for
1497/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1498/// expressed as:
1499/// cmp A
1500/// ccmp B, inv(CB), CA
1501/// check for CB flags
1502///
1503/// In general we can create code for arbitrary "... (and (and A B) C)"
1504/// sequences. We can also implement some "or" expressions, because "(or A B)"
1505/// is equivalent to "not (and (not A) (not B))" and we can implement some
1506/// negation operations:
1507/// We can negate the results of a single comparison by inverting the flags
1508/// used when the predicate fails and inverting the flags tested in the next
1509/// instruction; We can also negate the results of the whole previous
1510/// conditional compare sequence by inverting the flags tested in the next
1511/// instruction. However there is no way to negate the result of a partial
1512/// sequence.
1513///
1514/// Therefore on encountering an "or" expression we can negate the subtree on
1515/// one side and have to be able to push the negate to the leafs of the subtree
1516/// on the other side (see also the comments in code). As complete example:
1517/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1518/// (and (setCC (cmp C)) (setCD (cmp D)))"
1519/// is transformed to
1520/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1521/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1522/// and implemented as:
1523/// cmp C
1524/// ccmp D, inv(CD), CC
1525/// ccmp A, CA, inv(CD)
1526/// ccmp B, CB, inv(CA)
1527/// check for CB flags
1528/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1529/// by conditional compare sequences.
1530/// @{
1531
Geoff Berrye41c2df2015-07-20 22:03:52 +00001532/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001533static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1534 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001535 AArch64CC::CondCode Predicate,
1536 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001537 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001538 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001539 const bool FullFP16 =
1540 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1541
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001542 if (LHS.getValueType().isFloatingPoint()) {
1543 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001544 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001545 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1546 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1547 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001548 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001549 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001550 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001551 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001552 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1553 Opcode = AArch64ISD::CCMN;
1554 RHS = RHS.getOperand(1);
1555 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001556 }
1557 if (Opcode == 0)
1558 Opcode = AArch64ISD::CCMP;
1559
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001560 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1561 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1562 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001563 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1564 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1565}
1566
1567/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1568/// CanPushNegate is set to true if we can push a negate operation through
1569/// the tree in a was that we are left with AND operations and negate operations
1570/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1571/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1572/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001573static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001574 unsigned Depth = 0) {
1575 if (!Val.hasOneUse())
1576 return false;
1577 unsigned Opcode = Val->getOpcode();
1578 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001579 if (Val->getOperand(0).getValueType() == MVT::f128)
1580 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001581 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001582 return true;
1583 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001584 // Protect against exponential runtime and stack overflow.
1585 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001586 return false;
1587 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1588 SDValue O0 = Val->getOperand(0);
1589 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001590 bool CanNegateL;
1591 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001592 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001593 bool CanNegateR;
1594 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001595 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001596
1597 if (Opcode == ISD::OR) {
1598 // For an OR expression we need to be able to negate at least one side or
1599 // we cannot do the transformation at all.
1600 if (!CanNegateL && !CanNegateR)
1601 return false;
1602 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1603 // can negate the x and y subtrees.
1604 CanNegate = CanNegateL && CanNegateR;
1605 } else {
1606 // If the operands are OR expressions then we finally need to negate their
1607 // outputs, we can only do that for the operand with emitted last by
1608 // negating OutCC, not for both operands.
1609 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1610 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1611 if (NeedsNegOutL && NeedsNegOutR)
1612 return false;
1613 // We cannot negate an AND operation (it would become an OR),
1614 CanNegate = false;
1615 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001616 return true;
1617 }
1618 return false;
1619}
1620
1621/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1622/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1623/// Tries to transform the given i1 producing node @p Val to a series compare
1624/// and conditional compare operations. @returns an NZCV flags producing node
1625/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1626/// transformation was not possible.
1627/// On recursive invocations @p PushNegate may be set to true to have negation
1628/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1629/// for the comparisons in the current subtree; @p Depth limits the search
1630/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001631static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1632 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001633 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001634 // We're at a tree leaf, produce a conditional comparison operation.
1635 unsigned Opcode = Val->getOpcode();
1636 if (Opcode == ISD::SETCC) {
1637 SDValue LHS = Val->getOperand(0);
1638 SDValue RHS = Val->getOperand(1);
1639 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1640 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001641 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001642 CC = getSetCCInverse(CC, isInteger);
1643 SDLoc DL(Val);
1644 // Determine OutCC and handle FP special case.
1645 if (isInteger) {
1646 OutCC = changeIntCCToAArch64CC(CC);
1647 } else {
1648 assert(LHS.getValueType().isFloatingPoint());
1649 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001650 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1651 // Some floating point conditions can't be tested with a single condition
1652 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001653 if (ExtraCC != AArch64CC::AL) {
1654 SDValue ExtraCmp;
1655 if (!CCOp.getNode())
1656 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001657 else
1658 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001659 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001660 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001661 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001662 }
1663 }
1664
1665 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001666 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001667 return emitComparison(LHS, RHS, CC, DL, DAG);
1668 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001669 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001670 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001671 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001672 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1673 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001674
1675 // Check if both sides can be transformed.
1676 SDValue LHS = Val->getOperand(0);
1677 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001678
Matthias Braunfdef49b2016-01-23 04:05:22 +00001679 // In case of an OR we need to negate our operands and the result.
1680 // (A v B) <=> not(not(A) ^ not(B))
1681 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001682 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001683 // predicate flags giving us a free negation for one side. The other side
1684 // must be negatable by itself.
1685 if (NegateOpsAndResult) {
1686 // See which side we can negate.
1687 bool CanNegateL;
1688 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1689 assert(isValidL && "Valid conjunction/disjunction tree");
1690 (void)isValidL;
1691
1692#ifndef NDEBUG
1693 bool CanNegateR;
1694 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1695 assert(isValidR && "Valid conjunction/disjunction tree");
1696 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1697#endif
1698
1699 // Order the side which we cannot negate to RHS so we can emit it first.
1700 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001701 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001702 } else {
1703 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001704 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001705 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001706 // Order the side where we need to negate the output flags to RHS so it
1707 // gets emitted first.
1708 if (NeedsNegOutL)
1709 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001710 }
1711
1712 // Emit RHS. If we want to negate the tree we only need to push a negate
1713 // through if we are already in a PushNegate case, otherwise we can negate
1714 // the "flags to test" afterwards.
1715 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001716 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001717 CCOp, Predicate);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001718 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001719 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001720 // Emit LHS. We may need to negate it.
1721 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1722 NegateOpsAndResult, CmpR,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001723 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001724 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001725 // (or absorb the Negate parameter).
1726 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001727 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1728 return CmpL;
1729}
1730
Matthias Braunfdef49b2016-01-23 04:05:22 +00001731/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1732/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1733/// \see emitConjunctionDisjunctionTreeRec().
1734static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001735 AArch64CC::CondCode &OutCC) {
Matthias Braunfdef49b2016-01-23 04:05:22 +00001736 bool CanNegate;
1737 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1738 return SDValue();
1739
1740 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001741 AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001742}
1743
Matthias Braunaf7d7702015-07-16 20:02:37 +00001744/// @}
1745
Tim Northover3b0846e2014-05-24 12:50:23 +00001746static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001747 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001748 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001749 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1750 EVT VT = RHS.getValueType();
1751 uint64_t C = RHSC->getZExtValue();
1752 if (!isLegalArithImmed(C)) {
1753 // Constant does not fit, try adjusting it by one?
1754 switch (CC) {
1755 default:
1756 break;
1757 case ISD::SETLT:
1758 case ISD::SETGE:
1759 if ((VT == MVT::i32 && C != 0x80000000 &&
1760 isLegalArithImmed((uint32_t)(C - 1))) ||
1761 (VT == MVT::i64 && C != 0x80000000ULL &&
1762 isLegalArithImmed(C - 1ULL))) {
1763 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1764 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001765 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001766 }
1767 break;
1768 case ISD::SETULT:
1769 case ISD::SETUGE:
1770 if ((VT == MVT::i32 && C != 0 &&
1771 isLegalArithImmed((uint32_t)(C - 1))) ||
1772 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1773 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1774 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001775 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001776 }
1777 break;
1778 case ISD::SETLE:
1779 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001780 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001781 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001782 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001783 isLegalArithImmed(C + 1ULL))) {
1784 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1785 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001786 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001787 }
1788 break;
1789 case ISD::SETULE:
1790 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001791 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001792 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001793 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001794 isLegalArithImmed(C + 1ULL))) {
1795 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1796 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001797 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001798 }
1799 break;
1800 }
1801 }
1802 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001803 SDValue Cmp;
1804 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001805 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001806 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1807
1808 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1809 // For the i8 operand, the largest immediate is 255, so this can be easily
1810 // encoded in the compare instruction. For the i16 operand, however, the
1811 // largest immediate cannot be encoded in the compare.
1812 // Therefore, use a sign extending load and cmn to avoid materializing the
1813 // -1 constant. For example,
1814 // movz w1, #65535
1815 // ldrh w0, [x0, #0]
1816 // cmp w0, w1
1817 // >
1818 // ldrsh w0, [x0, #0]
1819 // cmn w0, #1
1820 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1821 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001822 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001823 // transformation is profitable.
1824 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1825 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1826 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1827 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1828 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1829 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1830 SDValue SExt =
1831 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1832 DAG.getValueType(MVT::i16));
1833 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1834 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001835 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001836 AArch64CC = changeIntCCToAArch64CC(CC);
1837 }
1838 }
1839
1840 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001841 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001842 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1843 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001844 }
1845 }
1846 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001847
1848 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001849 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001850 AArch64CC = changeIntCCToAArch64CC(CC);
1851 }
1852 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001853 return Cmp;
1854}
1855
1856static std::pair<SDValue, SDValue>
1857getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1858 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1859 "Unsupported value type");
1860 SDValue Value, Overflow;
1861 SDLoc DL(Op);
1862 SDValue LHS = Op.getOperand(0);
1863 SDValue RHS = Op.getOperand(1);
1864 unsigned Opc = 0;
1865 switch (Op.getOpcode()) {
1866 default:
1867 llvm_unreachable("Unknown overflow instruction!");
1868 case ISD::SADDO:
1869 Opc = AArch64ISD::ADDS;
1870 CC = AArch64CC::VS;
1871 break;
1872 case ISD::UADDO:
1873 Opc = AArch64ISD::ADDS;
1874 CC = AArch64CC::HS;
1875 break;
1876 case ISD::SSUBO:
1877 Opc = AArch64ISD::SUBS;
1878 CC = AArch64CC::VS;
1879 break;
1880 case ISD::USUBO:
1881 Opc = AArch64ISD::SUBS;
1882 CC = AArch64CC::LO;
1883 break;
1884 // Multiply needs a little bit extra work.
1885 case ISD::SMULO:
1886 case ISD::UMULO: {
1887 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001888 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001889 if (Op.getValueType() == MVT::i32) {
1890 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1891 // For a 32 bit multiply with overflow check we want the instruction
1892 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1893 // need to generate the following pattern:
1894 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1895 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1896 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1897 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1898 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001899 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001900 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1901 // operation. We need to clear out the upper 32 bits, because we used a
1902 // widening multiply that wrote all 64 bits. In the end this should be a
1903 // noop.
1904 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1905 if (IsSigned) {
1906 // The signed overflow check requires more than just a simple check for
1907 // any bit set in the upper 32 bits of the result. These bits could be
1908 // just the sign bits of a negative number. To perform the overflow
1909 // check we have to arithmetic shift right the 32nd bit of the result by
1910 // 31 bits. Then we compare the result to the upper 32 bits.
1911 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001912 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001913 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1914 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001915 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001916 // It is important that LowerBits is last, otherwise the arithmetic
1917 // shift will not be folded into the compare (SUBS).
1918 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1919 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1920 .getValue(1);
1921 } else {
1922 // The overflow check for unsigned multiply is easy. We only need to
1923 // check if any of the upper 32 bits are set. This can be done with a
1924 // CMP (shifted register). For that we need to generate the following
1925 // pattern:
1926 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1927 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001928 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001929 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1930 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001931 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1932 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001933 UpperBits).getValue(1);
1934 }
1935 break;
1936 }
1937 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1938 // For the 64 bit multiply
1939 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1940 if (IsSigned) {
1941 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1942 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001943 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001944 // It is important that LowerBits is last, otherwise the arithmetic
1945 // shift will not be folded into the compare (SUBS).
1946 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1947 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1948 .getValue(1);
1949 } else {
1950 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1951 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1952 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001953 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1954 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001955 UpperBits).getValue(1);
1956 }
1957 break;
1958 }
1959 } // switch (...)
1960
1961 if (Opc) {
1962 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1963
1964 // Emit the AArch64 operation with overflow check.
1965 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1966 Overflow = Value.getValue(1);
1967 }
1968 return std::make_pair(Value, Overflow);
1969}
1970
1971SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1972 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001973 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001974 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001975}
1976
1977static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1978 SDValue Sel = Op.getOperand(0);
1979 SDValue Other = Op.getOperand(1);
1980
1981 // If neither operand is a SELECT_CC, give up.
1982 if (Sel.getOpcode() != ISD::SELECT_CC)
1983 std::swap(Sel, Other);
1984 if (Sel.getOpcode() != ISD::SELECT_CC)
1985 return Op;
1986
1987 // The folding we want to perform is:
1988 // (xor x, (select_cc a, b, cc, 0, -1) )
1989 // -->
1990 // (csel x, (xor x, -1), cc ...)
1991 //
1992 // The latter will get matched to a CSINV instruction.
1993
1994 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1995 SDValue LHS = Sel.getOperand(0);
1996 SDValue RHS = Sel.getOperand(1);
1997 SDValue TVal = Sel.getOperand(2);
1998 SDValue FVal = Sel.getOperand(3);
1999 SDLoc dl(Sel);
2000
2001 // FIXME: This could be generalized to non-integer comparisons.
2002 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2003 return Op;
2004
2005 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2006 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2007
Eric Christopher572e03a2015-06-19 01:53:21 +00002008 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002009 if (!CFVal || !CTVal)
2010 return Op;
2011
2012 // We can commute the SELECT_CC by inverting the condition. This
2013 // might be needed to make this fit into a CSINV pattern.
2014 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2015 std::swap(TVal, FVal);
2016 std::swap(CTVal, CFVal);
2017 CC = ISD::getSetCCInverse(CC, true);
2018 }
2019
2020 // If the constants line up, perform the transform!
2021 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2022 SDValue CCVal;
2023 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2024
2025 FVal = Other;
2026 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002027 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002028
2029 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2030 CCVal, Cmp);
2031 }
2032
2033 return Op;
2034}
2035
2036static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2037 EVT VT = Op.getValueType();
2038
2039 // Let legalize expand this if it isn't a legal type yet.
2040 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2041 return SDValue();
2042
2043 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2044
2045 unsigned Opc;
2046 bool ExtraOp = false;
2047 switch (Op.getOpcode()) {
2048 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002049 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002050 case ISD::ADDC:
2051 Opc = AArch64ISD::ADDS;
2052 break;
2053 case ISD::SUBC:
2054 Opc = AArch64ISD::SUBS;
2055 break;
2056 case ISD::ADDE:
2057 Opc = AArch64ISD::ADCS;
2058 ExtraOp = true;
2059 break;
2060 case ISD::SUBE:
2061 Opc = AArch64ISD::SBCS;
2062 ExtraOp = true;
2063 break;
2064 }
2065
2066 if (!ExtraOp)
2067 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2068 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2069 Op.getOperand(2));
2070}
2071
2072static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2073 // Let legalize expand this if it isn't a legal type yet.
2074 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2075 return SDValue();
2076
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002077 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002078 AArch64CC::CondCode CC;
2079 // The actual operation that sets the overflow or carry flag.
2080 SDValue Value, Overflow;
2081 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2082
2083 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002084 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2085 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002086
2087 // We use an inverted condition, because the conditional select is inverted
2088 // too. This will allow it to be selected to a single instruction:
2089 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002090 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2091 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002092 CCVal, Overflow);
2093
2094 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002095 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002096}
2097
2098// Prefetch operands are:
2099// 1: Address to prefetch
2100// 2: bool isWrite
2101// 3: int locality (0 = no locality ... 3 = extreme locality)
2102// 4: bool isDataCache
2103static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2104 SDLoc DL(Op);
2105 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2106 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002107 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002108
2109 bool IsStream = !Locality;
2110 // When the locality number is set
2111 if (Locality) {
2112 // The front-end should have filtered out the out-of-range values
2113 assert(Locality <= 3 && "Prefetch locality out-of-range");
2114 // The locality degree is the opposite of the cache speed.
2115 // Put the number the other way around.
2116 // The encoding starts at 0 for level 1
2117 Locality = 3 - Locality;
2118 }
2119
2120 // built the mask value encoding the expected behavior.
2121 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002122 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002123 (Locality << 1) | // Cache level bits
2124 (unsigned)IsStream; // Stream bit
2125 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002126 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002127}
2128
2129SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2130 SelectionDAG &DAG) const {
2131 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2132
2133 RTLIB::Libcall LC;
2134 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2135
2136 return LowerF128Call(Op, DAG, LC);
2137}
2138
2139SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2140 SelectionDAG &DAG) const {
2141 if (Op.getOperand(0).getValueType() != MVT::f128) {
2142 // It's legal except when f128 is involved
2143 return Op;
2144 }
2145
2146 RTLIB::Libcall LC;
2147 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2148
2149 // FP_ROUND node has a second operand indicating whether it is known to be
2150 // precise. That doesn't take part in the LibCall so we can't directly use
2151 // LowerF128Call.
2152 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002153 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2154 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002155}
2156
2157static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2158 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2159 // Any additional optimization in this function should be recorded
2160 // in the cost tables.
2161 EVT InVT = Op.getOperand(0).getValueType();
2162 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002163 unsigned NumElts = InVT.getVectorNumElements();
2164
2165 // f16 vectors are promoted to f32 before a conversion.
2166 if (InVT.getVectorElementType() == MVT::f16) {
2167 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2168 SDLoc dl(Op);
2169 return DAG.getNode(
2170 Op.getOpcode(), dl, Op.getValueType(),
2171 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2172 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002173
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002174 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002175 SDLoc dl(Op);
2176 SDValue Cv =
2177 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2178 Op.getOperand(0));
2179 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002180 }
2181
2182 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002183 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002184 MVT ExtVT =
2185 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2186 VT.getVectorNumElements());
2187 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002188 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2189 }
2190
2191 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002192 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002193}
2194
2195SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2196 SelectionDAG &DAG) const {
2197 if (Op.getOperand(0).getValueType().isVector())
2198 return LowerVectorFP_TO_INT(Op, DAG);
2199
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002200 // f16 conversions are promoted to f32 when full fp16 is not supported.
2201 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2202 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002203 SDLoc dl(Op);
2204 return DAG.getNode(
2205 Op.getOpcode(), dl, Op.getValueType(),
2206 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2207 }
2208
Tim Northover3b0846e2014-05-24 12:50:23 +00002209 if (Op.getOperand(0).getValueType() != MVT::f128) {
2210 // It's legal except when f128 is involved
2211 return Op;
2212 }
2213
2214 RTLIB::Libcall LC;
2215 if (Op.getOpcode() == ISD::FP_TO_SINT)
2216 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2217 else
2218 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2219
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002220 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002221 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002222}
2223
2224static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2225 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2226 // Any additional optimization in this function should be recorded
2227 // in the cost tables.
2228 EVT VT = Op.getValueType();
2229 SDLoc dl(Op);
2230 SDValue In = Op.getOperand(0);
2231 EVT InVT = In.getValueType();
2232
Tim Northoveref0d7602014-06-15 09:27:06 +00002233 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2234 MVT CastVT =
2235 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2236 InVT.getVectorNumElements());
2237 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002238 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002239 }
2240
Tim Northoveref0d7602014-06-15 09:27:06 +00002241 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2242 unsigned CastOpc =
2243 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2244 EVT CastVT = VT.changeVectorElementTypeToInteger();
2245 In = DAG.getNode(CastOpc, dl, CastVT, In);
2246 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002247 }
2248
Tim Northoveref0d7602014-06-15 09:27:06 +00002249 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002250}
2251
2252SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2253 SelectionDAG &DAG) const {
2254 if (Op.getValueType().isVector())
2255 return LowerVectorINT_TO_FP(Op, DAG);
2256
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002257 // f16 conversions are promoted to f32 when full fp16 is not supported.
2258 if (Op.getValueType() == MVT::f16 &&
2259 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002260 SDLoc dl(Op);
2261 return DAG.getNode(
2262 ISD::FP_ROUND, dl, MVT::f16,
2263 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002264 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002265 }
2266
Tim Northover3b0846e2014-05-24 12:50:23 +00002267 // i128 conversions are libcalls.
2268 if (Op.getOperand(0).getValueType() == MVT::i128)
2269 return SDValue();
2270
2271 // Other conversions are legal, unless it's to the completely software-based
2272 // fp128.
2273 if (Op.getValueType() != MVT::f128)
2274 return Op;
2275
2276 RTLIB::Libcall LC;
2277 if (Op.getOpcode() == ISD::SINT_TO_FP)
2278 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2279 else
2280 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2281
2282 return LowerF128Call(Op, DAG, LC);
2283}
2284
2285SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2286 SelectionDAG &DAG) const {
2287 // For iOS, we want to call an alternative entry point: __sincos_stret,
2288 // which returns the values in two S / D registers.
2289 SDLoc dl(Op);
2290 SDValue Arg = Op.getOperand(0);
2291 EVT ArgVT = Arg.getValueType();
2292 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2293
2294 ArgListTy Args;
2295 ArgListEntry Entry;
2296
2297 Entry.Node = Arg;
2298 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002299 Entry.IsSExt = false;
2300 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002301 Args.push_back(Entry);
2302
2303 const char *LibcallName =
2304 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002305 SDValue Callee =
2306 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002307
Serge Gueltone38003f2017-05-09 19:31:13 +00002308 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002309 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002310 CLI.setDebugLoc(dl)
2311 .setChain(DAG.getEntryNode())
2312 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002313
2314 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2315 return CallResult.first;
2316}
2317
Tim Northoverf8bfe212014-07-18 13:07:05 +00002318static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2319 if (Op.getValueType() != MVT::f16)
2320 return SDValue();
2321
2322 assert(Op.getOperand(0).getValueType() == MVT::i16);
2323 SDLoc DL(Op);
2324
2325 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2326 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2327 return SDValue(
2328 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002329 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002330 0);
2331}
2332
Chad Rosierd9d0f862014-10-08 02:31:24 +00002333static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2334 if (OrigVT.getSizeInBits() >= 64)
2335 return OrigVT;
2336
2337 assert(OrigVT.isSimple() && "Expecting a simple value type");
2338
2339 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2340 switch (OrigSimpleTy) {
2341 default: llvm_unreachable("Unexpected Vector Type");
2342 case MVT::v2i8:
2343 case MVT::v2i16:
2344 return MVT::v2i32;
2345 case MVT::v4i8:
2346 return MVT::v4i16;
2347 }
2348}
2349
2350static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2351 const EVT &OrigTy,
2352 const EVT &ExtTy,
2353 unsigned ExtOpcode) {
2354 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2355 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2356 // 64-bits we need to insert a new extension so that it will be 64-bits.
2357 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2358 if (OrigTy.getSizeInBits() >= 64)
2359 return N;
2360
2361 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2362 EVT NewVT = getExtensionTo64Bits(OrigTy);
2363
2364 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2365}
2366
2367static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2368 bool isSigned) {
2369 EVT VT = N->getValueType(0);
2370
2371 if (N->getOpcode() != ISD::BUILD_VECTOR)
2372 return false;
2373
Pete Cooper3af9a252015-06-26 18:17:36 +00002374 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002375 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002376 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002377 unsigned HalfSize = EltSize / 2;
2378 if (isSigned) {
2379 if (!isIntN(HalfSize, C->getSExtValue()))
2380 return false;
2381 } else {
2382 if (!isUIntN(HalfSize, C->getZExtValue()))
2383 return false;
2384 }
2385 continue;
2386 }
2387 return false;
2388 }
2389
2390 return true;
2391}
2392
2393static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2394 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2395 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2396 N->getOperand(0)->getValueType(0),
2397 N->getValueType(0),
2398 N->getOpcode());
2399
2400 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2401 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002402 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002403 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002404 unsigned NumElts = VT.getVectorNumElements();
2405 MVT TruncVT = MVT::getIntegerVT(EltSize);
2406 SmallVector<SDValue, 8> Ops;
2407 for (unsigned i = 0; i != NumElts; ++i) {
2408 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2409 const APInt &CInt = C->getAPIntValue();
2410 // Element types smaller than 32 bits are not legal, so use i32 elements.
2411 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002412 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002413 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002414 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002415}
2416
2417static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002418 return N->getOpcode() == ISD::SIGN_EXTEND ||
2419 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002420}
2421
2422static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002423 return N->getOpcode() == ISD::ZERO_EXTEND ||
2424 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002425}
2426
2427static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2428 unsigned Opcode = N->getOpcode();
2429 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2430 SDNode *N0 = N->getOperand(0).getNode();
2431 SDNode *N1 = N->getOperand(1).getNode();
2432 return N0->hasOneUse() && N1->hasOneUse() &&
2433 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2434 }
2435 return false;
2436}
2437
2438static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2439 unsigned Opcode = N->getOpcode();
2440 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2441 SDNode *N0 = N->getOperand(0).getNode();
2442 SDNode *N1 = N->getOperand(1).getNode();
2443 return N0->hasOneUse() && N1->hasOneUse() &&
2444 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2445 }
2446 return false;
2447}
2448
2449static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2450 // Multiplications are only custom-lowered for 128-bit vectors so that
2451 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2452 EVT VT = Op.getValueType();
2453 assert(VT.is128BitVector() && VT.isInteger() &&
2454 "unexpected type for custom-lowering ISD::MUL");
2455 SDNode *N0 = Op.getOperand(0).getNode();
2456 SDNode *N1 = Op.getOperand(1).getNode();
2457 unsigned NewOpc = 0;
2458 bool isMLA = false;
2459 bool isN0SExt = isSignExtended(N0, DAG);
2460 bool isN1SExt = isSignExtended(N1, DAG);
2461 if (isN0SExt && isN1SExt)
2462 NewOpc = AArch64ISD::SMULL;
2463 else {
2464 bool isN0ZExt = isZeroExtended(N0, DAG);
2465 bool isN1ZExt = isZeroExtended(N1, DAG);
2466 if (isN0ZExt && isN1ZExt)
2467 NewOpc = AArch64ISD::UMULL;
2468 else if (isN1SExt || isN1ZExt) {
2469 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2470 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2471 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2472 NewOpc = AArch64ISD::SMULL;
2473 isMLA = true;
2474 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2475 NewOpc = AArch64ISD::UMULL;
2476 isMLA = true;
2477 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2478 std::swap(N0, N1);
2479 NewOpc = AArch64ISD::UMULL;
2480 isMLA = true;
2481 }
2482 }
2483
2484 if (!NewOpc) {
2485 if (VT == MVT::v2i64)
2486 // Fall through to expand this. It is not legal.
2487 return SDValue();
2488 else
2489 // Other vector multiplications are legal.
2490 return Op;
2491 }
2492 }
2493
2494 // Legalize to a S/UMULL instruction
2495 SDLoc DL(Op);
2496 SDValue Op0;
2497 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2498 if (!isMLA) {
2499 Op0 = skipExtensionForVectorMULL(N0, DAG);
2500 assert(Op0.getValueType().is64BitVector() &&
2501 Op1.getValueType().is64BitVector() &&
2502 "unexpected types for extended operands to VMULL");
2503 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2504 }
2505 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2506 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2507 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2508 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2509 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2510 EVT Op1VT = Op1.getValueType();
2511 return DAG.getNode(N0->getOpcode(), DL, VT,
2512 DAG.getNode(NewOpc, DL, VT,
2513 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2514 DAG.getNode(NewOpc, DL, VT,
2515 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2516}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002517
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002518SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2519 SelectionDAG &DAG) const {
2520 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2521 SDLoc dl(Op);
2522 switch (IntNo) {
2523 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002524 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002525 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2526 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2527 }
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +00002528 case Intrinsic::aarch64_neon_abs:
2529 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2530 Op.getOperand(1));
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002531 case Intrinsic::aarch64_neon_smax:
2532 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2533 Op.getOperand(1), Op.getOperand(2));
2534 case Intrinsic::aarch64_neon_umax:
2535 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2536 Op.getOperand(1), Op.getOperand(2));
2537 case Intrinsic::aarch64_neon_smin:
2538 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2539 Op.getOperand(1), Op.getOperand(2));
2540 case Intrinsic::aarch64_neon_umin:
2541 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2542 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002543 }
2544}
2545
Tim Northover3b0846e2014-05-24 12:50:23 +00002546SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2547 SelectionDAG &DAG) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002548 DEBUG(dbgs() << "Custom lowering: ");
2549 DEBUG(Op.dump());
2550
Tim Northover3b0846e2014-05-24 12:50:23 +00002551 switch (Op.getOpcode()) {
2552 default:
2553 llvm_unreachable("unimplemented operand");
2554 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002555 case ISD::BITCAST:
2556 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002557 case ISD::GlobalAddress:
2558 return LowerGlobalAddress(Op, DAG);
2559 case ISD::GlobalTLSAddress:
2560 return LowerGlobalTLSAddress(Op, DAG);
2561 case ISD::SETCC:
2562 return LowerSETCC(Op, DAG);
2563 case ISD::BR_CC:
2564 return LowerBR_CC(Op, DAG);
2565 case ISD::SELECT:
2566 return LowerSELECT(Op, DAG);
2567 case ISD::SELECT_CC:
2568 return LowerSELECT_CC(Op, DAG);
2569 case ISD::JumpTable:
2570 return LowerJumpTable(Op, DAG);
2571 case ISD::ConstantPool:
2572 return LowerConstantPool(Op, DAG);
2573 case ISD::BlockAddress:
2574 return LowerBlockAddress(Op, DAG);
2575 case ISD::VASTART:
2576 return LowerVASTART(Op, DAG);
2577 case ISD::VACOPY:
2578 return LowerVACOPY(Op, DAG);
2579 case ISD::VAARG:
2580 return LowerVAARG(Op, DAG);
2581 case ISD::ADDC:
2582 case ISD::ADDE:
2583 case ISD::SUBC:
2584 case ISD::SUBE:
2585 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2586 case ISD::SADDO:
2587 case ISD::UADDO:
2588 case ISD::SSUBO:
2589 case ISD::USUBO:
2590 case ISD::SMULO:
2591 case ISD::UMULO:
2592 return LowerXALUO(Op, DAG);
2593 case ISD::FADD:
2594 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2595 case ISD::FSUB:
2596 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2597 case ISD::FMUL:
2598 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2599 case ISD::FDIV:
2600 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2601 case ISD::FP_ROUND:
2602 return LowerFP_ROUND(Op, DAG);
2603 case ISD::FP_EXTEND:
2604 return LowerFP_EXTEND(Op, DAG);
2605 case ISD::FRAMEADDR:
2606 return LowerFRAMEADDR(Op, DAG);
2607 case ISD::RETURNADDR:
2608 return LowerRETURNADDR(Op, DAG);
2609 case ISD::INSERT_VECTOR_ELT:
2610 return LowerINSERT_VECTOR_ELT(Op, DAG);
2611 case ISD::EXTRACT_VECTOR_ELT:
2612 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2613 case ISD::BUILD_VECTOR:
2614 return LowerBUILD_VECTOR(Op, DAG);
2615 case ISD::VECTOR_SHUFFLE:
2616 return LowerVECTOR_SHUFFLE(Op, DAG);
2617 case ISD::EXTRACT_SUBVECTOR:
2618 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2619 case ISD::SRA:
2620 case ISD::SRL:
2621 case ISD::SHL:
2622 return LowerVectorSRA_SRL_SHL(Op, DAG);
2623 case ISD::SHL_PARTS:
2624 return LowerShiftLeftParts(Op, DAG);
2625 case ISD::SRL_PARTS:
2626 case ISD::SRA_PARTS:
2627 return LowerShiftRightParts(Op, DAG);
2628 case ISD::CTPOP:
2629 return LowerCTPOP(Op, DAG);
2630 case ISD::FCOPYSIGN:
2631 return LowerFCOPYSIGN(Op, DAG);
2632 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002633 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002634 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002635 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002636 case ISD::XOR:
2637 return LowerXOR(Op, DAG);
2638 case ISD::PREFETCH:
2639 return LowerPREFETCH(Op, DAG);
2640 case ISD::SINT_TO_FP:
2641 case ISD::UINT_TO_FP:
2642 return LowerINT_TO_FP(Op, DAG);
2643 case ISD::FP_TO_SINT:
2644 case ISD::FP_TO_UINT:
2645 return LowerFP_TO_INT(Op, DAG);
2646 case ISD::FSINCOS:
2647 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002648 case ISD::MUL:
2649 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002650 case ISD::INTRINSIC_WO_CHAIN:
2651 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002652 case ISD::VECREDUCE_ADD:
2653 case ISD::VECREDUCE_SMAX:
2654 case ISD::VECREDUCE_SMIN:
2655 case ISD::VECREDUCE_UMAX:
2656 case ISD::VECREDUCE_UMIN:
2657 case ISD::VECREDUCE_FMAX:
2658 case ISD::VECREDUCE_FMIN:
2659 return LowerVECREDUCE(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002660 }
2661}
2662
Tim Northover3b0846e2014-05-24 12:50:23 +00002663//===----------------------------------------------------------------------===//
2664// Calling Convention Implementation
2665//===----------------------------------------------------------------------===//
2666
2667#include "AArch64GenCallingConv.inc"
2668
Robin Morisset039781e2014-08-29 21:53:01 +00002669/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002670CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2671 bool IsVarArg) const {
2672 switch (CC) {
2673 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002674 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002675 case CallingConv::WebKit_JS:
2676 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002677 case CallingConv::GHC:
2678 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002679 case CallingConv::C:
2680 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002681 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002682 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002683 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002684 if (Subtarget->isTargetWindows() && IsVarArg)
2685 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002686 if (!Subtarget->isTargetDarwin())
2687 return CC_AArch64_AAPCS;
2688 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002689 case CallingConv::Win64:
2690 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002691 }
2692}
2693
Tim Northover406024a2016-08-10 21:44:01 +00002694CCAssignFn *
2695AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2696 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2697 : RetCC_AArch64_AAPCS;
2698}
2699
Tim Northover3b0846e2014-05-24 12:50:23 +00002700SDValue AArch64TargetLowering::LowerFormalArguments(
2701 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002702 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2703 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002704 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002705 MachineFrameInfo &MFI = MF.getFrameInfo();
Martin Storsjo2f24e932017-07-17 20:05:19 +00002706 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002707
2708 // Assign locations to all of the incoming arguments.
2709 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002710 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2711 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002712
2713 // At this point, Ins[].VT may already be promoted to i32. To correctly
2714 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2715 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2716 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2717 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2718 // LocVT.
2719 unsigned NumArgs = Ins.size();
2720 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2721 unsigned CurArgIdx = 0;
2722 for (unsigned i = 0; i != NumArgs; ++i) {
2723 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002724 if (Ins[i].isOrigArg()) {
2725 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2726 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002727
Andrew Trick05938a52015-02-16 18:10:47 +00002728 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002729 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2730 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002731 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2732 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2733 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2734 ValVT = MVT::i8;
2735 else if (ActualMVT == MVT::i16)
2736 ValVT = MVT::i16;
2737 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002738 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2739 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002740 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002741 assert(!Res && "Call operand has unhandled type");
2742 (void)Res;
2743 }
2744 assert(ArgLocs.size() == Ins.size());
2745 SmallVector<SDValue, 16> ArgValues;
2746 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2747 CCValAssign &VA = ArgLocs[i];
2748
2749 if (Ins[i].Flags.isByVal()) {
2750 // Byval is used for HFAs in the PCS, but the system should work in a
2751 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002752 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002753 int Size = Ins[i].Flags.getByValSize();
2754 unsigned NumRegs = (Size + 7) / 8;
2755
2756 // FIXME: This works on big-endian for composite byvals, which are the common
2757 // case. It should also work for fundamental types too.
2758 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002759 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002760 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002761 InVals.push_back(FrameIdxN);
2762
2763 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002764 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002765
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002766 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002767 // Arguments stored in registers.
2768 EVT RegVT = VA.getLocVT();
2769
2770 SDValue ArgValue;
2771 const TargetRegisterClass *RC;
2772
2773 if (RegVT == MVT::i32)
2774 RC = &AArch64::GPR32RegClass;
2775 else if (RegVT == MVT::i64)
2776 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002777 else if (RegVT == MVT::f16)
2778 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002779 else if (RegVT == MVT::f32)
2780 RC = &AArch64::FPR32RegClass;
2781 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2782 RC = &AArch64::FPR64RegClass;
2783 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2784 RC = &AArch64::FPR128RegClass;
2785 else
2786 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2787
2788 // Transform the arguments in physical registers into virtual ones.
2789 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2790 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2791
2792 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2793 // to 64 bits. Insert an assert[sz]ext to capture this, then
2794 // truncate to the right size.
2795 switch (VA.getLocInfo()) {
2796 default:
2797 llvm_unreachable("Unknown loc info!");
2798 case CCValAssign::Full:
2799 break;
2800 case CCValAssign::BCvt:
2801 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2802 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002803 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002804 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002805 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002806 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2807 // nodes after our lowering.
2808 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002809 break;
2810 }
2811
2812 InVals.push_back(ArgValue);
2813
2814 } else { // VA.isRegLoc()
2815 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2816 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002817 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002818
2819 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002820 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2821 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002822 BEAlign = 8 - ArgSize;
2823
Matthias Braun941a7052016-07-28 18:40:00 +00002824 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002825
2826 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002827 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002828 SDValue ArgValue;
2829
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002830 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002831 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002832 MVT MemVT = VA.getValVT();
2833
Tim Northover47e003c2014-05-26 17:21:53 +00002834 switch (VA.getLocInfo()) {
2835 default:
2836 break;
Tim Northover6890add2014-06-03 13:54:53 +00002837 case CCValAssign::BCvt:
2838 MemVT = VA.getLocVT();
2839 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002840 case CCValAssign::SExt:
2841 ExtType = ISD::SEXTLOAD;
2842 break;
2843 case CCValAssign::ZExt:
2844 ExtType = ISD::ZEXTLOAD;
2845 break;
2846 case CCValAssign::AExt:
2847 ExtType = ISD::EXTLOAD;
2848 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002849 }
2850
Alex Lorenze40c8a22015-08-11 23:09:45 +00002851 ArgValue = DAG.getExtLoad(
2852 ExtType, DL, VA.getLocVT(), Chain, FIN,
2853 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002854 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002855
Tim Northover3b0846e2014-05-24 12:50:23 +00002856 InVals.push_back(ArgValue);
2857 }
2858 }
2859
2860 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002861 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002862 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00002863 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002864 // The AAPCS variadic function ABI is identical to the non-variadic
2865 // one. As a result there may be more arguments in registers and we should
2866 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00002867 // Win64 variadic functions also pass arguments in registers, but all float
2868 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00002869 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2870 }
2871
Tim Northover3b0846e2014-05-24 12:50:23 +00002872 // This will point to the next argument passed via stack.
2873 unsigned StackOffset = CCInfo.getNextStackOffset();
2874 // We currently pass all varargs at 8-byte alignment.
2875 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002876 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002877 }
2878
Tim Northover3b0846e2014-05-24 12:50:23 +00002879 unsigned StackArgSize = CCInfo.getNextStackOffset();
2880 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2881 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2882 // This is a non-standard ABI so by fiat I say we're allowed to make full
2883 // use of the stack area to be popped, which must be aligned to 16 bytes in
2884 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002885 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002886
2887 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2888 // a multiple of 16.
2889 FuncInfo->setArgumentStackToRestore(StackArgSize);
2890
2891 // This realignment carries over to the available bytes below. Our own
2892 // callers will guarantee the space is free by giving an aligned value to
2893 // CALLSEQ_START.
2894 }
2895 // Even if we're not expected to free up the space, it's useful to know how
2896 // much is there while considering tail calls (because we can reuse it).
2897 FuncInfo->setBytesInStackArgArea(StackArgSize);
2898
2899 return Chain;
2900}
2901
2902void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002903 SelectionDAG &DAG,
2904 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002905 SDValue &Chain) const {
2906 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002907 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002908 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002909 auto PtrVT = getPointerTy(DAG.getDataLayout());
Martin Storsjo2f24e932017-07-17 20:05:19 +00002910 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002911
2912 SmallVector<SDValue, 8> MemOps;
2913
2914 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2915 AArch64::X3, AArch64::X4, AArch64::X5,
2916 AArch64::X6, AArch64::X7 };
2917 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002918 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002919
2920 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2921 int GPRIdx = 0;
2922 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00002923 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00002924 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00002925 if (GPRSaveSize & 15)
2926 // The extra size here, if triggered, will always be 8.
2927 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
2928 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00002929 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002930
Mehdi Amini44ede332015-07-09 02:09:04 +00002931 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002932
2933 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2934 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2935 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002936 SDValue Store = DAG.getStore(
2937 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00002938 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00002939 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2940 GPRIdx,
2941 (i - FirstVariadicGPR) * 8)
2942 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002943 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002944 FIN =
2945 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002946 }
2947 }
2948 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2949 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2950
Martin Storsjo2f24e932017-07-17 20:05:19 +00002951 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002952 static const MCPhysReg FPRArgRegs[] = {
2953 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2954 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2955 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002956 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002957
2958 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2959 int FPRIdx = 0;
2960 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002961 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002962
Mehdi Amini44ede332015-07-09 02:09:04 +00002963 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002964
2965 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2966 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2967 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2968
Alex Lorenze40c8a22015-08-11 23:09:45 +00002969 SDValue Store = DAG.getStore(
2970 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002971 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002972 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002973 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2974 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002975 }
2976 }
2977 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2978 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2979 }
2980
2981 if (!MemOps.empty()) {
2982 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2983 }
2984}
2985
2986/// LowerCallResult - Lower the result values of a call into the
2987/// appropriate copies out of appropriate physical registers.
2988SDValue AArch64TargetLowering::LowerCallResult(
2989 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002990 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2991 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002992 SDValue ThisVal) const {
2993 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2994 ? RetCC_AArch64_WebKit_JS
2995 : RetCC_AArch64_AAPCS;
2996 // Assign locations to each value returned by this call.
2997 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002998 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2999 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003000 CCInfo.AnalyzeCallResult(Ins, RetCC);
3001
3002 // Copy all of the result registers out of their specified physreg.
3003 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3004 CCValAssign VA = RVLocs[i];
3005
3006 // Pass 'this' value directly from the argument to return value, to avoid
3007 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003008 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003009 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3010 "unexpected return calling convention register assignment");
3011 InVals.push_back(ThisVal);
3012 continue;
3013 }
3014
3015 SDValue Val =
3016 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3017 Chain = Val.getValue(1);
3018 InFlag = Val.getValue(2);
3019
3020 switch (VA.getLocInfo()) {
3021 default:
3022 llvm_unreachable("Unknown loc info!");
3023 case CCValAssign::Full:
3024 break;
3025 case CCValAssign::BCvt:
3026 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3027 break;
3028 }
3029
3030 InVals.push_back(Val);
3031 }
3032
3033 return Chain;
3034}
3035
Matthias Braun1af14142016-09-13 19:27:38 +00003036/// Return true if the calling convention is one that we can guarantee TCO for.
3037static bool canGuaranteeTCO(CallingConv::ID CC) {
3038 return CC == CallingConv::Fast;
3039}
3040
3041/// Return true if we might ever do TCO for calls with this calling convention.
3042static bool mayTailCallThisCC(CallingConv::ID CC) {
3043 switch (CC) {
3044 case CallingConv::C:
3045 case CallingConv::PreserveMost:
3046 case CallingConv::Swift:
3047 return true;
3048 default:
3049 return canGuaranteeTCO(CC);
3050 }
3051}
3052
Tim Northover3b0846e2014-05-24 12:50:23 +00003053bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3054 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003055 const SmallVectorImpl<ISD::OutputArg> &Outs,
3056 const SmallVectorImpl<SDValue> &OutVals,
3057 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003058 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003059 return false;
3060
Matthias Braun8d414362016-03-30 22:46:04 +00003061 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003062 const Function *CallerF = MF.getFunction();
3063 CallingConv::ID CallerCC = CallerF->getCallingConv();
3064 bool CCMatch = CallerCC == CalleeCC;
3065
3066 // Byval parameters hand the function a pointer directly into the stack area
3067 // we want to reuse during a tail call. Working around this *is* possible (see
3068 // X86) but less efficient and uglier in LowerCall.
3069 for (Function::const_arg_iterator i = CallerF->arg_begin(),
3070 e = CallerF->arg_end();
3071 i != e; ++i)
3072 if (i->hasByValAttr())
3073 return false;
3074
Matthias Braun1af14142016-09-13 19:27:38 +00003075 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3076 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003077
Oliver Stannard12993dd2014-08-18 12:42:15 +00003078 // Externally-defined functions with weak linkage should not be
3079 // tail-called on AArch64 when the OS does not support dynamic
3080 // pre-emption of symbols, as the AAELF spec requires normal calls
3081 // to undefined weak functions to be replaced with a NOP or jump to the
3082 // next instruction. The behaviour of branch instructions in this
3083 // situation (as used for tail calls) is implementation-defined, so we
3084 // cannot rely on the linker replacing the tail call with a return.
3085 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3086 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003087 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003088 if (GV->hasExternalWeakLinkage() &&
3089 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003090 return false;
3091 }
3092
Tim Northover3b0846e2014-05-24 12:50:23 +00003093 // Now we search for cases where we can use a tail call without changing the
3094 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3095 // concept.
3096
3097 // I want anyone implementing a new calling convention to think long and hard
3098 // about this assert.
3099 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3100 "Unexpected variadic calling convention");
3101
Matthias Braun8d414362016-03-30 22:46:04 +00003102 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003103 if (isVarArg && !Outs.empty()) {
3104 // At least two cases here: if caller is fastcc then we can't have any
3105 // memory arguments (we'd be expected to clean up the stack afterwards). If
3106 // caller is C then we could potentially use its argument area.
3107
3108 // FIXME: for now we take the most conservative of these in both cases:
3109 // disallow all variadic memory operands.
3110 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003111 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003112
3113 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003114 for (const CCValAssign &ArgLoc : ArgLocs)
3115 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003116 return false;
3117 }
3118
Matthias Braun8d414362016-03-30 22:46:04 +00003119 // Check that the call results are passed in the same way.
3120 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3121 CCAssignFnForCall(CalleeCC, isVarArg),
3122 CCAssignFnForCall(CallerCC, isVarArg)))
3123 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003124 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003125 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3126 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003127 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003128 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3129 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003130 return false;
3131 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003132
3133 // Nothing more to check if the callee is taking no arguments
3134 if (Outs.empty())
3135 return true;
3136
3137 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003138 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003139
3140 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3141
3142 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3143
Matthias Braun74a0bd32016-04-13 21:43:16 +00003144 // If the stack arguments for this call do not fit into our own save area then
3145 // the call cannot be made tail.
3146 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3147 return false;
3148
Matthias Braun46b0f032016-04-14 01:10:42 +00003149 const MachineRegisterInfo &MRI = MF.getRegInfo();
3150 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3151 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003152
3153 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003154}
3155
3156SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3157 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003158 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003159 int ClobberedFI) const {
3160 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003161 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3162 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003163
3164 // Include the original chain at the beginning of the list. When this is
3165 // used by target LowerCall hooks, this helps legalize find the
3166 // CALLSEQ_BEGIN node.
3167 ArgChains.push_back(Chain);
3168
3169 // Add a chain value for each stack argument corresponding
3170 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3171 UE = DAG.getEntryNode().getNode()->use_end();
3172 U != UE; ++U)
3173 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3174 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3175 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003176 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003177 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003178 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003179
3180 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3181 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3182 ArgChains.push_back(SDValue(L, 1));
3183 }
3184
3185 // Build a tokenfactor for all the chains.
3186 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3187}
3188
3189bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3190 bool TailCallOpt) const {
3191 return CallCC == CallingConv::Fast && TailCallOpt;
3192}
3193
Tim Northover3b0846e2014-05-24 12:50:23 +00003194/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3195/// and add input and output parameter nodes.
3196SDValue
3197AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3198 SmallVectorImpl<SDValue> &InVals) const {
3199 SelectionDAG &DAG = CLI.DAG;
3200 SDLoc &DL = CLI.DL;
3201 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3202 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3203 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3204 SDValue Chain = CLI.Chain;
3205 SDValue Callee = CLI.Callee;
3206 bool &IsTailCall = CLI.IsTailCall;
3207 CallingConv::ID CallConv = CLI.CallConv;
3208 bool IsVarArg = CLI.IsVarArg;
3209
3210 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003211 bool IsThisReturn = false;
3212
3213 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3214 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3215 bool IsSibCall = false;
3216
3217 if (IsTailCall) {
3218 // Check if it's really possible to do a tail call.
3219 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003220 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003221 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003222 report_fatal_error("failed to perform tail call elimination on a call "
3223 "site marked musttail");
3224
3225 // A sibling call is one where we're under the usual C ABI and not planning
3226 // to change that but can still do a tail call:
3227 if (!TailCallOpt && IsTailCall)
3228 IsSibCall = true;
3229
3230 if (IsTailCall)
3231 ++NumTailCalls;
3232 }
3233
3234 // Analyze operands of the call, assigning locations to each operand.
3235 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003236 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3237 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003238
3239 if (IsVarArg) {
3240 // Handle fixed and variable vector arguments differently.
3241 // Variable vector arguments always go into memory.
3242 unsigned NumArgs = Outs.size();
3243
3244 for (unsigned i = 0; i != NumArgs; ++i) {
3245 MVT ArgVT = Outs[i].VT;
3246 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3247 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3248 /*IsVarArg=*/ !Outs[i].IsFixed);
3249 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3250 assert(!Res && "Call operand has unhandled type");
3251 (void)Res;
3252 }
3253 } else {
3254 // At this point, Outs[].VT may already be promoted to i32. To correctly
3255 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3256 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3257 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3258 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3259 // LocVT.
3260 unsigned NumArgs = Outs.size();
3261 for (unsigned i = 0; i != NumArgs; ++i) {
3262 MVT ValVT = Outs[i].VT;
3263 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003264 EVT ActualVT = getValueType(DAG.getDataLayout(),
3265 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003266 /*AllowUnknown*/ true);
3267 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3268 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3269 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003270 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003271 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003272 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003273 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003274
3275 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003276 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003277 assert(!Res && "Call operand has unhandled type");
3278 (void)Res;
3279 }
3280 }
3281
3282 // Get a count of how many bytes are to be pushed on the stack.
3283 unsigned NumBytes = CCInfo.getNextStackOffset();
3284
3285 if (IsSibCall) {
3286 // Since we're not changing the ABI to make this a tail call, the memory
3287 // operands are already available in the caller's incoming argument space.
3288 NumBytes = 0;
3289 }
3290
3291 // FPDiff is the byte offset of the call's argument area from the callee's.
3292 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3293 // by this amount for a tail call. In a sibling call it must be 0 because the
3294 // caller will deallocate the entire stack and the callee still expects its
3295 // arguments to begin at SP+0. Completely unused for non-tail calls.
3296 int FPDiff = 0;
3297
3298 if (IsTailCall && !IsSibCall) {
3299 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3300
3301 // Since callee will pop argument stack as a tail call, we must keep the
3302 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003303 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003304
3305 // FPDiff will be negative if this tail call requires more space than we
3306 // would automatically have in our incoming argument space. Positive if we
3307 // can actually shrink the stack.
3308 FPDiff = NumReusableBytes - NumBytes;
3309
3310 // The stack pointer must be 16-byte aligned at all times it's used for a
3311 // memory operation, which in practice means at *all* times and in
3312 // particular across call boundaries. Therefore our own arguments started at
3313 // a 16-byte aligned SP and the delta applied for the tail call should
3314 // satisfy the same constraint.
3315 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3316 }
3317
3318 // Adjust the stack pointer for the new arguments...
3319 // These operations are automatically eliminated by the prolog/epilog pass
3320 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003321 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003322
Mehdi Amini44ede332015-07-09 02:09:04 +00003323 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3324 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003325
3326 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3327 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003328 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003329
3330 // Walk the register/memloc assignments, inserting copies/loads.
3331 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3332 ++i, ++realArgIdx) {
3333 CCValAssign &VA = ArgLocs[i];
3334 SDValue Arg = OutVals[realArgIdx];
3335 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3336
3337 // Promote the value if needed.
3338 switch (VA.getLocInfo()) {
3339 default:
3340 llvm_unreachable("Unknown loc info!");
3341 case CCValAssign::Full:
3342 break;
3343 case CCValAssign::SExt:
3344 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3345 break;
3346 case CCValAssign::ZExt:
3347 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3348 break;
3349 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003350 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3351 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3352 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3353 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3354 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003355 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3356 break;
3357 case CCValAssign::BCvt:
3358 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3359 break;
3360 case CCValAssign::FPExt:
3361 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3362 break;
3363 }
3364
3365 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003366 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3367 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003368 assert(VA.getLocVT() == MVT::i64 &&
3369 "unexpected calling convention register assignment");
3370 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3371 "unexpected use of 'returned'");
3372 IsThisReturn = true;
3373 }
3374 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3375 } else {
3376 assert(VA.isMemLoc());
3377
3378 SDValue DstAddr;
3379 MachinePointerInfo DstInfo;
3380
3381 // FIXME: This works on big-endian for composite byvals, which are the
3382 // common case. It should also work for fundamental types too.
3383 uint32_t BEAlign = 0;
3384 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003385 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003386 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003387 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3388 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003389 if (OpSize < 8)
3390 BEAlign = 8 - OpSize;
3391 }
3392 unsigned LocMemOffset = VA.getLocMemOffset();
3393 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003394 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003395 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003396
3397 if (IsTailCall) {
3398 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003399 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003400
Mehdi Amini44ede332015-07-09 02:09:04 +00003401 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003402 DstInfo =
3403 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003404
3405 // Make sure any stack arguments overlapping with where we're storing
3406 // are loaded before this eventual operation. Otherwise they'll be
3407 // clobbered.
3408 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3409 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003410 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003411
Mehdi Amini44ede332015-07-09 02:09:04 +00003412 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003413 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3414 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003415 }
3416
3417 if (Outs[i].Flags.isByVal()) {
3418 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003419 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003420 SDValue Cpy = DAG.getMemcpy(
3421 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003422 /*isVol = */ false, /*AlwaysInline = */ false,
3423 /*isTailCall = */ false,
3424 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003425
3426 MemOpChains.push_back(Cpy);
3427 } else {
3428 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3429 // promoted to a legal register type i32, we should truncate Arg back to
3430 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003431 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3432 VA.getValVT() == MVT::i16)
3433 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003434
Justin Lebar9c375812016-07-15 18:27:10 +00003435 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003436 MemOpChains.push_back(Store);
3437 }
3438 }
3439 }
3440
3441 if (!MemOpChains.empty())
3442 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3443
3444 // Build a sequence of copy-to-reg nodes chained together with token chain
3445 // and flag operands which copy the outgoing args into the appropriate regs.
3446 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003447 for (auto &RegToPass : RegsToPass) {
3448 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3449 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003450 InFlag = Chain.getValue(1);
3451 }
3452
3453 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3454 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3455 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003456 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3457 auto GV = G->getGlobal();
3458 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3459 AArch64II::MO_GOT) {
3460 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3461 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3462 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003463 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003464 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3465 }
3466 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3467 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3468 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003469 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003470 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3471 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003472 } else {
3473 const char *Sym = S->getSymbol();
3474 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003475 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003476 }
3477
3478 // We don't usually want to end the call-sequence here because we would tidy
3479 // the frame up *after* the call, however in the ABI-changing tail-call case
3480 // we've carefully laid out the parameters so that when sp is reset they'll be
3481 // in the correct location.
3482 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003483 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3484 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003485 InFlag = Chain.getValue(1);
3486 }
3487
3488 std::vector<SDValue> Ops;
3489 Ops.push_back(Chain);
3490 Ops.push_back(Callee);
3491
3492 if (IsTailCall) {
3493 // Each tail call may have to adjust the stack by a different amount, so
3494 // this information must travel along with the operation for eventual
3495 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003496 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003497 }
3498
3499 // Add argument registers to the end of the list so that they are known live
3500 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003501 for (auto &RegToPass : RegsToPass)
3502 Ops.push_back(DAG.getRegister(RegToPass.first,
3503 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003504
3505 // Add a register mask operand representing the call-preserved registers.
3506 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003507 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003508 if (IsThisReturn) {
3509 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003510 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003511 if (!Mask) {
3512 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003513 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003514 }
3515 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003516 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003517
3518 assert(Mask && "Missing call preserved mask for calling convention");
3519 Ops.push_back(DAG.getRegisterMask(Mask));
3520
3521 if (InFlag.getNode())
3522 Ops.push_back(InFlag);
3523
3524 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3525
3526 // If we're doing a tall call, use a TC_RETURN here rather than an
3527 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003528 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003529 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003530 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003531 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003532
3533 // Returns a chain and a flag for retval copy to use.
3534 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3535 InFlag = Chain.getValue(1);
3536
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003537 uint64_t CalleePopBytes =
3538 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003539
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003540 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3541 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003542 InFlag, DL);
3543 if (!Ins.empty())
3544 InFlag = Chain.getValue(1);
3545
3546 // Handle result values, copying them out of physregs into vregs that we
3547 // return.
3548 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3549 InVals, IsThisReturn,
3550 IsThisReturn ? OutVals[0] : SDValue());
3551}
3552
3553bool AArch64TargetLowering::CanLowerReturn(
3554 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3555 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3556 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3557 ? RetCC_AArch64_WebKit_JS
3558 : RetCC_AArch64_AAPCS;
3559 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003560 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003561 return CCInfo.CheckReturn(Outs, RetCC);
3562}
3563
3564SDValue
3565AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3566 bool isVarArg,
3567 const SmallVectorImpl<ISD::OutputArg> &Outs,
3568 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003569 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003570 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3571 ? RetCC_AArch64_WebKit_JS
3572 : RetCC_AArch64_AAPCS;
3573 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003574 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3575 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003576 CCInfo.AnalyzeReturn(Outs, RetCC);
3577
3578 // Copy the result values into the output registers.
3579 SDValue Flag;
3580 SmallVector<SDValue, 4> RetOps(1, Chain);
3581 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3582 ++i, ++realRVLocIdx) {
3583 CCValAssign &VA = RVLocs[i];
3584 assert(VA.isRegLoc() && "Can only return in registers!");
3585 SDValue Arg = OutVals[realRVLocIdx];
3586
3587 switch (VA.getLocInfo()) {
3588 default:
3589 llvm_unreachable("Unknown loc info!");
3590 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003591 if (Outs[i].ArgVT == MVT::i1) {
3592 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3593 // value. This is strictly redundant on Darwin (which uses "zeroext
3594 // i1"), but will be optimised out before ISel.
3595 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3596 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3597 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003598 break;
3599 case CCValAssign::BCvt:
3600 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3601 break;
3602 }
3603
3604 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3605 Flag = Chain.getValue(1);
3606 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3607 }
Manman Rencbe4f942015-12-16 21:04:19 +00003608 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3609 const MCPhysReg *I =
3610 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3611 if (I) {
3612 for (; *I; ++I) {
3613 if (AArch64::GPR64RegClass.contains(*I))
3614 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3615 else if (AArch64::FPR64RegClass.contains(*I))
3616 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3617 else
3618 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3619 }
3620 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003621
3622 RetOps[0] = Chain; // Update chain.
3623
3624 // Add the flag if we have it.
3625 if (Flag.getNode())
3626 RetOps.push_back(Flag);
3627
3628 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3629}
3630
3631//===----------------------------------------------------------------------===//
3632// Other Lowering Code
3633//===----------------------------------------------------------------------===//
3634
Joel Jonesa7c4a522017-04-21 17:31:03 +00003635SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3636 SelectionDAG &DAG,
3637 unsigned Flag) const {
3638 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3639}
3640
3641SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3642 SelectionDAG &DAG,
3643 unsigned Flag) const {
3644 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3645}
3646
3647SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3648 SelectionDAG &DAG,
3649 unsigned Flag) const {
3650 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3651 N->getOffset(), Flag);
3652}
3653
3654SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3655 SelectionDAG &DAG,
3656 unsigned Flag) const {
3657 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3658}
3659
3660// (loadGOT sym)
3661template <class NodeTy>
3662SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const {
3663 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3664 SDLoc DL(N);
3665 EVT Ty = getPointerTy(DAG.getDataLayout());
3666 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT);
3667 // FIXME: Once remat is capable of dealing with instructions with register
3668 // operands, expand this into two nodes instead of using a wrapper node.
3669 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3670}
3671
3672// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3673template <class NodeTy>
3674SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG)
3675 const {
3676 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3677 SDLoc DL(N);
3678 EVT Ty = getPointerTy(DAG.getDataLayout());
3679 const unsigned char MO_NC = AArch64II::MO_NC;
3680 return DAG.getNode(
3681 AArch64ISD::WrapperLarge, DL, Ty,
3682 getTargetNode(N, Ty, DAG, AArch64II::MO_G3),
3683 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC),
3684 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC),
3685 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC));
3686}
3687
3688// (addlow (adrp %hi(sym)) %lo(sym))
3689template <class NodeTy>
3690SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
3691 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3692 SDLoc DL(N);
3693 EVT Ty = getPointerTy(DAG.getDataLayout());
3694 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE);
3695 SDValue Lo = getTargetNode(N, Ty, DAG,
3696 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3697 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3698 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3699}
3700
Tim Northover3b0846e2014-05-24 12:50:23 +00003701SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3702 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003703 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003704 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003705 unsigned char OpFlags =
3706 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3707
3708 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3709 "unexpected offset in global node");
3710
Joel Jonesa7c4a522017-04-21 17:31:03 +00003711 // This also catches the large code model case for Darwin.
Tim Northover3b0846e2014-05-24 12:50:23 +00003712 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003713 return getGOT(GN, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003714 }
3715
3716 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003717 return getAddrLarge(GN, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003718 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003719 return getAddr(GN, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003720 }
3721}
3722
3723/// \brief Convert a TLS address reference into the correct sequence of loads
3724/// and calls to compute the variable's address (for Darwin, currently) and
3725/// return an SDValue containing the final node.
3726
3727/// Darwin only has one TLS scheme which must be capable of dealing with the
3728/// fully general situation, in the worst case. This means:
3729/// + "extern __thread" declaration.
3730/// + Defined in a possibly unknown dynamic library.
3731///
3732/// The general system is that each __thread variable has a [3 x i64] descriptor
3733/// which contains information used by the runtime to calculate the address. The
3734/// only part of this the compiler needs to know about is the first xword, which
3735/// contains a function pointer that must be called with the address of the
3736/// entire descriptor in "x0".
3737///
3738/// Since this descriptor may be in a different unit, in general even the
3739/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3740/// is:
3741/// adrp x0, _var@TLVPPAGE
3742/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3743/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3744/// ; the function pointer
3745/// blr x1 ; Uses descriptor address in x0
3746/// ; Address of _var is now in x0.
3747///
3748/// If the address of _var's descriptor *is* known to the linker, then it can
3749/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3750/// a slight efficiency gain.
3751SDValue
3752AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3753 SelectionDAG &DAG) const {
3754 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3755
3756 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003757 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003758 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3759
3760 SDValue TLVPAddr =
3761 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3762 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3763
3764 // The first entry in the descriptor is a function pointer that we must call
3765 // to obtain the address of the variable.
3766 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00003767 SDValue FuncTLVGet = DAG.getLoad(
3768 MVT::i64, DL, Chain, DescAddr,
3769 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3770 /* Alignment = */ 8,
3771 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3772 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00003773 Chain = FuncTLVGet.getValue(1);
3774
Matthias Braun941a7052016-07-28 18:40:00 +00003775 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3776 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003777
3778 // TLS calls preserve all registers except those that absolutely must be
3779 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3780 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003781 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003782 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003783
3784 // Finally, we can make the call. This is just a degenerate version of a
3785 // normal AArch64 call node: x0 takes the address of the descriptor, and
3786 // returns the address of the variable in this thread.
3787 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3788 Chain =
3789 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3790 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3791 DAG.getRegisterMask(Mask), Chain.getValue(1));
3792 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3793}
3794
3795/// When accessing thread-local variables under either the general-dynamic or
3796/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3797/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003798/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003799///
Kristof Beylsaea84612015-03-04 09:12:08 +00003800/// The sequence is:
3801/// adrp x0, :tlsdesc:var
3802/// ldr x1, [x0, #:tlsdesc_lo12:var]
3803/// add x0, x0, #:tlsdesc_lo12:var
3804/// .tlsdesccall var
3805/// blr x1
3806/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003807///
Kristof Beylsaea84612015-03-04 09:12:08 +00003808/// The above sequence must be produced unscheduled, to enable the linker to
3809/// optimize/relax this sequence.
3810/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3811/// above sequence, and expanded really late in the compilation flow, to ensure
3812/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003813SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3814 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003815 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003816 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003817
Kristof Beylsaea84612015-03-04 09:12:08 +00003818 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003819 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003820
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003821 Chain =
3822 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003823 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003824
3825 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3826}
3827
3828SDValue
3829AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3830 SelectionDAG &DAG) const {
3831 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
Petr Hosek9eb0a1e2017-04-04 19:51:53 +00003832 assert(Subtarget->useSmallAddressing() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003833 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003834 // Different choices can be made for the maximum size of the TLS area for a
3835 // module. For the small address model, the default TLS size is 16MiB and the
3836 // maximum TLS size is 4GiB.
3837 // FIXME: add -mtls-size command line option and make it control the 16MiB
3838 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003839 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3840
3841 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003842
3843 if (DAG.getTarget().Options.EmulatedTLS)
3844 return LowerToTLSEmulatedModel(GA, DAG);
3845
Kristof Beylsaea84612015-03-04 09:12:08 +00003846 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3847 if (Model == TLSModel::LocalDynamic)
3848 Model = TLSModel::GeneralDynamic;
3849 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003850
3851 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003852 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003853 SDLoc DL(Op);
3854 const GlobalValue *GV = GA->getGlobal();
3855
3856 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3857
3858 if (Model == TLSModel::LocalExec) {
3859 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003860 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003861 SDValue LoVar = DAG.getTargetGlobalAddress(
3862 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003863 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003864
Kristof Beylsaea84612015-03-04 09:12:08 +00003865 SDValue TPWithOff_lo =
3866 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003867 HiVar,
3868 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003869 0);
3870 SDValue TPWithOff =
3871 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003872 LoVar,
3873 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003874 0);
3875 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003876 } else if (Model == TLSModel::InitialExec) {
3877 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3878 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3879 } else if (Model == TLSModel::LocalDynamic) {
3880 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3881 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3882 // the beginning of the module's TLS region, followed by a DTPREL offset
3883 // calculation.
3884
3885 // These accesses will need deduplicating if there's more than one.
3886 AArch64FunctionInfo *MFI =
3887 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3888 MFI->incNumLocalDynamicTLSAccesses();
3889
Tim Northover3b0846e2014-05-24 12:50:23 +00003890 // The call needs a relocation too for linker relaxation. It doesn't make
3891 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3892 // the address.
3893 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3894 AArch64II::MO_TLS);
3895
3896 // Now we can calculate the offset from TPIDR_EL0 to this module's
3897 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003898 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003899
3900 // Now use :dtprel_whatever: operations to calculate this variable's offset
3901 // in its thread-storage area.
3902 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003903 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003904 SDValue LoVar = DAG.getTargetGlobalAddress(
3905 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003906 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3907
Kristof Beylsaea84612015-03-04 09:12:08 +00003908 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003909 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003910 0);
3911 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003912 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003913 0);
3914 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003915 // The call needs a relocation too for linker relaxation. It doesn't make
3916 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3917 // the address.
3918 SDValue SymAddr =
3919 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3920
3921 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003922 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003923 } else
3924 llvm_unreachable("Unsupported ELF TLS access model");
3925
3926 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3927}
3928
3929SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3930 SelectionDAG &DAG) const {
3931 if (Subtarget->isTargetDarwin())
3932 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00003933 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00003934 return LowerELFGlobalTLSAddress(Op, DAG);
3935
3936 llvm_unreachable("Unexpected platform trying to use TLS");
3937}
Eugene Zelenko049b0172017-01-06 00:30:53 +00003938
Tim Northover3b0846e2014-05-24 12:50:23 +00003939SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3940 SDValue Chain = Op.getOperand(0);
3941 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3942 SDValue LHS = Op.getOperand(2);
3943 SDValue RHS = Op.getOperand(3);
3944 SDValue Dest = Op.getOperand(4);
3945 SDLoc dl(Op);
3946
3947 // Handle f128 first, since lowering it will result in comparing the return
3948 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3949 // is expecting to deal with.
3950 if (LHS.getValueType() == MVT::f128) {
3951 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3952
3953 // If softenSetCCOperands returned a scalar, we need to compare the result
3954 // against zero to select between true and false values.
3955 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003956 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003957 CC = ISD::SETNE;
3958 }
3959 }
3960
3961 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3962 // instruction.
3963 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003964 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003965 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3966 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3967 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3968 "Unexpected condition code.");
3969 // Only lower legal XALUO ops.
3970 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3971 return SDValue();
3972
3973 // The actual operation with overflow check.
3974 AArch64CC::CondCode OFCC;
3975 SDValue Value, Overflow;
3976 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3977
3978 if (CC == ISD::SETNE)
3979 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003980 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003981
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003982 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3983 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003984 }
3985
3986 if (LHS.getValueType().isInteger()) {
3987 assert((LHS.getValueType() == RHS.getValueType()) &&
3988 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3989
3990 // If the RHS of the comparison is zero, we can potentially fold this
3991 // to a specialized branch.
3992 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3993 if (RHSC && RHSC->getZExtValue() == 0) {
3994 if (CC == ISD::SETEQ) {
3995 // See if we can use a TBZ to fold in an AND as well.
3996 // TBZ has a smaller branch displacement than CBZ. If the offset is
3997 // out of bounds, a late MI-layer pass rewrites branches.
3998 // 403.gcc is an example that hits this case.
3999 if (LHS.getOpcode() == ISD::AND &&
4000 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4001 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4002 SDValue Test = LHS.getOperand(0);
4003 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004004 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004005 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4006 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004007 }
4008
4009 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4010 } else if (CC == ISD::SETNE) {
4011 // See if we can use a TBZ to fold in an AND as well.
4012 // TBZ has a smaller branch displacement than CBZ. If the offset is
4013 // out of bounds, a late MI-layer pass rewrites branches.
4014 // 403.gcc is an example that hits this case.
4015 if (LHS.getOpcode() == ISD::AND &&
4016 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4017 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4018 SDValue Test = LHS.getOperand(0);
4019 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004020 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004021 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4022 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004023 }
4024
4025 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004026 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4027 // Don't combine AND since emitComparison converts the AND to an ANDS
4028 // (a.k.a. TST) and the test in the test bit and branch instruction
4029 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004030 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004031 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004032 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004033 }
4034 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004035 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4036 LHS.getOpcode() != ISD::AND) {
4037 // Don't combine AND since emitComparison converts the AND to an ANDS
4038 // (a.k.a. TST) and the test in the test bit and branch instruction
4039 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004040 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004041 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004042 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004043 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004044
4045 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004046 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004047 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4048 Cmp);
4049 }
4050
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004051 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4052 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004053
4054 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4055 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004056 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004057 AArch64CC::CondCode CC1, CC2;
4058 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004059 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004060 SDValue BR1 =
4061 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4062 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004063 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004064 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4065 Cmp);
4066 }
4067
4068 return BR1;
4069}
4070
4071SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4072 SelectionDAG &DAG) const {
4073 EVT VT = Op.getValueType();
4074 SDLoc DL(Op);
4075
4076 SDValue In1 = Op.getOperand(0);
4077 SDValue In2 = Op.getOperand(1);
4078 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004079
4080 if (SrcVT.bitsLT(VT))
4081 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4082 else if (SrcVT.bitsGT(VT))
4083 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004084
4085 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004086 uint64_t EltMask;
4087 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004088
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004089 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004090 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004091 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004092 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004093 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004094 DAG.getUNDEF(VecVT), In2);
4095 } else {
4096 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4097 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4098 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004099 };
4100
4101 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4102 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4103 EltMask = 0x80000000ULL;
4104 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004105 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004106 VecVT = MVT::v2i64;
4107
Eric Christopher572e03a2015-06-19 01:53:21 +00004108 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004109 // immediate moves cannot materialize that in a single instruction for
4110 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004111 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004112
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004113 setVecVal(AArch64::dsub);
4114 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4115 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4116 EltMask = 0x8000ULL;
4117 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004118 } else {
4119 llvm_unreachable("Invalid type for copysign!");
4120 }
4121
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004122 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004123
4124 // If we couldn't materialize the mask above, then the mask vector will be
4125 // the zero vector, and we need to negate it here.
4126 if (VT == MVT::f64 || VT == MVT::v2f64) {
4127 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4128 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4129 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4130 }
4131
4132 SDValue Sel =
4133 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4134
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004135 if (VT == MVT::f16)
4136 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004137 if (VT == MVT::f32)
4138 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4139 else if (VT == MVT::f64)
4140 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4141 else
4142 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4143}
4144
4145SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004146 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
4147 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004148 return SDValue();
4149
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004150 if (!Subtarget->hasNEON())
4151 return SDValue();
4152
Tim Northover3b0846e2014-05-24 12:50:23 +00004153 // While there is no integer popcount instruction, it can
4154 // be more efficiently lowered to the following sequence that uses
4155 // AdvSIMD registers/instructions as long as the copies to/from
4156 // the AdvSIMD registers are cheap.
4157 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4158 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4159 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4160 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4161 SDValue Val = Op.getOperand(0);
4162 SDLoc DL(Op);
4163 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004164
Hao Liue0335d72015-01-30 02:13:53 +00004165 if (VT == MVT::i32)
4166 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4167 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004168
Hao Liue0335d72015-01-30 02:13:53 +00004169 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004170 SDValue UaddLV = DAG.getNode(
4171 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004172 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004173
4174 if (VT == MVT::i64)
4175 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4176 return UaddLV;
4177}
4178
4179SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4180
4181 if (Op.getValueType().isVector())
4182 return LowerVSETCC(Op, DAG);
4183
4184 SDValue LHS = Op.getOperand(0);
4185 SDValue RHS = Op.getOperand(1);
4186 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4187 SDLoc dl(Op);
4188
4189 // We chose ZeroOrOneBooleanContents, so use zero and one.
4190 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004191 SDValue TVal = DAG.getConstant(1, dl, VT);
4192 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004193
4194 // Handle f128 first, since one possible outcome is a normal integer
4195 // comparison which gets picked up by the next if statement.
4196 if (LHS.getValueType() == MVT::f128) {
4197 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4198
4199 // If softenSetCCOperands returned a scalar, use it.
4200 if (!RHS.getNode()) {
4201 assert(LHS.getValueType() == Op.getValueType() &&
4202 "Unexpected setcc expansion!");
4203 return LHS;
4204 }
4205 }
4206
4207 if (LHS.getValueType().isInteger()) {
4208 SDValue CCVal;
4209 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004210 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004211
4212 // Note that we inverted the condition above, so we reverse the order of
4213 // the true and false operands here. This will allow the setcc to be
4214 // matched to a single CSINC instruction.
4215 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4216 }
4217
4218 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004219 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4220 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004221
4222 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4223 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004224 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004225
4226 AArch64CC::CondCode CC1, CC2;
4227 changeFPCCToAArch64CC(CC, CC1, CC2);
4228 if (CC2 == AArch64CC::AL) {
4229 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004230 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004231
4232 // Note that we inverted the condition above, so we reverse the order of
4233 // the true and false operands here. This will allow the setcc to be
4234 // matched to a single CSINC instruction.
4235 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4236 } else {
4237 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4238 // totally clean. Some of them require two CSELs to implement. As is in
4239 // this case, we emit the first CSEL and then emit a second using the output
4240 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4241
4242 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004243 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004244 SDValue CS1 =
4245 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4246
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004247 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004248 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4249 }
4250}
4251
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004252SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4253 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004254 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004255 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004256 // Handle f128 first, because it will result in a comparison of some RTLIB
4257 // call result against zero.
4258 if (LHS.getValueType() == MVT::f128) {
4259 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4260
4261 // If softenSetCCOperands returned a scalar, we need to compare the result
4262 // against zero to select between true and false values.
4263 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004264 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004265 CC = ISD::SETNE;
4266 }
4267 }
4268
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004269 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004270 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004271 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4272 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4273 }
4274
4275 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004276 if (LHS.getValueType().isInteger()) {
4277 assert((LHS.getValueType() == RHS.getValueType()) &&
4278 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4279
4280 unsigned Opcode = AArch64ISD::CSEL;
4281
4282 // If both the TVal and the FVal are constants, see if we can swap them in
4283 // order to for a CSINV or CSINC out of them.
4284 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4285 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4286
4287 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4288 std::swap(TVal, FVal);
4289 std::swap(CTVal, CFVal);
4290 CC = ISD::getSetCCInverse(CC, true);
4291 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4292 std::swap(TVal, FVal);
4293 std::swap(CTVal, CFVal);
4294 CC = ISD::getSetCCInverse(CC, true);
4295 } else if (TVal.getOpcode() == ISD::XOR) {
4296 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4297 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004298 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004299 std::swap(TVal, FVal);
4300 std::swap(CTVal, CFVal);
4301 CC = ISD::getSetCCInverse(CC, true);
4302 }
4303 } else if (TVal.getOpcode() == ISD::SUB) {
4304 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4305 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004306 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004307 std::swap(TVal, FVal);
4308 std::swap(CTVal, CFVal);
4309 CC = ISD::getSetCCInverse(CC, true);
4310 }
4311 } else if (CTVal && CFVal) {
4312 const int64_t TrueVal = CTVal->getSExtValue();
4313 const int64_t FalseVal = CFVal->getSExtValue();
4314 bool Swap = false;
4315
4316 // If both TVal and FVal are constants, see if FVal is the
4317 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4318 // instead of a CSEL in that case.
4319 if (TrueVal == ~FalseVal) {
4320 Opcode = AArch64ISD::CSINV;
4321 } else if (TrueVal == -FalseVal) {
4322 Opcode = AArch64ISD::CSNEG;
4323 } else if (TVal.getValueType() == MVT::i32) {
4324 // If our operands are only 32-bit wide, make sure we use 32-bit
4325 // arithmetic for the check whether we can use CSINC. This ensures that
4326 // the addition in the check will wrap around properly in case there is
4327 // an overflow (which would not be the case if we do the check with
4328 // 64-bit arithmetic).
4329 const uint32_t TrueVal32 = CTVal->getZExtValue();
4330 const uint32_t FalseVal32 = CFVal->getZExtValue();
4331
4332 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4333 Opcode = AArch64ISD::CSINC;
4334
4335 if (TrueVal32 > FalseVal32) {
4336 Swap = true;
4337 }
4338 }
4339 // 64-bit check whether we can use CSINC.
4340 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4341 Opcode = AArch64ISD::CSINC;
4342
4343 if (TrueVal > FalseVal) {
4344 Swap = true;
4345 }
4346 }
4347
4348 // Swap TVal and FVal if necessary.
4349 if (Swap) {
4350 std::swap(TVal, FVal);
4351 std::swap(CTVal, CFVal);
4352 CC = ISD::getSetCCInverse(CC, true);
4353 }
4354
4355 if (Opcode != AArch64ISD::CSEL) {
4356 // Drop FVal since we can get its value by simply inverting/negating
4357 // TVal.
4358 FVal = TVal;
4359 }
4360 }
4361
Chad Rosier58f505b2016-08-26 18:05:50 +00004362 // Avoid materializing a constant when possible by reusing a known value in
4363 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004364 // is one, zero or negative one in the case of a CSEL. We can always
4365 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4366 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004367 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4368 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4369 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4370 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4371 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4372 // "a != C ? x : a" to avoid materializing C.
4373 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4374 TVal = LHS;
4375 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4376 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004377 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4378 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4379 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4380 // avoid materializing C.
4381 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4382 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4383 Opcode = AArch64ISD::CSINV;
4384 TVal = LHS;
4385 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4386 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004387 }
4388
Tim Northover3b0846e2014-05-24 12:50:23 +00004389 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004390 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004391 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004392 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4393 }
4394
4395 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004396 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4397 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004398 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004399 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004400 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004401
4402 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4403 // clean. Some of them require two CSELs to implement.
4404 AArch64CC::CondCode CC1, CC2;
4405 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004406
4407 if (DAG.getTarget().Options.UnsafeFPMath) {
4408 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4409 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4410 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4411 if (RHSVal && RHSVal->isZero()) {
4412 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4413 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4414
4415 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004416 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004417 TVal = LHS;
4418 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004419 CFVal && CFVal->isZero() &&
4420 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004421 FVal = LHS;
4422 }
4423 }
4424
4425 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004426 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004427 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4428
4429 // If we need a second CSEL, emit it, using the output of the first as the
4430 // RHS. We're effectively OR'ing the two CC's together.
4431 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004432 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004433 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4434 }
4435
4436 // Otherwise, return the output of the first CSEL.
4437 return CS1;
4438}
4439
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004440SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4441 SelectionDAG &DAG) const {
4442 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4443 SDValue LHS = Op.getOperand(0);
4444 SDValue RHS = Op.getOperand(1);
4445 SDValue TVal = Op.getOperand(2);
4446 SDValue FVal = Op.getOperand(3);
4447 SDLoc DL(Op);
4448 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4449}
4450
4451SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4452 SelectionDAG &DAG) const {
4453 SDValue CCVal = Op->getOperand(0);
4454 SDValue TVal = Op->getOperand(1);
4455 SDValue FVal = Op->getOperand(2);
4456 SDLoc DL(Op);
4457
4458 unsigned Opc = CCVal.getOpcode();
4459 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4460 // instruction.
4461 if (CCVal.getResNo() == 1 &&
4462 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4463 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4464 // Only lower legal XALUO ops.
4465 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4466 return SDValue();
4467
4468 AArch64CC::CondCode OFCC;
4469 SDValue Value, Overflow;
4470 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004471 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004472
4473 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4474 CCVal, Overflow);
4475 }
4476
4477 // Lower it the same way as we would lower a SELECT_CC node.
4478 ISD::CondCode CC;
4479 SDValue LHS, RHS;
4480 if (CCVal.getOpcode() == ISD::SETCC) {
4481 LHS = CCVal.getOperand(0);
4482 RHS = CCVal.getOperand(1);
4483 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4484 } else {
4485 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004486 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004487 CC = ISD::SETNE;
4488 }
4489 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4490}
4491
Tim Northover3b0846e2014-05-24 12:50:23 +00004492SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4493 SelectionDAG &DAG) const {
4494 // Jump table entries as PC relative offsets. No additional tweaking
4495 // is necessary here. Just get the address of the jump table.
4496 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004497
4498 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4499 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004500 return getAddrLarge(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004501 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004502 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004503}
4504
4505SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4506 SelectionDAG &DAG) const {
4507 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004508
4509 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4510 // Use the GOT for the large code model on iOS.
4511 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004512 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004513 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004514 return getAddrLarge(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004515 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004516 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004517 }
4518}
4519
4520SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4521 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004522 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004523 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4524 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004525 return getAddrLarge(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004526 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004527 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004528 }
4529}
4530
4531SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4532 SelectionDAG &DAG) const {
4533 AArch64FunctionInfo *FuncInfo =
4534 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4535
4536 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004537 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4538 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004539 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4540 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004541 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004542}
4543
Martin Storsjo68266fa2017-07-13 17:03:12 +00004544SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4545 SelectionDAG &DAG) const {
4546 AArch64FunctionInfo *FuncInfo =
4547 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4548
4549 SDLoc DL(Op);
4550 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4551 ? FuncInfo->getVarArgsGPRIndex()
4552 : FuncInfo->getVarArgsStackIndex(),
4553 getPointerTy(DAG.getDataLayout()));
4554 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4555 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4556 MachinePointerInfo(SV));
4557}
4558
Tim Northover3b0846e2014-05-24 12:50:23 +00004559SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4560 SelectionDAG &DAG) const {
4561 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4562 // Standard, section B.3.
4563 MachineFunction &MF = DAG.getMachineFunction();
4564 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004565 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004566 SDLoc DL(Op);
4567
4568 SDValue Chain = Op.getOperand(0);
4569 SDValue VAList = Op.getOperand(1);
4570 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4571 SmallVector<SDValue, 4> MemOps;
4572
4573 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004574 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004575 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004576 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004577
4578 // void *__gr_top at offset 8
4579 int GPRSize = FuncInfo->getVarArgsGPRSize();
4580 if (GPRSize > 0) {
4581 SDValue GRTop, GRTopAddr;
4582
Mehdi Amini44ede332015-07-09 02:09:04 +00004583 GRTopAddr =
4584 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004585
Mehdi Amini44ede332015-07-09 02:09:04 +00004586 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4587 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4588 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004589
4590 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004591 MachinePointerInfo(SV, 8),
4592 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004593 }
4594
4595 // void *__vr_top at offset 16
4596 int FPRSize = FuncInfo->getVarArgsFPRSize();
4597 if (FPRSize > 0) {
4598 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004599 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4600 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004601
Mehdi Amini44ede332015-07-09 02:09:04 +00004602 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4603 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4604 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004605
4606 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004607 MachinePointerInfo(SV, 16),
4608 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004609 }
4610
4611 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004612 SDValue GROffsAddr =
4613 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004614 MemOps.push_back(DAG.getStore(
4615 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4616 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004617
4618 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004619 SDValue VROffsAddr =
4620 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004621 MemOps.push_back(DAG.getStore(
4622 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4623 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004624
4625 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4626}
4627
4628SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4629 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00004630 MachineFunction &MF = DAG.getMachineFunction();
4631
4632 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00004633 return LowerWin64_VASTART(Op, DAG);
4634 else if (Subtarget->isTargetDarwin())
4635 return LowerDarwin_VASTART(Op, DAG);
4636 else
4637 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004638}
4639
4640SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4641 SelectionDAG &DAG) const {
4642 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4643 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004644 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00004645 unsigned VaListSize =
4646 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00004647 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4648 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4649
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004650 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4651 Op.getOperand(2),
4652 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004653 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004654 MachinePointerInfo(SrcSV));
4655}
4656
4657SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4658 assert(Subtarget->isTargetDarwin() &&
4659 "automatic va_arg instruction only works on Darwin");
4660
4661 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4662 EVT VT = Op.getValueType();
4663 SDLoc DL(Op);
4664 SDValue Chain = Op.getOperand(0);
4665 SDValue Addr = Op.getOperand(1);
4666 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004667 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004668
Justin Lebar9c375812016-07-15 18:27:10 +00004669 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004670 Chain = VAList.getValue(1);
4671
4672 if (Align > 8) {
4673 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004674 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4675 DAG.getConstant(Align - 1, DL, PtrVT));
4676 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4677 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004678 }
4679
4680 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004681 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004682
4683 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4684 // up to 64 bits. At the very least, we have to increase the striding of the
4685 // vaargs list to match this, and for FP values we need to introduce
4686 // FP_ROUND nodes as well.
4687 if (VT.isInteger() && !VT.isVector())
4688 ArgSize = 8;
4689 bool NeedFPTrunc = false;
4690 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4691 ArgSize = 8;
4692 NeedFPTrunc = true;
4693 }
4694
4695 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004696 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4697 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004698 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004699 SDValue APStore =
4700 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004701
4702 // Load the actual argument out of the pointer VAList
4703 if (NeedFPTrunc) {
4704 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004705 SDValue WideFP =
4706 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004707 // Round the value down to an f32.
4708 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004709 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004710 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4711 // Merge the rounded value with the chain output of the load.
4712 return DAG.getMergeValues(Ops, DL);
4713 }
4714
Justin Lebar9c375812016-07-15 18:27:10 +00004715 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004716}
4717
4718SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4719 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004720 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4721 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004722
4723 EVT VT = Op.getValueType();
4724 SDLoc DL(Op);
4725 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4726 SDValue FrameAddr =
4727 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4728 while (Depth--)
4729 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004730 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004731 return FrameAddr;
4732}
4733
4734// FIXME? Maybe this could be a TableGen attribute on some registers and
4735// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004736unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4737 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004738 unsigned Reg = StringSwitch<unsigned>(RegName)
4739 .Case("sp", AArch64::SP)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004740 .Case("x18", AArch64::X18)
4741 .Case("w18", AArch64::W18)
Tim Northover3b0846e2014-05-24 12:50:23 +00004742 .Default(0);
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004743 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4744 !Subtarget->isX18Reserved())
4745 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004746 if (Reg)
4747 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004748 report_fatal_error(Twine("Invalid register name \""
4749 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004750}
4751
4752SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4753 SelectionDAG &DAG) const {
4754 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004755 MachineFrameInfo &MFI = MF.getFrameInfo();
4756 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004757
4758 EVT VT = Op.getValueType();
4759 SDLoc DL(Op);
4760 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4761 if (Depth) {
4762 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004763 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004764 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4765 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004766 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004767 }
4768
4769 // Return LR, which contains the return address. Mark it an implicit live-in.
4770 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4771 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4772}
4773
4774/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4775/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4776SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4777 SelectionDAG &DAG) const {
4778 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4779 EVT VT = Op.getValueType();
4780 unsigned VTBits = VT.getSizeInBits();
4781 SDLoc dl(Op);
4782 SDValue ShOpLo = Op.getOperand(0);
4783 SDValue ShOpHi = Op.getOperand(1);
4784 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004785 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4786
4787 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4788
4789 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004790 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004791 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4792
4793 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4794 // is "undef". We wanted 0, so CSEL it directly.
4795 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4796 ISD::SETEQ, dl, DAG);
4797 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4798 HiBitsForLo =
4799 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4800 HiBitsForLo, CCVal, Cmp);
4801
Tim Northover3b0846e2014-05-24 12:50:23 +00004802 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004803 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004804
Tim Northoverf3be9d52015-12-02 00:33:54 +00004805 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4806 SDValue LoForNormalShift =
4807 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004808
Tim Northoverf3be9d52015-12-02 00:33:54 +00004809 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4810 dl, DAG);
4811 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4812 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4813 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4814 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004815
4816 // AArch64 shifts larger than the register width are wrapped rather than
4817 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004818 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4819 SDValue HiForBigShift =
4820 Opc == ISD::SRA
4821 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4822 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4823 : DAG.getConstant(0, dl, VT);
4824 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4825 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004826
4827 SDValue Ops[2] = { Lo, Hi };
4828 return DAG.getMergeValues(Ops, dl);
4829}
4830
4831/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4832/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4833SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004834 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004835 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4836 EVT VT = Op.getValueType();
4837 unsigned VTBits = VT.getSizeInBits();
4838 SDLoc dl(Op);
4839 SDValue ShOpLo = Op.getOperand(0);
4840 SDValue ShOpHi = Op.getOperand(1);
4841 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004842
4843 assert(Op.getOpcode() == ISD::SHL_PARTS);
4844 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004845 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004846 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4847
4848 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4849 // is "undef". We wanted 0, so CSEL it directly.
4850 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4851 ISD::SETEQ, dl, DAG);
4852 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4853 LoBitsForHi =
4854 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4855 LoBitsForHi, CCVal, Cmp);
4856
Tim Northover3b0846e2014-05-24 12:50:23 +00004857 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004858 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004859 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4860 SDValue HiForNormalShift =
4861 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004862
Tim Northoverf3be9d52015-12-02 00:33:54 +00004863 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004864
Tim Northoverf3be9d52015-12-02 00:33:54 +00004865 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4866 dl, DAG);
4867 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4868 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4869 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004870
4871 // AArch64 shifts of larger than register sizes are wrapped rather than
4872 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004873 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4874 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4875 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4876 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004877
4878 SDValue Ops[2] = { Lo, Hi };
4879 return DAG.getMergeValues(Ops, dl);
4880}
4881
4882bool AArch64TargetLowering::isOffsetFoldingLegal(
4883 const GlobalAddressSDNode *GA) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004884 DEBUG(dbgs() << "Skipping offset folding global address: ");
4885 DEBUG(GA->dump());
4886 DEBUG(dbgs() << "AArch64 doesn't support folding offsets into global "
4887 "addresses\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00004888 return false;
4889}
4890
4891bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4892 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4893 // FIXME: We should be able to handle f128 as well with a clever lowering.
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004894 if (Imm.isPosZero() && (VT == MVT::f16 || VT == MVT::f64 || VT == MVT::f32)) {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004895 DEBUG(dbgs() << "Legal fp imm: materialize 0 using the zero register\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00004896 return true;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004897 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004898
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004899 StringRef FPType;
4900 bool IsLegal = false;
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004901 SmallString<128> ImmStrVal;
4902 Imm.toString(ImmStrVal);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004903
4904 if (VT == MVT::f64) {
4905 FPType = "f64";
4906 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
4907 } else if (VT == MVT::f32) {
4908 FPType = "f32";
4909 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
4910 } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) {
4911 FPType = "f16";
4912 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
4913 }
4914
4915 if (IsLegal) {
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004916 DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004917 return true;
4918 }
4919
4920 if (!FPType.empty())
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004921 DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004922 else
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004923 DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal << ": unsupported fp type\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004924
Tim Northover3b0846e2014-05-24 12:50:23 +00004925 return false;
4926}
4927
4928//===----------------------------------------------------------------------===//
4929// AArch64 Optimization Hooks
4930//===----------------------------------------------------------------------===//
4931
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004932static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4933 SDValue Operand, SelectionDAG &DAG,
4934 int &ExtraSteps) {
4935 EVT VT = Operand.getValueType();
4936 if (ST->hasNEON() &&
4937 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4938 VT == MVT::f32 || VT == MVT::v1f32 ||
4939 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4940 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4941 // For the reciprocal estimates, convergence is quadratic, so the number
4942 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4943 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4944 // the result for float (23 mantissa bits) is 2 and for double (52
4945 // mantissa bits) is 3.
4946 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4947
4948 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4949 }
4950
4951 return SDValue();
4952}
4953
Evandro Menezes21f9ce12016-11-10 23:31:06 +00004954SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4955 SelectionDAG &DAG, int Enabled,
4956 int &ExtraSteps,
4957 bool &UseOneConst,
4958 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004959 if (Enabled == ReciprocalEstimate::Enabled ||
4960 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4961 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4962 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00004963 SDLoc DL(Operand);
4964 EVT VT = Operand.getValueType();
4965
4966 SDNodeFlags Flags;
4967 Flags.setUnsafeAlgebra(true);
4968
4969 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4970 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4971 for (int i = ExtraSteps; i > 0; --i) {
4972 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00004973 Flags);
4974 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
4975 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00004976 }
4977
4978 if (!Reciprocal) {
4979 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4980 VT);
4981 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4982 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4983
Amara Emersond28f0cd42017-05-01 15:17:51 +00004984 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00004985 // Correct the result if the operand is 0.0.
4986 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4987 VT, Eq, Operand, Estimate);
4988 }
4989
4990 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004991 return Estimate;
4992 }
4993
4994 return SDValue();
4995}
4996
4997SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4998 SelectionDAG &DAG, int Enabled,
4999 int &ExtraSteps) const {
5000 if (Enabled == ReciprocalEstimate::Enabled)
5001 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005002 DAG, ExtraSteps)) {
5003 SDLoc DL(Operand);
5004 EVT VT = Operand.getValueType();
5005
5006 SDNodeFlags Flags;
5007 Flags.setUnsafeAlgebra(true);
5008
5009 // Newton reciprocal iteration: E * (2 - X * E)
5010 // AArch64 reciprocal iteration instruction: (2 - M * N)
5011 for (int i = ExtraSteps; i > 0; --i) {
5012 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005013 Estimate, Flags);
5014 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005015 }
5016
5017 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005018 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005019 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005020
5021 return SDValue();
5022}
5023
Tim Northover3b0846e2014-05-24 12:50:23 +00005024//===----------------------------------------------------------------------===//
5025// AArch64 Inline Assembly Support
5026//===----------------------------------------------------------------------===//
5027
5028// Table of Constraints
5029// TODO: This is the current set of constraints supported by ARM for the
5030// compiler, not all of them may make sense, e.g. S may be difficult to support.
5031//
5032// r - A general register
5033// w - An FP/SIMD register of some size in the range v0-v31
5034// x - An FP/SIMD register of some size in the range v0-v15
5035// I - Constant that can be used with an ADD instruction
5036// J - Constant that can be used with a SUB instruction
5037// K - Constant that can be used with a 32-bit logical instruction
5038// L - Constant that can be used with a 64-bit logical instruction
5039// M - Constant that can be used as a 32-bit MOV immediate
5040// N - Constant that can be used as a 64-bit MOV immediate
5041// Q - A memory reference with base register and no offset
5042// S - A symbolic address
5043// Y - Floating point constant zero
5044// Z - Integer constant zero
5045//
5046// Note that general register operands will be output using their 64-bit x
5047// register name, whatever the size of the variable, unless the asm operand
5048// is prefixed by the %w modifier. Floating-point and SIMD register operands
5049// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5050// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005051const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5052 // At this point, we have to lower this constraint to something else, so we
5053 // lower it to an "r" or "w". However, by doing this we will force the result
5054 // to be in register, while the X constraint is much more permissive.
5055 //
5056 // Although we are correct (we are free to emit anything, without
5057 // constraints), we might break use cases that would expect us to be more
5058 // efficient and emit something else.
5059 if (!Subtarget->hasFPARMv8())
5060 return "r";
5061
5062 if (ConstraintVT.isFloatingPoint())
5063 return "w";
5064
5065 if (ConstraintVT.isVector() &&
5066 (ConstraintVT.getSizeInBits() == 64 ||
5067 ConstraintVT.getSizeInBits() == 128))
5068 return "w";
5069
5070 return "r";
5071}
Tim Northover3b0846e2014-05-24 12:50:23 +00005072
5073/// getConstraintType - Given a constraint letter, return the type of
5074/// constraint it is for this target.
5075AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005076AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005077 if (Constraint.size() == 1) {
5078 switch (Constraint[0]) {
5079 default:
5080 break;
5081 case 'z':
5082 return C_Other;
5083 case 'x':
5084 case 'w':
5085 return C_RegisterClass;
5086 // An address with a single base register. Due to the way we
5087 // currently handle addresses it is the same as 'r'.
5088 case 'Q':
5089 return C_Memory;
5090 }
5091 }
5092 return TargetLowering::getConstraintType(Constraint);
5093}
5094
5095/// Examine constraint type and operand type and determine a weight value.
5096/// This object must already have been set up with the operand type
5097/// and the current alternative constraint selected.
5098TargetLowering::ConstraintWeight
5099AArch64TargetLowering::getSingleConstraintMatchWeight(
5100 AsmOperandInfo &info, const char *constraint) const {
5101 ConstraintWeight weight = CW_Invalid;
5102 Value *CallOperandVal = info.CallOperandVal;
5103 // If we don't have a value, we can't do a match,
5104 // but allow it at the lowest weight.
5105 if (!CallOperandVal)
5106 return CW_Default;
5107 Type *type = CallOperandVal->getType();
5108 // Look at the constraint type.
5109 switch (*constraint) {
5110 default:
5111 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5112 break;
5113 case 'x':
5114 case 'w':
5115 if (type->isFloatingPointTy() || type->isVectorTy())
5116 weight = CW_Register;
5117 break;
5118 case 'z':
5119 weight = CW_Constant;
5120 break;
5121 }
5122 return weight;
5123}
5124
5125std::pair<unsigned, const TargetRegisterClass *>
5126AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005127 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005128 if (Constraint.size() == 1) {
5129 switch (Constraint[0]) {
5130 case 'r':
5131 if (VT.getSizeInBits() == 64)
5132 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5133 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5134 case 'w':
Amara Emerson614b44b2016-11-07 15:42:12 +00005135 if (VT.getSizeInBits() == 16)
5136 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005137 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005138 return std::make_pair(0U, &AArch64::FPR32RegClass);
5139 if (VT.getSizeInBits() == 64)
5140 return std::make_pair(0U, &AArch64::FPR64RegClass);
5141 if (VT.getSizeInBits() == 128)
5142 return std::make_pair(0U, &AArch64::FPR128RegClass);
5143 break;
5144 // The instructions that this constraint is designed for can
5145 // only take 128-bit registers so just use that regclass.
5146 case 'x':
5147 if (VT.getSizeInBits() == 128)
5148 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5149 break;
5150 }
5151 }
5152 if (StringRef("{cc}").equals_lower(Constraint))
5153 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5154
5155 // Use the default implementation in TargetLowering to convert the register
5156 // constraint into a member of a register class.
5157 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005158 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005159
5160 // Not found as a standard register?
5161 if (!Res.second) {
5162 unsigned Size = Constraint.size();
5163 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5164 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005165 int RegNo;
5166 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5167 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005168 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005169 // By default we'll emit v0-v31 for this unless there's a modifier where
5170 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005171 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5172 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5173 Res.second = &AArch64::FPR64RegClass;
5174 } else {
5175 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5176 Res.second = &AArch64::FPR128RegClass;
5177 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005178 }
5179 }
5180 }
5181
5182 return Res;
5183}
5184
5185/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5186/// vector. If it is invalid, don't add anything to Ops.
5187void AArch64TargetLowering::LowerAsmOperandForConstraint(
5188 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5189 SelectionDAG &DAG) const {
5190 SDValue Result;
5191
5192 // Currently only support length 1 constraints.
5193 if (Constraint.length() != 1)
5194 return;
5195
5196 char ConstraintLetter = Constraint[0];
5197 switch (ConstraintLetter) {
5198 default:
5199 break;
5200
5201 // This set of constraints deal with valid constants for various instructions.
5202 // Validate and return a target constant for them if we can.
5203 case 'z': {
5204 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005205 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005206 return;
5207
5208 if (Op.getValueType() == MVT::i64)
5209 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5210 else
5211 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5212 break;
5213 }
5214
5215 case 'I':
5216 case 'J':
5217 case 'K':
5218 case 'L':
5219 case 'M':
5220 case 'N':
5221 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5222 if (!C)
5223 return;
5224
5225 // Grab the value and do some validation.
5226 uint64_t CVal = C->getZExtValue();
5227 switch (ConstraintLetter) {
5228 // The I constraint applies only to simple ADD or SUB immediate operands:
5229 // i.e. 0 to 4095 with optional shift by 12
5230 // The J constraint applies only to ADD or SUB immediates that would be
5231 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5232 // instruction [or vice versa], in other words -1 to -4095 with optional
5233 // left shift by 12.
5234 case 'I':
5235 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5236 break;
5237 return;
5238 case 'J': {
5239 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005240 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5241 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005242 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005243 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005244 return;
5245 }
5246 // The K and L constraints apply *only* to logical immediates, including
5247 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5248 // been removed and MOV should be used). So these constraints have to
5249 // distinguish between bit patterns that are valid 32-bit or 64-bit
5250 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5251 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5252 // versa.
5253 case 'K':
5254 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5255 break;
5256 return;
5257 case 'L':
5258 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5259 break;
5260 return;
5261 // The M and N constraints are a superset of K and L respectively, for use
5262 // with the MOV (immediate) alias. As well as the logical immediates they
5263 // also match 32 or 64-bit immediates that can be loaded either using a
5264 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5265 // (M) or 64-bit 0x1234000000000000 (N) etc.
5266 // As a note some of this code is liberally stolen from the asm parser.
5267 case 'M': {
5268 if (!isUInt<32>(CVal))
5269 return;
5270 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5271 break;
5272 if ((CVal & 0xFFFF) == CVal)
5273 break;
5274 if ((CVal & 0xFFFF0000ULL) == CVal)
5275 break;
5276 uint64_t NCVal = ~(uint32_t)CVal;
5277 if ((NCVal & 0xFFFFULL) == NCVal)
5278 break;
5279 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5280 break;
5281 return;
5282 }
5283 case 'N': {
5284 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5285 break;
5286 if ((CVal & 0xFFFFULL) == CVal)
5287 break;
5288 if ((CVal & 0xFFFF0000ULL) == CVal)
5289 break;
5290 if ((CVal & 0xFFFF00000000ULL) == CVal)
5291 break;
5292 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5293 break;
5294 uint64_t NCVal = ~CVal;
5295 if ((NCVal & 0xFFFFULL) == NCVal)
5296 break;
5297 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5298 break;
5299 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5300 break;
5301 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5302 break;
5303 return;
5304 }
5305 default:
5306 return;
5307 }
5308
5309 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005310 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005311 break;
5312 }
5313
5314 if (Result.getNode()) {
5315 Ops.push_back(Result);
5316 return;
5317 }
5318
5319 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5320}
5321
5322//===----------------------------------------------------------------------===//
5323// AArch64 Advanced SIMD Support
5324//===----------------------------------------------------------------------===//
5325
5326/// WidenVector - Given a value in the V64 register class, produce the
5327/// equivalent value in the V128 register class.
5328static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5329 EVT VT = V64Reg.getValueType();
5330 unsigned NarrowSize = VT.getVectorNumElements();
5331 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5332 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5333 SDLoc DL(V64Reg);
5334
5335 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005336 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005337}
5338
5339/// getExtFactor - Determine the adjustment factor for the position when
5340/// generating an "extract from vector registers" instruction.
5341static unsigned getExtFactor(SDValue &V) {
5342 EVT EltType = V.getValueType().getVectorElementType();
5343 return EltType.getSizeInBits() / 8;
5344}
5345
5346/// NarrowVector - Given a value in the V128 register class, produce the
5347/// equivalent value in the V64 register class.
5348static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5349 EVT VT = V128Reg.getValueType();
5350 unsigned WideSize = VT.getVectorNumElements();
5351 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5352 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5353 SDLoc DL(V128Reg);
5354
5355 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5356}
5357
5358// Gather data to see if the operation can be modelled as a
5359// shuffle in combination with VEXTs.
5360SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5361 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005362 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005363 DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005364 SDLoc dl(Op);
5365 EVT VT = Op.getValueType();
5366 unsigned NumElts = VT.getVectorNumElements();
5367
Tim Northover7324e842014-07-24 15:39:55 +00005368 struct ShuffleSourceInfo {
5369 SDValue Vec;
5370 unsigned MinElt;
5371 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005372
Tim Northover7324e842014-07-24 15:39:55 +00005373 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5374 // be compatible with the shuffle we intend to construct. As a result
5375 // ShuffleVec will be some sliding window into the original Vec.
5376 SDValue ShuffleVec;
5377
5378 // Code should guarantee that element i in Vec starts at element "WindowBase
5379 // + i * WindowScale in ShuffleVec".
5380 int WindowBase;
5381 int WindowScale;
5382
Tim Northover7324e842014-07-24 15:39:55 +00005383 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005384 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5385 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5386
5387 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005388 };
5389
5390 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5391 // node.
5392 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005393 for (unsigned i = 0; i < NumElts; ++i) {
5394 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005395 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005396 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005397 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5398 !isa<ConstantSDNode>(V.getOperand(1))) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005399 DEBUG(dbgs() << "Reshuffle failed: "
5400 "a shuffle can only come from building a vector from "
5401 "various elements of other vectors, provided their "
5402 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005403 return SDValue();
5404 }
5405
Tim Northover7324e842014-07-24 15:39:55 +00005406 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005407 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005408 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005409 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005410 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005411
Tim Northover7324e842014-07-24 15:39:55 +00005412 // Update the minimum and maximum lane number seen.
5413 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5414 Source->MinElt = std::min(Source->MinElt, EltNo);
5415 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005416 }
5417
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005418 if (Sources.size() > 2) {
5419 DEBUG(dbgs() << "Reshuffle failed: currently only do something sane when at "
5420 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005421 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005422 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005423
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005424 // Find out the smallest element size among result and two sources, and use
5425 // it as element size to build the shuffle_vector.
5426 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005427 for (auto &Source : Sources) {
5428 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005429 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5430 SmallestEltTy = SrcEltTy;
5431 }
5432 }
5433 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005434 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005435 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5436 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005437
Tim Northover7324e842014-07-24 15:39:55 +00005438 // If the source vector is too wide or too narrow, we may nevertheless be able
5439 // to construct a compatible shuffle either by concatenating it with UNDEF or
5440 // extracting a suitable range of elements.
5441 for (auto &Src : Sources) {
5442 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005443
Tim Northover7324e842014-07-24 15:39:55 +00005444 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005445 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005446
5447 // This stage of the search produces a source with the same element type as
5448 // the original, but with a total width matching the BUILD_VECTOR output.
5449 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005450 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5451 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005452
5453 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5454 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005455 // We can pad out the smaller vector for free, so if it's part of a
5456 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005457 Src.ShuffleVec =
5458 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5459 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005460 continue;
5461 }
5462
Tim Northover7324e842014-07-24 15:39:55 +00005463 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005464
James Molloyf497d552014-10-17 17:06:31 +00005465 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005466 DEBUG(dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005467 return SDValue();
5468 }
5469
James Molloyf497d552014-10-17 17:06:31 +00005470 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005471 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005472 Src.ShuffleVec =
5473 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005474 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005475 Src.WindowBase = -NumSrcElts;
5476 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005477 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005478 Src.ShuffleVec =
5479 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005480 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005481 } else {
5482 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005483 SDValue VEXTSrc1 =
5484 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005485 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005486 SDValue VEXTSrc2 =
5487 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005488 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005489 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5490
5491 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005492 VEXTSrc2,
5493 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005494 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005495 }
5496 }
5497
Tim Northover7324e842014-07-24 15:39:55 +00005498 // Another possible incompatibility occurs from the vector element types. We
5499 // can fix this by bitcasting the source vectors to the same type we intend
5500 // for the shuffle.
5501 for (auto &Src : Sources) {
5502 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5503 if (SrcEltTy == SmallestEltTy)
5504 continue;
5505 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5506 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5507 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5508 Src.WindowBase *= Src.WindowScale;
5509 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005510
Tim Northover7324e842014-07-24 15:39:55 +00005511 // Final sanity check before we try to actually produce a shuffle.
5512 DEBUG(
5513 for (auto Src : Sources)
5514 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5515 );
5516
5517 // The stars all align, our next step is to produce the mask for the shuffle.
5518 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005519 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005520 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005521 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005522 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005523 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005524
David Majnemer0d955d02016-08-11 22:21:41 +00005525 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005526 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5527
5528 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5529 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5530 // segment.
5531 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005532 int BitsDefined =
5533 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005534 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5535
5536 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5537 // starting at the appropriate offset.
5538 int *LaneMask = &Mask[i * ResMultiplier];
5539
5540 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5541 ExtractBase += NumElts * (Src - Sources.begin());
5542 for (int j = 0; j < LanesDefined; ++j)
5543 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005544 }
5545
5546 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005547 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
5548 DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00005549 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005550 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005551
Tim Northover7324e842014-07-24 15:39:55 +00005552 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5553 for (unsigned i = 0; i < Sources.size(); ++i)
5554 ShuffleOps[i] = Sources[i].ShuffleVec;
5555
5556 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005557 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005558 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5559
5560 DEBUG(
5561 dbgs() << "Reshuffle, creating node: ";
5562 Shuffle.dump();
5563 dbgs() << "Reshuffle, creating node: ";
5564 V.dump();
5565 );
5566
5567 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00005568}
5569
5570// check if an EXT instruction can handle the shuffle mask when the
5571// vector sources of the shuffle are the same.
5572static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5573 unsigned NumElts = VT.getVectorNumElements();
5574
5575 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5576 if (M[0] < 0)
5577 return false;
5578
5579 Imm = M[0];
5580
5581 // If this is a VEXT shuffle, the immediate value is the index of the first
5582 // element. The other shuffle indices must be the successive elements after
5583 // the first one.
5584 unsigned ExpectedElt = Imm;
5585 for (unsigned i = 1; i < NumElts; ++i) {
5586 // Increment the expected index. If it wraps around, just follow it
5587 // back to index zero and keep going.
5588 ++ExpectedElt;
5589 if (ExpectedElt == NumElts)
5590 ExpectedElt = 0;
5591
5592 if (M[i] < 0)
5593 continue; // ignore UNDEF indices
5594 if (ExpectedElt != static_cast<unsigned>(M[i]))
5595 return false;
5596 }
5597
5598 return true;
5599}
5600
5601// check if an EXT instruction can handle the shuffle mask when the
5602// vector sources of the shuffle are different.
5603static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5604 unsigned &Imm) {
5605 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005606 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005607
5608 // Benefit form APInt to handle overflow when calculating expected element.
5609 unsigned NumElts = VT.getVectorNumElements();
5610 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5611 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5612 // The following shuffle indices must be the successive elements after the
5613 // first real element.
5614 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5615 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5616 if (FirstWrongElt != M.end())
5617 return false;
5618
5619 // The index of an EXT is the first element if it is not UNDEF.
5620 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005621 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005622 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5623 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5624 // ExpectedElt is the last mask index plus 1.
5625 Imm = ExpectedElt.getZExtValue();
5626
5627 // There are two difference cases requiring to reverse input vectors.
5628 // For example, for vector <4 x i32> we have the following cases,
5629 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5630 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5631 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5632 // to reverse two input vectors.
5633 if (Imm < NumElts)
5634 ReverseEXT = true;
5635 else
5636 Imm -= NumElts;
5637
5638 return true;
5639}
5640
5641/// isREVMask - Check if a vector shuffle corresponds to a REV
5642/// instruction with the specified blocksize. (The order of the elements
5643/// within each block of the vector is reversed.)
5644static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5645 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5646 "Only possible block sizes for REV are: 16, 32, 64");
5647
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005648 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00005649 if (EltSz == 64)
5650 return false;
5651
5652 unsigned NumElts = VT.getVectorNumElements();
5653 unsigned BlockElts = M[0] + 1;
5654 // If the first shuffle index is UNDEF, be optimistic.
5655 if (M[0] < 0)
5656 BlockElts = BlockSize / EltSz;
5657
5658 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5659 return false;
5660
5661 for (unsigned i = 0; i < NumElts; ++i) {
5662 if (M[i] < 0)
5663 continue; // ignore UNDEF indices
5664 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5665 return false;
5666 }
5667
5668 return true;
5669}
5670
5671static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5672 unsigned NumElts = VT.getVectorNumElements();
5673 WhichResult = (M[0] == 0 ? 0 : 1);
5674 unsigned Idx = WhichResult * NumElts / 2;
5675 for (unsigned i = 0; i != NumElts; i += 2) {
5676 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5677 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5678 return false;
5679 Idx += 1;
5680 }
5681
5682 return true;
5683}
5684
5685static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5686 unsigned NumElts = VT.getVectorNumElements();
5687 WhichResult = (M[0] == 0 ? 0 : 1);
5688 for (unsigned i = 0; i != NumElts; ++i) {
5689 if (M[i] < 0)
5690 continue; // ignore UNDEF indices
5691 if ((unsigned)M[i] != 2 * i + WhichResult)
5692 return false;
5693 }
5694
5695 return true;
5696}
5697
5698static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5699 unsigned NumElts = VT.getVectorNumElements();
5700 WhichResult = (M[0] == 0 ? 0 : 1);
5701 for (unsigned i = 0; i < NumElts; i += 2) {
5702 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5703 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5704 return false;
5705 }
5706 return true;
5707}
5708
5709/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5710/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5711/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5712static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5713 unsigned NumElts = VT.getVectorNumElements();
5714 WhichResult = (M[0] == 0 ? 0 : 1);
5715 unsigned Idx = WhichResult * NumElts / 2;
5716 for (unsigned i = 0; i != NumElts; i += 2) {
5717 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5718 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5719 return false;
5720 Idx += 1;
5721 }
5722
5723 return true;
5724}
5725
5726/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5727/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5728/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5729static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5730 unsigned Half = VT.getVectorNumElements() / 2;
5731 WhichResult = (M[0] == 0 ? 0 : 1);
5732 for (unsigned j = 0; j != 2; ++j) {
5733 unsigned Idx = WhichResult;
5734 for (unsigned i = 0; i != Half; ++i) {
5735 int MIdx = M[i + j * Half];
5736 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5737 return false;
5738 Idx += 2;
5739 }
5740 }
5741
5742 return true;
5743}
5744
5745/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5746/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5747/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5748static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5749 unsigned NumElts = VT.getVectorNumElements();
5750 WhichResult = (M[0] == 0 ? 0 : 1);
5751 for (unsigned i = 0; i < NumElts; i += 2) {
5752 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5753 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5754 return false;
5755 }
5756 return true;
5757}
5758
5759static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5760 bool &DstIsLeft, int &Anomaly) {
5761 if (M.size() != static_cast<size_t>(NumInputElements))
5762 return false;
5763
5764 int NumLHSMatch = 0, NumRHSMatch = 0;
5765 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5766
5767 for (int i = 0; i < NumInputElements; ++i) {
5768 if (M[i] == -1) {
5769 ++NumLHSMatch;
5770 ++NumRHSMatch;
5771 continue;
5772 }
5773
5774 if (M[i] == i)
5775 ++NumLHSMatch;
5776 else
5777 LastLHSMismatch = i;
5778
5779 if (M[i] == i + NumInputElements)
5780 ++NumRHSMatch;
5781 else
5782 LastRHSMismatch = i;
5783 }
5784
5785 if (NumLHSMatch == NumInputElements - 1) {
5786 DstIsLeft = true;
5787 Anomaly = LastLHSMismatch;
5788 return true;
5789 } else if (NumRHSMatch == NumInputElements - 1) {
5790 DstIsLeft = false;
5791 Anomaly = LastRHSMismatch;
5792 return true;
5793 }
5794
5795 return false;
5796}
5797
5798static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5799 if (VT.getSizeInBits() != 128)
5800 return false;
5801
5802 unsigned NumElts = VT.getVectorNumElements();
5803
5804 for (int I = 0, E = NumElts / 2; I != E; I++) {
5805 if (Mask[I] != I)
5806 return false;
5807 }
5808
5809 int Offset = NumElts / 2;
5810 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5811 if (Mask[I] != I + SplitLHS * Offset)
5812 return false;
5813 }
5814
5815 return true;
5816}
5817
5818static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5819 SDLoc DL(Op);
5820 EVT VT = Op.getValueType();
5821 SDValue V0 = Op.getOperand(0);
5822 SDValue V1 = Op.getOperand(1);
5823 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5824
5825 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5826 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5827 return SDValue();
5828
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005829 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00005830
5831 if (!isConcatMask(Mask, VT, SplitV0))
5832 return SDValue();
5833
5834 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5835 VT.getVectorNumElements() / 2);
5836 if (SplitV0) {
5837 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005838 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005839 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005840 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005841 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005842 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005843 }
5844 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5845}
5846
5847/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5848/// the specified operations to build the shuffle.
5849static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5850 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005851 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005852 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5853 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5854 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5855
5856 enum {
5857 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5858 OP_VREV,
5859 OP_VDUP0,
5860 OP_VDUP1,
5861 OP_VDUP2,
5862 OP_VDUP3,
5863 OP_VEXT1,
5864 OP_VEXT2,
5865 OP_VEXT3,
5866 OP_VUZPL, // VUZP, left result
5867 OP_VUZPR, // VUZP, right result
5868 OP_VZIPL, // VZIP, left result
5869 OP_VZIPR, // VZIP, right result
5870 OP_VTRNL, // VTRN, left result
5871 OP_VTRNR // VTRN, right result
5872 };
5873
5874 if (OpNum == OP_COPY) {
5875 if (LHSID == (1 * 9 + 2) * 9 + 3)
5876 return LHS;
5877 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5878 return RHS;
5879 }
5880
5881 SDValue OpLHS, OpRHS;
5882 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5883 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5884 EVT VT = OpLHS.getValueType();
5885
5886 switch (OpNum) {
5887 default:
5888 llvm_unreachable("Unknown shuffle opcode!");
5889 case OP_VREV:
5890 // VREV divides the vector in half and swaps within the half.
5891 if (VT.getVectorElementType() == MVT::i32 ||
5892 VT.getVectorElementType() == MVT::f32)
5893 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5894 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005895 if (VT.getVectorElementType() == MVT::i16 ||
5896 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005897 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5898 // vrev <4 x i8> -> REV16
5899 assert(VT.getVectorElementType() == MVT::i8);
5900 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5901 case OP_VDUP0:
5902 case OP_VDUP1:
5903 case OP_VDUP2:
5904 case OP_VDUP3: {
5905 EVT EltTy = VT.getVectorElementType();
5906 unsigned Opcode;
5907 if (EltTy == MVT::i8)
5908 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005909 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005910 Opcode = AArch64ISD::DUPLANE16;
5911 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5912 Opcode = AArch64ISD::DUPLANE32;
5913 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5914 Opcode = AArch64ISD::DUPLANE64;
5915 else
5916 llvm_unreachable("Invalid vector element type?");
5917
5918 if (VT.getSizeInBits() == 64)
5919 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005920 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005921 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5922 }
5923 case OP_VEXT1:
5924 case OP_VEXT2:
5925 case OP_VEXT3: {
5926 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5927 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005928 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005929 }
5930 case OP_VUZPL:
5931 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5932 OpRHS);
5933 case OP_VUZPR:
5934 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5935 OpRHS);
5936 case OP_VZIPL:
5937 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5938 OpRHS);
5939 case OP_VZIPR:
5940 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5941 OpRHS);
5942 case OP_VTRNL:
5943 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5944 OpRHS);
5945 case OP_VTRNR:
5946 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5947 OpRHS);
5948 }
5949}
5950
5951static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5952 SelectionDAG &DAG) {
5953 // Check to see if we can use the TBL instruction.
5954 SDValue V1 = Op.getOperand(0);
5955 SDValue V2 = Op.getOperand(1);
5956 SDLoc DL(Op);
5957
5958 EVT EltVT = Op.getValueType().getVectorElementType();
5959 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5960
5961 SmallVector<SDValue, 8> TBLMask;
5962 for (int Val : ShuffleMask) {
5963 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5964 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005965 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005966 }
5967 }
5968
5969 MVT IndexVT = MVT::v8i8;
5970 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005971 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005972 IndexVT = MVT::v16i8;
5973 IndexLen = 16;
5974 }
5975
5976 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5977 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5978
5979 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005980 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005981 if (IndexLen == 8)
5982 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5983 Shuffle = DAG.getNode(
5984 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005985 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005986 DAG.getBuildVector(IndexVT, DL,
5987 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005988 } else {
5989 if (IndexLen == 8) {
5990 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5991 Shuffle = DAG.getNode(
5992 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005993 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005994 DAG.getBuildVector(IndexVT, DL,
5995 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005996 } else {
5997 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5998 // cannot currently represent the register constraints on the input
5999 // table registers.
6000 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006001 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6002 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006003 Shuffle = DAG.getNode(
6004 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006005 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6006 V2Cst, DAG.getBuildVector(IndexVT, DL,
6007 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006008 }
6009 }
6010 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6011}
6012
6013static unsigned getDUPLANEOp(EVT EltType) {
6014 if (EltType == MVT::i8)
6015 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006016 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006017 return AArch64ISD::DUPLANE16;
6018 if (EltType == MVT::i32 || EltType == MVT::f32)
6019 return AArch64ISD::DUPLANE32;
6020 if (EltType == MVT::i64 || EltType == MVT::f64)
6021 return AArch64ISD::DUPLANE64;
6022
6023 llvm_unreachable("Invalid vector element type?");
6024}
6025
6026SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6027 SelectionDAG &DAG) const {
6028 SDLoc dl(Op);
6029 EVT VT = Op.getValueType();
6030
6031 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6032
6033 // Convert shuffles that are directly supported on NEON to target-specific
6034 // DAG nodes, instead of keeping them as shuffles and matching them again
6035 // during code selection. This is more efficient and avoids the possibility
6036 // of inconsistencies between legalization and selection.
6037 ArrayRef<int> ShuffleMask = SVN->getMask();
6038
6039 SDValue V1 = Op.getOperand(0);
6040 SDValue V2 = Op.getOperand(1);
6041
Craig Topperbc56e3b2016-06-30 04:38:51 +00006042 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006043 int Lane = SVN->getSplatIndex();
6044 // If this is undef splat, generate it via "just" vdup, if possible.
6045 if (Lane == -1)
6046 Lane = 0;
6047
6048 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6049 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6050 V1.getOperand(0));
6051 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6052 // constant. If so, we can just reference the lane's definition directly.
6053 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6054 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6055 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6056
6057 // Otherwise, duplicate from the lane of the input vector.
6058 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6059
6060 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6061 // to make a vector of the same size as this SHUFFLE. We can ignore the
6062 // extract entirely, and canonicalise the concat using WidenVector.
6063 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6064 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6065 V1 = V1.getOperand(0);
6066 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6067 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6068 Lane -= Idx * VT.getVectorNumElements() / 2;
6069 V1 = WidenVector(V1.getOperand(Idx), DAG);
6070 } else if (VT.getSizeInBits() == 64)
6071 V1 = WidenVector(V1, DAG);
6072
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006073 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006074 }
6075
6076 if (isREVMask(ShuffleMask, VT, 64))
6077 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6078 if (isREVMask(ShuffleMask, VT, 32))
6079 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6080 if (isREVMask(ShuffleMask, VT, 16))
6081 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6082
6083 bool ReverseEXT = false;
6084 unsigned Imm;
6085 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6086 if (ReverseEXT)
6087 std::swap(V1, V2);
6088 Imm *= getExtFactor(V1);
6089 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006090 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006091 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006092 Imm *= getExtFactor(V1);
6093 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006094 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006095 }
6096
6097 unsigned WhichResult;
6098 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6099 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6100 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6101 }
6102 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6103 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6104 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6105 }
6106 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6107 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6108 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6109 }
6110
6111 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6112 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6113 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6114 }
6115 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6116 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6117 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6118 }
6119 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6120 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6121 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6122 }
6123
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006124 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006125 return Concat;
6126
6127 bool DstIsLeft;
6128 int Anomaly;
6129 int NumInputElements = V1.getValueType().getVectorNumElements();
6130 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6131 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006132 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006133
6134 SDValue SrcVec = V1;
6135 int SrcLane = ShuffleMask[Anomaly];
6136 if (SrcLane >= NumInputElements) {
6137 SrcVec = V2;
6138 SrcLane -= VT.getVectorNumElements();
6139 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006140 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006141
6142 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006143
6144 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006145 ScalarVT = MVT::i32;
6146
6147 return DAG.getNode(
6148 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6149 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6150 DstLaneV);
6151 }
6152
6153 // If the shuffle is not directly supported and it has 4 elements, use
6154 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6155 unsigned NumElts = VT.getVectorNumElements();
6156 if (NumElts == 4) {
6157 unsigned PFIndexes[4];
6158 for (unsigned i = 0; i != 4; ++i) {
6159 if (ShuffleMask[i] < 0)
6160 PFIndexes[i] = 8;
6161 else
6162 PFIndexes[i] = ShuffleMask[i];
6163 }
6164
6165 // Compute the index in the perfect shuffle table.
6166 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6167 PFIndexes[2] * 9 + PFIndexes[3];
6168 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6169 unsigned Cost = (PFEntry >> 30);
6170
6171 if (Cost <= 4)
6172 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6173 }
6174
6175 return GenerateTBL(Op, ShuffleMask, DAG);
6176}
6177
6178static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6179 APInt &UndefBits) {
6180 EVT VT = BVN->getValueType(0);
6181 APInt SplatBits, SplatUndef;
6182 unsigned SplatBitSize;
6183 bool HasAnyUndefs;
6184 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6185 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6186
6187 for (unsigned i = 0; i < NumSplats; ++i) {
6188 CnstBits <<= SplatBitSize;
6189 UndefBits <<= SplatBitSize;
6190 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6191 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6192 }
6193
6194 return true;
6195 }
6196
6197 return false;
6198}
6199
6200SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6201 SelectionDAG &DAG) const {
6202 BuildVectorSDNode *BVN =
6203 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6204 SDValue LHS = Op.getOperand(0);
6205 SDLoc dl(Op);
6206 EVT VT = Op.getValueType();
6207
6208 if (!BVN)
6209 return Op;
6210
6211 APInt CnstBits(VT.getSizeInBits(), 0);
6212 APInt UndefBits(VT.getSizeInBits(), 0);
6213 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6214 // We only have BIC vector immediate instruction, which is and-not.
6215 CnstBits = ~CnstBits;
6216
6217 // We make use of a little bit of goto ickiness in order to avoid having to
6218 // duplicate the immediate matching logic for the undef toggled case.
6219 bool SecondTry = false;
6220 AttemptModImm:
6221
6222 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6223 CnstBits = CnstBits.zextOrTrunc(64);
6224 uint64_t CnstVal = CnstBits.getZExtValue();
6225
6226 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6227 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6228 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6229 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006230 DAG.getConstant(CnstVal, dl, MVT::i32),
6231 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006232 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006233 }
6234
6235 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6236 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6237 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6238 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006239 DAG.getConstant(CnstVal, dl, MVT::i32),
6240 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006241 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006242 }
6243
6244 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6245 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6246 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6247 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006248 DAG.getConstant(CnstVal, dl, MVT::i32),
6249 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006250 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006251 }
6252
6253 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6254 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6255 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6256 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006257 DAG.getConstant(CnstVal, dl, MVT::i32),
6258 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006259 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006260 }
6261
6262 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6263 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6264 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6265 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006266 DAG.getConstant(CnstVal, dl, MVT::i32),
6267 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006268 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006269 }
6270
6271 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6272 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6273 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6274 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006275 DAG.getConstant(CnstVal, dl, MVT::i32),
6276 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006277 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006278 }
6279 }
6280
6281 if (SecondTry)
6282 goto FailedModImm;
6283 SecondTry = true;
6284 CnstBits = ~UndefBits;
6285 goto AttemptModImm;
6286 }
6287
6288// We can always fall back to a non-immediate AND.
6289FailedModImm:
6290 return Op;
6291}
6292
6293// Specialized code to quickly find if PotentialBVec is a BuildVector that
6294// consists of only the same constant int value, returned in reference arg
6295// ConstVal
6296static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6297 uint64_t &ConstVal) {
6298 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6299 if (!Bvec)
6300 return false;
6301 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6302 if (!FirstElt)
6303 return false;
6304 EVT VT = Bvec->getValueType(0);
6305 unsigned NumElts = VT.getVectorNumElements();
6306 for (unsigned i = 1; i < NumElts; ++i)
6307 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6308 return false;
6309 ConstVal = FirstElt->getZExtValue();
6310 return true;
6311}
6312
6313static unsigned getIntrinsicID(const SDNode *N) {
6314 unsigned Opcode = N->getOpcode();
6315 switch (Opcode) {
6316 default:
6317 return Intrinsic::not_intrinsic;
6318 case ISD::INTRINSIC_WO_CHAIN: {
6319 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6320 if (IID < Intrinsic::num_intrinsics)
6321 return IID;
6322 return Intrinsic::not_intrinsic;
6323 }
6324 }
6325}
6326
6327// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6328// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6329// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6330// Also, logical shift right -> sri, with the same structure.
6331static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6332 EVT VT = N->getValueType(0);
6333
6334 if (!VT.isVector())
6335 return SDValue();
6336
6337 SDLoc DL(N);
6338
6339 // Is the first op an AND?
6340 const SDValue And = N->getOperand(0);
6341 if (And.getOpcode() != ISD::AND)
6342 return SDValue();
6343
6344 // Is the second op an shl or lshr?
6345 SDValue Shift = N->getOperand(1);
6346 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6347 // or AArch64ISD::VLSHR vector, #shift
6348 unsigned ShiftOpc = Shift.getOpcode();
6349 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6350 return SDValue();
6351 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6352
6353 // Is the shift amount constant?
6354 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6355 if (!C2node)
6356 return SDValue();
6357
6358 // Is the and mask vector all constant?
6359 uint64_t C1;
6360 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6361 return SDValue();
6362
6363 // Is C1 == ~C2, taking into account how much one can shift elements of a
6364 // particular size?
6365 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006366 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006367 if (C2 > ElemSizeInBits)
6368 return SDValue();
6369 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6370 if ((C1 & ElemMask) != (~C2 & ElemMask))
6371 return SDValue();
6372
6373 SDValue X = And.getOperand(0);
6374 SDValue Y = Shift.getOperand(0);
6375
6376 unsigned Intrin =
6377 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6378 SDValue ResultSLI =
6379 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006380 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6381 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006382
6383 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6384 DEBUG(N->dump(&DAG));
6385 DEBUG(dbgs() << "into: \n");
6386 DEBUG(ResultSLI->dump(&DAG));
6387
6388 ++NumShiftInserts;
6389 return ResultSLI;
6390}
6391
6392SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6393 SelectionDAG &DAG) const {
6394 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6395 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006396 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006397 return Res;
6398 }
6399
6400 BuildVectorSDNode *BVN =
6401 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6402 SDValue LHS = Op.getOperand(1);
6403 SDLoc dl(Op);
6404 EVT VT = Op.getValueType();
6405
6406 // OR commutes, so try swapping the operands.
6407 if (!BVN) {
6408 LHS = Op.getOperand(0);
6409 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6410 }
6411 if (!BVN)
6412 return Op;
6413
6414 APInt CnstBits(VT.getSizeInBits(), 0);
6415 APInt UndefBits(VT.getSizeInBits(), 0);
6416 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6417 // We make use of a little bit of goto ickiness in order to avoid having to
6418 // duplicate the immediate matching logic for the undef toggled case.
6419 bool SecondTry = false;
6420 AttemptModImm:
6421
6422 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6423 CnstBits = CnstBits.zextOrTrunc(64);
6424 uint64_t CnstVal = CnstBits.getZExtValue();
6425
6426 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6427 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6428 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6429 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006430 DAG.getConstant(CnstVal, dl, MVT::i32),
6431 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006432 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006433 }
6434
6435 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6436 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6437 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6438 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006439 DAG.getConstant(CnstVal, dl, MVT::i32),
6440 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006441 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006442 }
6443
6444 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6445 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6446 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6447 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006448 DAG.getConstant(CnstVal, dl, MVT::i32),
6449 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006450 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006451 }
6452
6453 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6454 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6455 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6456 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006457 DAG.getConstant(CnstVal, dl, MVT::i32),
6458 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006459 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006460 }
6461
6462 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6463 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6464 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6465 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006466 DAG.getConstant(CnstVal, dl, MVT::i32),
6467 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006468 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006469 }
6470
6471 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6472 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6473 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6474 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006475 DAG.getConstant(CnstVal, dl, MVT::i32),
6476 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006477 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006478 }
6479 }
6480
6481 if (SecondTry)
6482 goto FailedModImm;
6483 SecondTry = true;
6484 CnstBits = UndefBits;
6485 goto AttemptModImm;
6486 }
6487
6488// We can always fall back to a non-immediate OR.
6489FailedModImm:
6490 return Op;
6491}
6492
Kevin Qin4473c192014-07-07 02:45:40 +00006493// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6494// be truncated to fit element width.
6495static SDValue NormalizeBuildVector(SDValue Op,
6496 SelectionDAG &DAG) {
6497 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006498 SDLoc dl(Op);
6499 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006500 EVT EltTy= VT.getVectorElementType();
6501
6502 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6503 return Op;
6504
6505 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006506 for (SDValue Lane : Op->ops()) {
6507 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006508 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006509 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006510 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006511 }
6512 Ops.push_back(Lane);
6513 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006514 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006515}
6516
6517SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6518 SelectionDAG &DAG) const {
6519 SDLoc dl(Op);
6520 EVT VT = Op.getValueType();
6521 Op = NormalizeBuildVector(Op, DAG);
6522 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006523
6524 APInt CnstBits(VT.getSizeInBits(), 0);
6525 APInt UndefBits(VT.getSizeInBits(), 0);
6526 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6527 // We make use of a little bit of goto ickiness in order to avoid having to
6528 // duplicate the immediate matching logic for the undef toggled case.
6529 bool SecondTry = false;
6530 AttemptModImm:
6531
6532 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6533 CnstBits = CnstBits.zextOrTrunc(64);
6534 uint64_t CnstVal = CnstBits.getZExtValue();
6535
6536 // Certain magic vector constants (used to express things like NOT
6537 // and NEG) are passed through unmodified. This allows codegen patterns
6538 // for these operations to match. Special-purpose patterns will lower
6539 // these immediates to MOVIs if it proves necessary.
6540 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6541 return Op;
6542
6543 // The many faces of MOVI...
6544 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6545 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6546 if (VT.getSizeInBits() == 128) {
6547 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006548 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006549 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006550 }
6551
6552 // Support the V64 version via subregister insertion.
6553 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006554 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006555 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006556 }
6557
6558 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6559 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6560 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6561 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006562 DAG.getConstant(CnstVal, dl, MVT::i32),
6563 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006564 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006565 }
6566
6567 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6568 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6569 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6570 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006571 DAG.getConstant(CnstVal, dl, MVT::i32),
6572 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006573 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006574 }
6575
6576 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6577 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6578 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6579 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006580 DAG.getConstant(CnstVal, dl, MVT::i32),
6581 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006582 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006583 }
6584
6585 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6586 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6587 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6588 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006589 DAG.getConstant(CnstVal, dl, MVT::i32),
6590 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006591 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006592 }
6593
6594 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6595 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6596 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6597 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006598 DAG.getConstant(CnstVal, dl, MVT::i32),
6599 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006600 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006601 }
6602
6603 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6604 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6605 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6606 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006607 DAG.getConstant(CnstVal, dl, MVT::i32),
6608 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006609 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006610 }
6611
6612 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6613 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6614 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6615 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006616 DAG.getConstant(CnstVal, dl, MVT::i32),
6617 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006618 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006619 }
6620
6621 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6622 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6623 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6624 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006625 DAG.getConstant(CnstVal, dl, MVT::i32),
6626 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006627 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006628 }
6629
6630 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6631 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6632 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6633 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006634 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006635 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006636 }
6637
6638 // The few faces of FMOV...
6639 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6640 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6641 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6642 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006643 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006644 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006645 }
6646
6647 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6648 VT.getSizeInBits() == 128) {
6649 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6650 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006651 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006652 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006653 }
6654
6655 // The many faces of MVNI...
6656 CnstVal = ~CnstVal;
6657 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6658 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6659 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6660 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006661 DAG.getConstant(CnstVal, dl, MVT::i32),
6662 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006663 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006664 }
6665
6666 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6667 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6668 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6669 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006670 DAG.getConstant(CnstVal, dl, MVT::i32),
6671 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006672 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006673 }
6674
6675 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6676 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6677 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6678 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006679 DAG.getConstant(CnstVal, dl, MVT::i32),
6680 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006681 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006682 }
6683
6684 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6685 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6686 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6687 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006688 DAG.getConstant(CnstVal, dl, MVT::i32),
6689 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006690 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006691 }
6692
6693 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6694 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6695 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6696 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006697 DAG.getConstant(CnstVal, dl, MVT::i32),
6698 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006699 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006700 }
6701
6702 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6703 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6704 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6705 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006706 DAG.getConstant(CnstVal, dl, MVT::i32),
6707 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006708 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006709 }
6710
6711 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6712 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6713 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6714 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006715 DAG.getConstant(CnstVal, dl, MVT::i32),
6716 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006717 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006718 }
6719
6720 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6721 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6722 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6723 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006724 DAG.getConstant(CnstVal, dl, MVT::i32),
6725 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006726 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006727 }
6728 }
6729
6730 if (SecondTry)
6731 goto FailedModImm;
6732 SecondTry = true;
6733 CnstBits = UndefBits;
6734 goto AttemptModImm;
6735 }
6736FailedModImm:
6737
6738 // Scan through the operands to find some interesting properties we can
6739 // exploit:
6740 // 1) If only one value is used, we can use a DUP, or
6741 // 2) if only the low element is not undef, we can just insert that, or
6742 // 3) if only one constant value is used (w/ some non-constant lanes),
6743 // we can splat the constant value into the whole vector then fill
6744 // in the non-constant lanes.
6745 // 4) FIXME: If different constant values are used, but we can intelligently
6746 // select the values we'll be overwriting for the non-constant
6747 // lanes such that we can directly materialize the vector
6748 // some other way (MOVI, e.g.), we can be sneaky.
6749 unsigned NumElts = VT.getVectorNumElements();
6750 bool isOnlyLowElement = true;
6751 bool usesOnlyOneValue = true;
6752 bool usesOnlyOneConstantValue = true;
6753 bool isConstant = true;
6754 unsigned NumConstantLanes = 0;
6755 SDValue Value;
6756 SDValue ConstantValue;
6757 for (unsigned i = 0; i < NumElts; ++i) {
6758 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006759 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006760 continue;
6761 if (i > 0)
6762 isOnlyLowElement = false;
6763 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6764 isConstant = false;
6765
6766 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6767 ++NumConstantLanes;
6768 if (!ConstantValue.getNode())
6769 ConstantValue = V;
6770 else if (ConstantValue != V)
6771 usesOnlyOneConstantValue = false;
6772 }
6773
6774 if (!Value.getNode())
6775 Value = V;
6776 else if (V != Value)
6777 usesOnlyOneValue = false;
6778 }
6779
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006780 if (!Value.getNode()) {
6781 DEBUG(dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006782 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006783 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006784
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006785 if (isOnlyLowElement) {
6786 DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
6787 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006788 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006789 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006790
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006791 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00006792 // i32 and try again.
6793 if (usesOnlyOneValue) {
6794 if (!isConstant) {
6795 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006796 Value.getValueType() != VT) {
6797 DEBUG(dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006798 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006799 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006800
6801 // This is actually a DUPLANExx operation, which keeps everything vectory.
6802
Tim Northover3b0846e2014-05-24 12:50:23 +00006803 SDValue Lane = Value.getOperand(1);
6804 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006805 if (Value.getValueSizeInBits() == 64) {
6806 DEBUG(dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
6807 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006808 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006809 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006810
6811 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6812 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6813 }
6814
6815 if (VT.getVectorElementType().isFloatingPoint()) {
6816 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006817 EVT EltTy = VT.getVectorElementType();
6818 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6819 "Unsupported floating-point vector type");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006820 DEBUG(dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
6821 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006822 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006823 for (unsigned i = 0; i < NumElts; ++i)
6824 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6825 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006826 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006827 DEBUG(
6828 dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
6829 Val.dump();
6830 );
Tim Northover3b0846e2014-05-24 12:50:23 +00006831 Val = LowerBUILD_VECTOR(Val, DAG);
6832 if (Val.getNode())
6833 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6834 }
6835 }
6836
6837 // If there was only one constant value used and for more than one lane,
6838 // start by splatting that value, then replace the non-constant lanes. This
6839 // is better than the default, which will perform a separate initialization
6840 // for each lane.
6841 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6842 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6843 // Now insert the non-constant lanes.
6844 for (unsigned i = 0; i < NumElts; ++i) {
6845 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006846 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006847 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6848 // Note that type legalization likely mucked about with the VT of the
6849 // source operand, so we may have to convert it here before inserting.
6850 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6851 }
6852 }
6853 return Val;
6854 }
6855
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006856 // This will generate a load from the constant pool.
6857 if (isConstant) {
6858 DEBUG(dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
6859 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006860 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006861 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006862
6863 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6864 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006865 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006866 return shuffle;
6867 }
6868
6869 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6870 // know the default expansion would otherwise fall back on something even
6871 // worse. For a vector with one or two non-undef values, that's
6872 // scalar_to_vector for the elements followed by a shuffle (provided the
6873 // shuffle is valid for the target) and materialization element by element
6874 // on the stack followed by a load for everything else.
6875 if (!isConstant && !usesOnlyOneValue) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006876 DEBUG(dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
6877 "of INSERT_VECTOR_ELT\n");
6878
Tim Northover3b0846e2014-05-24 12:50:23 +00006879 SDValue Vec = DAG.getUNDEF(VT);
6880 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006881 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00006882
6883 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00006884 // a) Avoid a RMW dependency on the full vector register, and
6885 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00006886 // value is already in an S or D register, and we're forced to emit an
6887 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00006888 //
6889 // We also allow types like i8 and i16 which are illegal scalar but legal
6890 // vector element types. After type-legalization the inserted value is
6891 // extended (i32) and it is safe to cast them to the vector type by ignoring
6892 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6893 if (!Op0.isUndef()) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006894 DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00006895 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006896 ++i;
6897 }
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006898 DEBUG(
6899 if (i < NumElts)
6900 dbgs() << "Creating nodes for the other vector elements:\n";
6901 );
Tim Northover3b0846e2014-05-24 12:50:23 +00006902 for (; i < NumElts; ++i) {
6903 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006904 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006905 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006906 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006907 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6908 }
6909 return Vec;
6910 }
6911
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006912 DEBUG(dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
6913 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006914 return SDValue();
6915}
6916
6917SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6918 SelectionDAG &DAG) const {
6919 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6920
Tim Northovere4b8e132014-07-15 10:00:26 +00006921 // Check for non-constant or out of range lane.
6922 EVT VT = Op.getOperand(0).getValueType();
6923 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6924 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006925 return SDValue();
6926
Tim Northover3b0846e2014-05-24 12:50:23 +00006927
6928 // Insertion/extraction are legal for V128 types.
6929 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006930 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6931 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006932 return Op;
6933
6934 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006935 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006936 return SDValue();
6937
6938 // For V64 types, we perform insertion by expanding the value
6939 // to a V128 type and perform the insertion on that.
6940 SDLoc DL(Op);
6941 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6942 EVT WideTy = WideVec.getValueType();
6943
6944 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6945 Op.getOperand(1), Op.getOperand(2));
6946 // Re-narrow the resultant vector.
6947 return NarrowVector(Node, DAG);
6948}
6949
6950SDValue
6951AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6952 SelectionDAG &DAG) const {
6953 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6954
Tim Northovere4b8e132014-07-15 10:00:26 +00006955 // Check for non-constant or out of range lane.
6956 EVT VT = Op.getOperand(0).getValueType();
6957 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6958 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006959 return SDValue();
6960
Tim Northover3b0846e2014-05-24 12:50:23 +00006961
6962 // Insertion/extraction are legal for V128 types.
6963 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006964 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6965 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006966 return Op;
6967
6968 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006969 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006970 return SDValue();
6971
6972 // For V64 types, we perform extraction by expanding the value
6973 // to a V128 type and perform the extraction on that.
6974 SDLoc DL(Op);
6975 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6976 EVT WideTy = WideVec.getValueType();
6977
6978 EVT ExtrTy = WideTy.getVectorElementType();
6979 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6980 ExtrTy = MVT::i32;
6981
6982 // For extractions, we just return the result directly.
6983 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6984 Op.getOperand(1));
6985}
6986
6987SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6988 SelectionDAG &DAG) const {
6989 EVT VT = Op.getOperand(0).getValueType();
6990 SDLoc dl(Op);
6991 // Just in case...
6992 if (!VT.isVector())
6993 return SDValue();
6994
6995 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6996 if (!Cst)
6997 return SDValue();
6998 unsigned Val = Cst->getZExtValue();
6999
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007000 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007001
7002 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7003 if (Val == 0)
7004 return Op;
7005
Tim Northover3b0846e2014-05-24 12:50:23 +00007006 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7007 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007008 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007009 return Op;
7010
7011 return SDValue();
7012}
7013
Zvi Rackover1b736822017-07-26 08:06:58 +00007014bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007015 if (VT.getVectorNumElements() == 4 &&
7016 (VT.is128BitVector() || VT.is64BitVector())) {
7017 unsigned PFIndexes[4];
7018 for (unsigned i = 0; i != 4; ++i) {
7019 if (M[i] < 0)
7020 PFIndexes[i] = 8;
7021 else
7022 PFIndexes[i] = M[i];
7023 }
7024
7025 // Compute the index in the perfect shuffle table.
7026 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7027 PFIndexes[2] * 9 + PFIndexes[3];
7028 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7029 unsigned Cost = (PFEntry >> 30);
7030
7031 if (Cost <= 4)
7032 return true;
7033 }
7034
7035 bool DummyBool;
7036 int DummyInt;
7037 unsigned DummyUnsigned;
7038
7039 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7040 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7041 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7042 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7043 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7044 isZIPMask(M, VT, DummyUnsigned) ||
7045 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7046 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7047 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7048 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7049 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7050}
7051
7052/// getVShiftImm - Check if this is a valid build_vector for the immediate
7053/// operand of a vector shift operation, where all the elements of the
7054/// build_vector must have the same constant integer value.
7055static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7056 // Ignore bit_converts.
7057 while (Op.getOpcode() == ISD::BITCAST)
7058 Op = Op.getOperand(0);
7059 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7060 APInt SplatBits, SplatUndef;
7061 unsigned SplatBitSize;
7062 bool HasAnyUndefs;
7063 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7064 HasAnyUndefs, ElementBits) ||
7065 SplatBitSize > ElementBits)
7066 return false;
7067 Cnt = SplatBits.getSExtValue();
7068 return true;
7069}
7070
7071/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7072/// operand of a vector shift left operation. That value must be in the range:
7073/// 0 <= Value < ElementBits for a left shift; or
7074/// 0 <= Value <= ElementBits for a long left shift.
7075static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7076 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007077 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007078 if (!getVShiftImm(Op, ElementBits, Cnt))
7079 return false;
7080 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7081}
7082
7083/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007084/// operand of a vector shift right operation. The value must be in the range:
7085/// 1 <= Value <= ElementBits for a right shift; or
7086static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007087 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007088 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007089 if (!getVShiftImm(Op, ElementBits, Cnt))
7090 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007091 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7092}
7093
7094SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7095 SelectionDAG &DAG) const {
7096 EVT VT = Op.getValueType();
7097 SDLoc DL(Op);
7098 int64_t Cnt;
7099
7100 if (!Op.getOperand(1).getValueType().isVector())
7101 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007102 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007103
7104 switch (Op.getOpcode()) {
7105 default:
7106 llvm_unreachable("unexpected shift opcode");
7107
7108 case ISD::SHL:
7109 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007110 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7111 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007112 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007113 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7114 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007115 Op.getOperand(0), Op.getOperand(1));
7116 case ISD::SRA:
7117 case ISD::SRL:
7118 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007119 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007120 unsigned Opc =
7121 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007122 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7123 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007124 }
7125
7126 // Right shift register. Note, there is not a shift right register
7127 // instruction, but the shift left register instruction takes a signed
7128 // value, where negative numbers specify a right shift.
7129 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7130 : Intrinsic::aarch64_neon_ushl;
7131 // negate the shift amount
7132 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7133 SDValue NegShiftLeft =
7134 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007135 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7136 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007137 return NegShiftLeft;
7138 }
7139
7140 return SDValue();
7141}
7142
7143static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7144 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007145 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007146 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007147 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7148 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007149
7150 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7151 APInt CnstBits(VT.getSizeInBits(), 0);
7152 APInt UndefBits(VT.getSizeInBits(), 0);
7153 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7154 bool IsZero = IsCnst && (CnstBits == 0);
7155
7156 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7157 switch (CC) {
7158 default:
7159 return SDValue();
7160 case AArch64CC::NE: {
7161 SDValue Fcmeq;
7162 if (IsZero)
7163 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7164 else
7165 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7166 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7167 }
7168 case AArch64CC::EQ:
7169 if (IsZero)
7170 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7171 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7172 case AArch64CC::GE:
7173 if (IsZero)
7174 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7175 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7176 case AArch64CC::GT:
7177 if (IsZero)
7178 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7179 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7180 case AArch64CC::LS:
7181 if (IsZero)
7182 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7183 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7184 case AArch64CC::LT:
7185 if (!NoNans)
7186 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007187 // If we ignore NaNs then we can use to the MI implementation.
7188 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007189 case AArch64CC::MI:
7190 if (IsZero)
7191 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7192 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7193 }
7194 }
7195
7196 switch (CC) {
7197 default:
7198 return SDValue();
7199 case AArch64CC::NE: {
7200 SDValue Cmeq;
7201 if (IsZero)
7202 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7203 else
7204 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7205 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7206 }
7207 case AArch64CC::EQ:
7208 if (IsZero)
7209 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7210 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7211 case AArch64CC::GE:
7212 if (IsZero)
7213 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7214 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7215 case AArch64CC::GT:
7216 if (IsZero)
7217 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7218 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7219 case AArch64CC::LE:
7220 if (IsZero)
7221 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7222 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7223 case AArch64CC::LS:
7224 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7225 case AArch64CC::LO:
7226 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7227 case AArch64CC::LT:
7228 if (IsZero)
7229 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7230 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7231 case AArch64CC::HI:
7232 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7233 case AArch64CC::HS:
7234 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7235 }
7236}
7237
7238SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7239 SelectionDAG &DAG) const {
7240 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7241 SDValue LHS = Op.getOperand(0);
7242 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007243 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007244 SDLoc dl(Op);
7245
7246 if (LHS.getValueType().getVectorElementType().isInteger()) {
7247 assert(LHS.getValueType() == RHS.getValueType());
7248 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007249 SDValue Cmp =
7250 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7251 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007252 }
7253
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007254 if (LHS.getValueType().getVectorElementType() == MVT::f16)
7255 return SDValue();
7256
Tim Northover3b0846e2014-05-24 12:50:23 +00007257 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7258 LHS.getValueType().getVectorElementType() == MVT::f64);
7259
7260 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7261 // clean. Some of them require two branches to implement.
7262 AArch64CC::CondCode CC1, CC2;
7263 bool ShouldInvert;
7264 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7265
7266 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7267 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007268 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007269 if (!Cmp.getNode())
7270 return SDValue();
7271
7272 if (CC2 != AArch64CC::AL) {
7273 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007274 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007275 if (!Cmp2.getNode())
7276 return SDValue();
7277
Tim Northover45aa89c2015-02-08 00:50:47 +00007278 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007279 }
7280
Tim Northover45aa89c2015-02-08 00:50:47 +00007281 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7282
Tim Northover3b0846e2014-05-24 12:50:23 +00007283 if (ShouldInvert)
7284 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7285
7286 return Cmp;
7287}
7288
Amara Emersonc9916d72017-05-16 21:29:22 +00007289static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7290 SelectionDAG &DAG) {
7291 SDValue VecOp = ScalarOp.getOperand(0);
7292 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7293 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7294 DAG.getConstant(0, DL, MVT::i64));
7295}
7296
7297SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7298 SelectionDAG &DAG) const {
7299 SDLoc dl(Op);
7300 switch (Op.getOpcode()) {
7301 case ISD::VECREDUCE_ADD:
7302 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7303 case ISD::VECREDUCE_SMAX:
7304 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7305 case ISD::VECREDUCE_SMIN:
7306 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7307 case ISD::VECREDUCE_UMAX:
7308 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7309 case ISD::VECREDUCE_UMIN:
7310 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7311 case ISD::VECREDUCE_FMAX: {
7312 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7313 return DAG.getNode(
7314 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7315 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7316 Op.getOperand(0));
7317 }
7318 case ISD::VECREDUCE_FMIN: {
7319 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7320 return DAG.getNode(
7321 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7322 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7323 Op.getOperand(0));
7324 }
7325 default:
7326 llvm_unreachable("Unhandled reduction");
7327 }
7328}
7329
Tim Northover3b0846e2014-05-24 12:50:23 +00007330/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7331/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7332/// specified in the intrinsic calls.
7333bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7334 const CallInst &I,
7335 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007336 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007337 switch (Intrinsic) {
7338 case Intrinsic::aarch64_neon_ld2:
7339 case Intrinsic::aarch64_neon_ld3:
7340 case Intrinsic::aarch64_neon_ld4:
7341 case Intrinsic::aarch64_neon_ld1x2:
7342 case Intrinsic::aarch64_neon_ld1x3:
7343 case Intrinsic::aarch64_neon_ld1x4:
7344 case Intrinsic::aarch64_neon_ld2lane:
7345 case Intrinsic::aarch64_neon_ld3lane:
7346 case Intrinsic::aarch64_neon_ld4lane:
7347 case Intrinsic::aarch64_neon_ld2r:
7348 case Intrinsic::aarch64_neon_ld3r:
7349 case Intrinsic::aarch64_neon_ld4r: {
7350 Info.opc = ISD::INTRINSIC_W_CHAIN;
7351 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007352 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007353 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7354 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7355 Info.offset = 0;
7356 Info.align = 0;
7357 Info.vol = false; // volatile loads with NEON intrinsics not supported
7358 Info.readMem = true;
7359 Info.writeMem = false;
7360 return true;
7361 }
7362 case Intrinsic::aarch64_neon_st2:
7363 case Intrinsic::aarch64_neon_st3:
7364 case Intrinsic::aarch64_neon_st4:
7365 case Intrinsic::aarch64_neon_st1x2:
7366 case Intrinsic::aarch64_neon_st1x3:
7367 case Intrinsic::aarch64_neon_st1x4:
7368 case Intrinsic::aarch64_neon_st2lane:
7369 case Intrinsic::aarch64_neon_st3lane:
7370 case Intrinsic::aarch64_neon_st4lane: {
7371 Info.opc = ISD::INTRINSIC_VOID;
7372 // Conservatively set memVT to the entire set of vectors stored.
7373 unsigned NumElts = 0;
7374 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7375 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7376 if (!ArgTy->isVectorTy())
7377 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007378 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007379 }
7380 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7381 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7382 Info.offset = 0;
7383 Info.align = 0;
7384 Info.vol = false; // volatile stores with NEON intrinsics not supported
7385 Info.readMem = false;
7386 Info.writeMem = true;
7387 return true;
7388 }
7389 case Intrinsic::aarch64_ldaxr:
7390 case Intrinsic::aarch64_ldxr: {
7391 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7392 Info.opc = ISD::INTRINSIC_W_CHAIN;
7393 Info.memVT = MVT::getVT(PtrTy->getElementType());
7394 Info.ptrVal = I.getArgOperand(0);
7395 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007396 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007397 Info.vol = true;
7398 Info.readMem = true;
7399 Info.writeMem = false;
7400 return true;
7401 }
7402 case Intrinsic::aarch64_stlxr:
7403 case Intrinsic::aarch64_stxr: {
7404 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7405 Info.opc = ISD::INTRINSIC_W_CHAIN;
7406 Info.memVT = MVT::getVT(PtrTy->getElementType());
7407 Info.ptrVal = I.getArgOperand(1);
7408 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007409 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007410 Info.vol = true;
7411 Info.readMem = false;
7412 Info.writeMem = true;
7413 return true;
7414 }
7415 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007416 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007417 Info.opc = ISD::INTRINSIC_W_CHAIN;
7418 Info.memVT = MVT::i128;
7419 Info.ptrVal = I.getArgOperand(0);
7420 Info.offset = 0;
7421 Info.align = 16;
7422 Info.vol = true;
7423 Info.readMem = true;
7424 Info.writeMem = false;
7425 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007426 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007427 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007428 Info.opc = ISD::INTRINSIC_W_CHAIN;
7429 Info.memVT = MVT::i128;
7430 Info.ptrVal = I.getArgOperand(2);
7431 Info.offset = 0;
7432 Info.align = 16;
7433 Info.vol = true;
7434 Info.readMem = false;
7435 Info.writeMem = true;
7436 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007437 default:
7438 break;
7439 }
7440
7441 return false;
7442}
7443
7444// Truncations from 64-bit GPR to 32-bit GPR is free.
7445bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7446 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7447 return false;
7448 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7449 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007450 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007451}
7452bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007453 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007454 return false;
7455 unsigned NumBits1 = VT1.getSizeInBits();
7456 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007457 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007458}
7459
Chad Rosier54390052015-02-23 19:15:16 +00007460/// Check if it is profitable to hoist instruction in then/else to if.
7461/// Not profitable if I and it's user can form a FMA instruction
7462/// because we prefer FMSUB/FMADD.
7463bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7464 if (I->getOpcode() != Instruction::FMul)
7465 return true;
7466
Davide Italiano3e9986f2017-04-18 00:29:54 +00007467 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00007468 return true;
7469
7470 Instruction *User = I->user_back();
7471
7472 if (User &&
7473 !(User->getOpcode() == Instruction::FSub ||
7474 User->getOpcode() == Instruction::FAdd))
7475 return true;
7476
7477 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007478 const DataLayout &DL = I->getModule()->getDataLayout();
7479 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007480
Eric Christopher114fa1c2016-02-29 22:50:49 +00007481 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7482 isOperationLegalOrCustom(ISD::FMA, VT) &&
7483 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7484 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007485}
7486
Tim Northover3b0846e2014-05-24 12:50:23 +00007487// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7488// 64-bit GPR.
7489bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7490 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7491 return false;
7492 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7493 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007494 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007495}
7496bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007497 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007498 return false;
7499 unsigned NumBits1 = VT1.getSizeInBits();
7500 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007501 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007502}
7503
7504bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7505 EVT VT1 = Val.getValueType();
7506 if (isZExtFree(VT1, VT2)) {
7507 return true;
7508 }
7509
7510 if (Val.getOpcode() != ISD::LOAD)
7511 return false;
7512
7513 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007514 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7515 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7516 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007517}
7518
Quentin Colombet6843ac42015-03-31 20:52:32 +00007519bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7520 if (isa<FPExtInst>(Ext))
7521 return false;
7522
Haicheng Wu50692a22017-08-01 21:26:45 +00007523 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00007524 if (Ext->getType()->isVectorTy())
7525 return false;
7526
7527 for (const Use &U : Ext->uses()) {
7528 // The extension is free if we can fold it with a left shift in an
7529 // addressing mode or an arithmetic operation: add, sub, and cmp.
7530
7531 // Is there a shift?
7532 const Instruction *Instr = cast<Instruction>(U.getUser());
7533
7534 // Is this a constant shift?
7535 switch (Instr->getOpcode()) {
7536 case Instruction::Shl:
7537 if (!isa<ConstantInt>(Instr->getOperand(1)))
7538 return false;
7539 break;
7540 case Instruction::GetElementPtr: {
7541 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007542 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00007543 std::advance(GTI, U.getOperandNo()-1);
7544 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007545 // This extension will end up with a shift because of the scaling factor.
7546 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7547 // Get the shift amount based on the scaling factor:
7548 // log2(sizeof(IdxTy)) - log2(8).
7549 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007550 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007551 // Is the constant foldable in the shift of the addressing mode?
7552 // I.e., shift amount is between 1 and 4 inclusive.
7553 if (ShiftAmt == 0 || ShiftAmt > 4)
7554 return false;
7555 break;
7556 }
7557 case Instruction::Trunc:
7558 // Check if this is a noop.
7559 // trunc(sext ty1 to ty2) to ty1.
7560 if (Instr->getType() == Ext->getOperand(0)->getType())
7561 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007562 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007563 default:
7564 return false;
7565 }
7566
7567 // At this point we can use the bfm family, so this extension is free
7568 // for that use.
7569 }
7570 return true;
7571}
7572
Tim Northover3b0846e2014-05-24 12:50:23 +00007573bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7574 unsigned &RequiredAligment) const {
7575 if (!LoadedType.isSimple() ||
7576 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7577 return false;
7578 // Cyclone supports unaligned accesses.
7579 RequiredAligment = 0;
7580 unsigned NumBits = LoadedType.getSizeInBits();
7581 return NumBits == 32 || NumBits == 64;
7582}
7583
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007584/// A helper function for determining the number of interleaved accesses we
7585/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007586unsigned
7587AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7588 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007589 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7590}
7591
Geoff Berryb1e87142017-07-14 21:44:12 +00007592MachineMemOperand::Flags
7593AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
7594 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
7595 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
7596 return MOStridedAccess;
7597 return MachineMemOperand::MONone;
7598}
7599
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007600bool AArch64TargetLowering::isLegalInterleavedAccessType(
7601 VectorType *VecTy, const DataLayout &DL) const {
7602
7603 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7604 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7605
7606 // Ensure the number of vector elements is greater than 1.
7607 if (VecTy->getNumElements() < 2)
7608 return false;
7609
7610 // Ensure the element type is legal.
7611 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7612 return false;
7613
7614 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7615 // 128 will be split into multiple interleaved accesses.
7616 return VecSize == 64 || VecSize % 128 == 0;
7617}
7618
Hao Liu7ec8ee32015-06-26 02:32:07 +00007619/// \brief Lower an interleaved load into a ldN intrinsic.
7620///
7621/// E.g. Lower an interleaved load (Factor = 2):
7622/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7623/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7624/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7625///
7626/// Into:
7627/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7628/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7629/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7630bool AArch64TargetLowering::lowerInterleavedLoad(
7631 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7632 ArrayRef<unsigned> Indices, unsigned Factor) const {
7633 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7634 "Invalid interleave factor");
7635 assert(!Shuffles.empty() && "Empty shufflevector input");
7636 assert(Shuffles.size() == Indices.size() &&
7637 "Unmatched number of shufflevectors and indices");
7638
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007639 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007640
7641 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007642
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007643 // Skip if we do not have NEON and skip illegal vector types. We can
7644 // "legalize" wide vector types into multiple interleaved accesses as long as
7645 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007646 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007647 return false;
7648
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007649 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7650
Hao Liu7ec8ee32015-06-26 02:32:07 +00007651 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7652 // load integer vectors first and then convert to pointer vectors.
7653 Type *EltTy = VecTy->getVectorElementType();
7654 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007655 VecTy =
7656 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007657
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007658 IRBuilder<> Builder(LI);
7659
7660 // The base address of the load.
7661 Value *BaseAddr = LI->getPointerOperand();
7662
7663 if (NumLoads > 1) {
7664 // If we're going to generate more than one load, reset the sub-vector type
7665 // to something legal.
7666 VecTy = VectorType::get(VecTy->getVectorElementType(),
7667 VecTy->getVectorNumElements() / NumLoads);
7668
7669 // We will compute the pointer operand of each load from the original base
7670 // address using GEPs. Cast the base address to a pointer to the scalar
7671 // element type.
7672 BaseAddr = Builder.CreateBitCast(
7673 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7674 LI->getPointerAddressSpace()));
7675 }
7676
Hao Liu7ec8ee32015-06-26 02:32:07 +00007677 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7678 Type *Tys[2] = {VecTy, PtrTy};
7679 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7680 Intrinsic::aarch64_neon_ld3,
7681 Intrinsic::aarch64_neon_ld4};
7682 Function *LdNFunc =
7683 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7684
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007685 // Holds sub-vectors extracted from the load intrinsic return values. The
7686 // sub-vectors are associated with the shufflevector instructions they will
7687 // replace.
7688 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007689
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007690 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00007691
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007692 // If we're generating more than one load, compute the base address of
7693 // subsequent loads as an offset from the previous.
7694 if (LoadCount > 0)
7695 BaseAddr = Builder.CreateConstGEP1_32(
7696 BaseAddr, VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007697
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007698 CallInst *LdN = Builder.CreateCall(
7699 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00007700
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007701 // Extract and store the sub-vectors returned by the load intrinsic.
7702 for (unsigned i = 0; i < Shuffles.size(); i++) {
7703 ShuffleVectorInst *SVI = Shuffles[i];
7704 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00007705
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007706 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7707
7708 // Convert the integer vector to pointer vector if the element is pointer.
7709 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00007710 SubVec = Builder.CreateIntToPtr(
7711 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
7712 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007713 SubVecs[SVI].push_back(SubVec);
7714 }
7715 }
7716
7717 // Replace uses of the shufflevector instructions with the sub-vectors
7718 // returned by the load intrinsic. If a shufflevector instruction is
7719 // associated with more than one sub-vector, those sub-vectors will be
7720 // concatenated into a single wide vector.
7721 for (ShuffleVectorInst *SVI : Shuffles) {
7722 auto &SubVec = SubVecs[SVI];
7723 auto *WideVec =
7724 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7725 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007726 }
7727
7728 return true;
7729}
7730
Hao Liu7ec8ee32015-06-26 02:32:07 +00007731/// \brief Lower an interleaved store into a stN intrinsic.
7732///
7733/// E.g. Lower an interleaved store (Factor = 3):
7734/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007735/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00007736/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7737///
7738/// Into:
7739/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7740/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7741/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7742/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7743///
7744/// Note that the new shufflevectors will be removed and we'll only generate one
7745/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007746///
7747/// Example for a more general valid mask (Factor 3). Lower:
7748/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7749/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7750/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7751///
7752/// Into:
7753/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7754/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7755/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7756/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00007757bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7758 ShuffleVectorInst *SVI,
7759 unsigned Factor) const {
7760 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7761 "Invalid interleave factor");
7762
7763 VectorType *VecTy = SVI->getType();
7764 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7765 "Invalid interleaved store");
7766
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007767 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007768 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007769 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007770
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007771 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007772
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007773 // Skip if we do not have NEON and skip illegal vector types. We can
7774 // "legalize" wide vector types into multiple interleaved accesses as long as
7775 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007776 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007777 return false;
7778
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007779 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7780
Hao Liu7ec8ee32015-06-26 02:32:07 +00007781 Value *Op0 = SVI->getOperand(0);
7782 Value *Op1 = SVI->getOperand(1);
7783 IRBuilder<> Builder(SI);
7784
7785 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7786 // vectors to integer vectors.
7787 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007788 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007789 unsigned NumOpElts =
7790 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7791
7792 // Convert to the corresponding integer vector.
7793 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7794 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7795 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7796
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007797 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007798 }
7799
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007800 // The base address of the store.
7801 Value *BaseAddr = SI->getPointerOperand();
7802
7803 if (NumStores > 1) {
7804 // If we're going to generate more than one store, reset the lane length
7805 // and sub-vector type to something legal.
7806 LaneLen /= NumStores;
7807 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7808
7809 // We will compute the pointer operand of each store from the original base
7810 // address using GEPs. Cast the base address to a pointer to the scalar
7811 // element type.
7812 BaseAddr = Builder.CreateBitCast(
7813 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7814 SI->getPointerAddressSpace()));
7815 }
7816
7817 auto Mask = SVI->getShuffleMask();
7818
Hao Liu7ec8ee32015-06-26 02:32:07 +00007819 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7820 Type *Tys[2] = {SubVecTy, PtrTy};
7821 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7822 Intrinsic::aarch64_neon_st3,
7823 Intrinsic::aarch64_neon_st4};
7824 Function *StNFunc =
7825 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7826
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007827 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00007828
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007829 SmallVector<Value *, 5> Ops;
7830
7831 // Split the shufflevector operands into sub vectors for the new stN call.
7832 for (unsigned i = 0; i < Factor; i++) {
7833 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7834 if (Mask[IdxI] >= 0) {
7835 Ops.push_back(Builder.CreateShuffleVector(
7836 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7837 } else {
7838 unsigned StartMask = 0;
7839 for (unsigned j = 1; j < LaneLen; j++) {
7840 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7841 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7842 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7843 break;
7844 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007845 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007846 // Note: Filling undef gaps with random elements is ok, since
7847 // those elements were being written anyway (with undefs).
7848 // In the case of all undefs we're defaulting to using elems from 0
7849 // Note: StartMask cannot be negative, it's checked in
7850 // isReInterleaveMask
7851 Ops.push_back(Builder.CreateShuffleVector(
7852 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007853 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007854 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007855
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007856 // If we generating more than one store, we compute the base address of
7857 // subsequent stores as an offset from the previous.
7858 if (StoreCount > 0)
7859 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7860
7861 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7862 Builder.CreateCall(StNFunc, Ops);
7863 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007864 return true;
7865}
7866
Tim Northover3b0846e2014-05-24 12:50:23 +00007867static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7868 unsigned AlignCheck) {
7869 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7870 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7871}
7872
7873EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7874 unsigned SrcAlign, bool IsMemset,
7875 bool ZeroMemset,
7876 bool MemcpyStrSrc,
7877 MachineFunction &MF) const {
7878 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7879 // instruction to materialize the v2i64 zero and one store (with restrictive
7880 // addressing mode). Just do two i64 store of zero-registers.
7881 bool Fast;
7882 const Function *F = MF.getFunction();
7883 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007884 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007885 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007886 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007887 return MVT::f128;
7888
Lang Hames90333852015-04-09 03:40:33 +00007889 if (Size >= 8 &&
7890 (memOpAlign(SrcAlign, DstAlign, 8) ||
7891 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7892 return MVT::i64;
7893
7894 if (Size >= 4 &&
7895 (memOpAlign(SrcAlign, DstAlign, 4) ||
7896 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007897 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007898
7899 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007900}
7901
7902// 12-bit optionally shifted immediates are legal for adds.
7903bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00007904 if (Immed == std::numeric_limits<int64_t>::min()) {
7905 DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00007906 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00007907 }
Geoff Berry486f49c2016-06-07 16:48:43 +00007908 // Same encoding for add/sub, just flip the sign.
7909 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00007910 bool IsLegal = ((Immed >> 12) == 0 ||
7911 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7912 DEBUG(dbgs() << "Is " << Immed << " legal add imm: " <<
7913 (IsLegal ? "yes" : "no") << "\n");
7914 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00007915}
7916
7917// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7918// immediates is the same as for an add or a sub.
7919bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007920 return isLegalAddImmediate(Immed);
7921}
7922
7923/// isLegalAddressingMode - Return true if the addressing mode represented
7924/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007925bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7926 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00007927 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007928 // AArch64 has five basic addressing modes:
7929 // reg
7930 // reg + 9-bit signed offset
7931 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7932 // reg1 + reg2
7933 // reg + SIZE_IN_BYTES * reg
7934
7935 // No global is ever allowed as a base.
7936 if (AM.BaseGV)
7937 return false;
7938
7939 // No reg+reg+imm addressing.
7940 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7941 return false;
7942
7943 // check reg + imm case:
7944 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7945 uint64_t NumBytes = 0;
7946 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007947 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007948 NumBytes = NumBits / 8;
7949 if (!isPowerOf2_64(NumBits))
7950 NumBytes = 0;
7951 }
7952
7953 if (!AM.Scale) {
7954 int64_t Offset = AM.BaseOffs;
7955
7956 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00007957 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00007958 return true;
7959
7960 // 12-bit unsigned offset
7961 unsigned shift = Log2_64(NumBytes);
7962 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7963 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7964 (Offset >> shift) << shift == Offset)
7965 return true;
7966 return false;
7967 }
7968
7969 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7970
Haicheng Wu6bb0e392016-12-21 21:40:47 +00007971 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007972}
7973
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007974int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7975 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007976 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007977 // Scaling factors are not free at all.
7978 // Operands | Rt Latency
7979 // -------------------------------------------
7980 // Rt, [Xn, Xm] | 4
7981 // -------------------------------------------
7982 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7983 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007984 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007985 // Scale represents reg2 * scale, thus account for 1 if
7986 // it is not equal to 0 or 1.
7987 return AM.Scale != 0 && AM.Scale != 1;
7988 return -1;
7989}
7990
7991bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7992 VT = VT.getScalarType();
7993
7994 if (!VT.isSimple())
7995 return false;
7996
7997 switch (VT.getSimpleVT().SimpleTy) {
7998 case MVT::f32:
7999 case MVT::f64:
8000 return true;
8001 default:
8002 break;
8003 }
8004
8005 return false;
8006}
8007
8008const MCPhysReg *
8009AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8010 // LR is a callee-save register, but we must treat it as clobbered by any call
8011 // site. Hence we include LR in the scratch registers, which are in turn added
8012 // as implicit-defs for stackmaps and patchpoints.
8013 static const MCPhysReg ScratchRegs[] = {
8014 AArch64::X16, AArch64::X17, AArch64::LR, 0
8015 };
8016 return ScratchRegs;
8017}
8018
8019bool
8020AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
8021 EVT VT = N->getValueType(0);
8022 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8023 // it with shift to let it be lowered to UBFX.
8024 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8025 isa<ConstantSDNode>(N->getOperand(1))) {
8026 uint64_t TruncMask = N->getConstantOperandVal(1);
8027 if (isMask_64(TruncMask) &&
8028 N->getOperand(0).getOpcode() == ISD::SRL &&
8029 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8030 return false;
8031 }
8032 return true;
8033}
8034
8035bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8036 Type *Ty) const {
8037 assert(Ty->isIntegerTy());
8038
8039 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8040 if (BitSize == 0)
8041 return false;
8042
8043 int64_t Val = Imm.getSExtValue();
8044 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8045 return true;
8046
8047 if ((int64_t)Val < 0)
8048 Val = ~Val;
8049 if (BitSize == 32)
8050 Val &= (1LL << 32) - 1;
8051
8052 unsigned LZ = countLeadingZeros((uint64_t)Val);
8053 unsigned Shift = (63 - LZ) / 16;
8054 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008055 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008056}
8057
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008058/// Turn vector tests of the signbit in the form of:
8059/// xor (sra X, elt_size(X)-1), -1
8060/// into:
8061/// cmge X, X, #0
8062static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8063 const AArch64Subtarget *Subtarget) {
8064 EVT VT = N->getValueType(0);
8065 if (!Subtarget->hasNEON() || !VT.isVector())
8066 return SDValue();
8067
8068 // There must be a shift right algebraic before the xor, and the xor must be a
8069 // 'not' operation.
8070 SDValue Shift = N->getOperand(0);
8071 SDValue Ones = N->getOperand(1);
8072 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8073 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8074 return SDValue();
8075
8076 // The shift should be smearing the sign bit across each vector element.
8077 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8078 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8079 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8080 return SDValue();
8081
8082 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8083}
8084
Tim Northover3b0846e2014-05-24 12:50:23 +00008085// Generate SUBS and CSEL for integer abs.
8086static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8087 EVT VT = N->getValueType(0);
8088
8089 SDValue N0 = N->getOperand(0);
8090 SDValue N1 = N->getOperand(1);
8091 SDLoc DL(N);
8092
8093 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8094 // and change it to SUB and CSEL.
8095 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8096 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8097 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8098 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8099 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008100 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008101 N0.getOperand(0));
8102 // Generate SUBS & CSEL.
8103 SDValue Cmp =
8104 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008105 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008106 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008107 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008108 SDValue(Cmp.getNode(), 1));
8109 }
8110 return SDValue();
8111}
8112
Tim Northover3b0846e2014-05-24 12:50:23 +00008113static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8114 TargetLowering::DAGCombinerInfo &DCI,
8115 const AArch64Subtarget *Subtarget) {
8116 if (DCI.isBeforeLegalizeOps())
8117 return SDValue();
8118
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008119 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8120 return Cmp;
8121
Tim Northover3b0846e2014-05-24 12:50:23 +00008122 return performIntegerAbsCombine(N, DAG);
8123}
8124
Chad Rosier17020f92014-07-23 14:57:52 +00008125SDValue
8126AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8127 SelectionDAG &DAG,
8128 std::vector<SDNode *> *Created) const {
Reid Klecknerb5180542017-03-21 16:57:19 +00008129 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008130 if (isIntDivCheap(N->getValueType(0), Attr))
8131 return SDValue(N,0); // Lower SDIV as SDIV
8132
Chad Rosier17020f92014-07-23 14:57:52 +00008133 // fold (sdiv X, pow2)
8134 EVT VT = N->getValueType(0);
8135 if ((VT != MVT::i32 && VT != MVT::i64) ||
8136 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8137 return SDValue();
8138
8139 SDLoc DL(N);
8140 SDValue N0 = N->getOperand(0);
8141 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008142 SDValue Zero = DAG.getConstant(0, DL, VT);
8143 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008144
8145 // Add (N0 < 0) ? Pow2 - 1 : 0;
8146 SDValue CCVal;
8147 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8148 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8149 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8150
8151 if (Created) {
8152 Created->push_back(Cmp.getNode());
8153 Created->push_back(Add.getNode());
8154 Created->push_back(CSel.getNode());
8155 }
8156
8157 // Divide by pow2.
8158 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008159 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008160
8161 // If we're dividing by a positive value, we're done. Otherwise, we must
8162 // negate the result.
8163 if (Divisor.isNonNegative())
8164 return SRA;
8165
8166 if (Created)
8167 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008168 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008169}
8170
Tim Northover3b0846e2014-05-24 12:50:23 +00008171static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8172 TargetLowering::DAGCombinerInfo &DCI,
8173 const AArch64Subtarget *Subtarget) {
8174 if (DCI.isBeforeLegalizeOps())
8175 return SDValue();
8176
Chad Rosier31ee8132016-11-11 17:07:37 +00008177 // The below optimizations require a constant RHS.
8178 if (!isa<ConstantSDNode>(N->getOperand(1)))
8179 return SDValue();
8180
8181 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8182 const APInt &ConstValue = C->getAPIntValue();
8183
Tim Northover3b0846e2014-05-24 12:50:23 +00008184 // Multiplication of a power of two plus/minus one can be done more
8185 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8186 // future CPUs have a cheaper MADD instruction, this may need to be
8187 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8188 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008189 // More aggressively, some multiplications N0 * C can be lowered to
8190 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8191 // e.g. 6=3*2=(2+1)*2.
8192 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8193 // which equals to (1+2)*16-(1+2).
8194 SDValue N0 = N->getOperand(0);
8195 // TrailingZeroes is used to test if the mul can be lowered to
8196 // shift+add+shift.
8197 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8198 if (TrailingZeroes) {
8199 // Conservatively do not lower to shift+add+shift if the mul might be
8200 // folded into smul or umul.
8201 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8202 isZeroExtended(N0.getNode(), DAG)))
8203 return SDValue();
8204 // Conservatively do not lower to shift+add+shift if the mul might be
8205 // folded into madd or msub.
8206 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8207 N->use_begin()->getOpcode() == ISD::SUB))
8208 return SDValue();
8209 }
8210 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8211 // and shift+add+shift.
8212 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8213
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008214 unsigned ShiftAmt, AddSubOpc;
8215 // Is the shifted value the LHS operand of the add/sub?
8216 bool ShiftValUseIsN0 = true;
8217 // Do we need to negate the result?
8218 bool NegateResult = false;
8219
Chad Rosier31ee8132016-11-11 17:07:37 +00008220 if (ConstValue.isNonNegative()) {
8221 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00008222 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00008223 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8224 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008225 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00008226 if (SCVMinus1.isPowerOf2()) {
8227 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008228 AddSubOpc = ISD::ADD;
8229 } else if (CVPlus1.isPowerOf2()) {
8230 ShiftAmt = CVPlus1.logBase2();
8231 AddSubOpc = ISD::SUB;
8232 } else
8233 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00008234 } else {
8235 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00008236 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008237 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008238 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008239 if (CVNegPlus1.isPowerOf2()) {
8240 ShiftAmt = CVNegPlus1.logBase2();
8241 AddSubOpc = ISD::SUB;
8242 ShiftValUseIsN0 = false;
8243 } else if (CVNegMinus1.isPowerOf2()) {
8244 ShiftAmt = CVNegMinus1.logBase2();
8245 AddSubOpc = ISD::ADD;
8246 NegateResult = true;
8247 } else
8248 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008249 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008250
8251 SDLoc DL(N);
8252 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008253 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008254 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8255
8256 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8257 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8258 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008259 assert(!(NegateResult && TrailingZeroes) &&
8260 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008261 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008262 if (NegateResult)
8263 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8264 // Shift the result.
8265 if (TrailingZeroes)
8266 return DAG.getNode(ISD::SHL, DL, VT, Res,
8267 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8268 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00008269}
8270
Jim Grosbachf7502c42014-07-18 00:40:52 +00008271static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8272 SelectionDAG &DAG) {
8273 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8274 // optimize away operation when it's from a constant.
8275 //
8276 // The general transformation is:
8277 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8278 // AND(VECTOR_CMP(x,y), constant2)
8279 // constant2 = UNARYOP(constant)
8280
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008281 // Early exit if this isn't a vector operation, the operand of the
8282 // unary operation isn't a bitwise AND, or if the sizes of the operations
8283 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00008284 EVT VT = N->getValueType(0);
8285 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008286 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8287 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008288 return SDValue();
8289
Jim Grosbach724e4382014-07-23 20:41:43 +00008290 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00008291 // make the transformation for non-constant splats as well, but it's unclear
8292 // that would be a benefit as it would not eliminate any operations, just
8293 // perform one more step in scalar code before moving to the vector unit.
8294 if (BuildVectorSDNode *BV =
8295 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00008296 // Bail out if the vector isn't a constant.
8297 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008298 return SDValue();
8299
8300 // Everything checks out. Build up the new and improved node.
8301 SDLoc DL(N);
8302 EVT IntVT = BV->getValueType(0);
8303 // Create a new constant of the appropriate type for the transformed
8304 // DAG.
8305 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8306 // The AND node needs bitcasts to/from an integer vector type around it.
8307 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8308 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8309 N->getOperand(0)->getOperand(0), MaskConst);
8310 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8311 return Res;
8312 }
8313
8314 return SDValue();
8315}
8316
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008317static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8318 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00008319 // First try to optimize away the conversion when it's conditionally from
8320 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008321 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00008322 return Res;
8323
Tim Northover3b0846e2014-05-24 12:50:23 +00008324 EVT VT = N->getValueType(0);
8325 if (VT != MVT::f32 && VT != MVT::f64)
8326 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00008327
Tim Northover3b0846e2014-05-24 12:50:23 +00008328 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008329 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00008330 return SDValue();
8331
8332 // If the result of an integer load is only used by an integer-to-float
8333 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00008334 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00008335 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008336 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008337 // Do not change the width of a volatile load.
8338 !cast<LoadSDNode>(N0)->isVolatile()) {
8339 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8340 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00008341 LN0->getPointerInfo(), LN0->getAlignment(),
8342 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008343
8344 // Make sure successors of the original load stay after it by updating them
8345 // to use the new Chain.
8346 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8347
8348 unsigned Opcode =
8349 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8350 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8351 }
8352
8353 return SDValue();
8354}
8355
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008356/// Fold a floating-point multiply by power of two into floating-point to
8357/// fixed-point conversion.
8358static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00008359 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008360 const AArch64Subtarget *Subtarget) {
8361 if (!Subtarget->hasNEON())
8362 return SDValue();
8363
8364 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00008365 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8366 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008367 return SDValue();
8368
8369 SDValue ConstVec = Op->getOperand(1);
8370 if (!isa<BuildVectorSDNode>(ConstVec))
8371 return SDValue();
8372
8373 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8374 uint32_t FloatBits = FloatTy.getSizeInBits();
8375 if (FloatBits != 32 && FloatBits != 64)
8376 return SDValue();
8377
8378 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8379 uint32_t IntBits = IntTy.getSizeInBits();
8380 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8381 return SDValue();
8382
8383 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8384 if (IntBits > FloatBits)
8385 return SDValue();
8386
8387 BitVector UndefElements;
8388 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8389 int32_t Bits = IntBits == 64 ? 64 : 32;
8390 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8391 if (C == -1 || C == 0 || C > Bits)
8392 return SDValue();
8393
8394 MVT ResTy;
8395 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8396 switch (NumLanes) {
8397 default:
8398 return SDValue();
8399 case 2:
8400 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8401 break;
8402 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00008403 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008404 break;
8405 }
8406
Silviu Barangafa00ba32016-08-08 13:13:57 +00008407 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8408 return SDValue();
8409
8410 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8411 "Illegal vector type after legalization");
8412
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008413 SDLoc DL(N);
8414 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8415 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8416 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8417 SDValue FixConv =
8418 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8419 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8420 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8421 // We can handle smaller integers by generating an extra trunc.
8422 if (IntBits < FloatBits)
8423 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8424
8425 return FixConv;
8426}
8427
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008428/// Fold a floating-point divide by power of two into fixed-point to
8429/// floating-point conversion.
8430static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00008431 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008432 const AArch64Subtarget *Subtarget) {
8433 if (!Subtarget->hasNEON())
8434 return SDValue();
8435
8436 SDValue Op = N->getOperand(0);
8437 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00008438 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8439 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008440 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8441 return SDValue();
8442
8443 SDValue ConstVec = N->getOperand(1);
8444 if (!isa<BuildVectorSDNode>(ConstVec))
8445 return SDValue();
8446
8447 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8448 int32_t IntBits = IntTy.getSizeInBits();
8449 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8450 return SDValue();
8451
8452 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8453 int32_t FloatBits = FloatTy.getSizeInBits();
8454 if (FloatBits != 32 && FloatBits != 64)
8455 return SDValue();
8456
8457 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8458 if (IntBits > FloatBits)
8459 return SDValue();
8460
8461 BitVector UndefElements;
8462 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8463 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8464 if (C == -1 || C == 0 || C > FloatBits)
8465 return SDValue();
8466
8467 MVT ResTy;
8468 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8469 switch (NumLanes) {
8470 default:
8471 return SDValue();
8472 case 2:
8473 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8474 break;
8475 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00008476 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008477 break;
8478 }
8479
Tim Northover85cf5642016-08-26 18:52:31 +00008480 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8481 return SDValue();
8482
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008483 SDLoc DL(N);
8484 SDValue ConvInput = Op.getOperand(0);
8485 bool IsSigned = Opc == ISD::SINT_TO_FP;
8486 if (IntBits < FloatBits)
8487 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8488 ResTy, ConvInput);
8489
8490 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8491 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8492 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8493 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8494 DAG.getConstant(C, DL, MVT::i32));
8495}
8496
Tim Northover3b0846e2014-05-24 12:50:23 +00008497/// An EXTR instruction is made up of two shifts, ORed together. This helper
8498/// searches for and classifies those shifts.
8499static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8500 bool &FromHi) {
8501 if (N.getOpcode() == ISD::SHL)
8502 FromHi = false;
8503 else if (N.getOpcode() == ISD::SRL)
8504 FromHi = true;
8505 else
8506 return false;
8507
8508 if (!isa<ConstantSDNode>(N.getOperand(1)))
8509 return false;
8510
8511 ShiftAmount = N->getConstantOperandVal(1);
8512 Src = N->getOperand(0);
8513 return true;
8514}
8515
8516/// EXTR instruction extracts a contiguous chunk of bits from two existing
8517/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00008518/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
8519/// with an EXTR. Can't quite be done in TableGen because the two immediates
8520/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00008521static SDValue tryCombineToEXTR(SDNode *N,
8522 TargetLowering::DAGCombinerInfo &DCI) {
8523 SelectionDAG &DAG = DCI.DAG;
8524 SDLoc DL(N);
8525 EVT VT = N->getValueType(0);
8526
8527 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8528
8529 if (VT != MVT::i32 && VT != MVT::i64)
8530 return SDValue();
8531
8532 SDValue LHS;
8533 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008534 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008535 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8536 return SDValue();
8537
8538 SDValue RHS;
8539 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008540 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008541 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8542 return SDValue();
8543
8544 // If they're both trying to come from the high part of the register, they're
8545 // not really an EXTR.
8546 if (LHSFromHi == RHSFromHi)
8547 return SDValue();
8548
8549 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8550 return SDValue();
8551
8552 if (LHSFromHi) {
8553 std::swap(LHS, RHS);
8554 std::swap(ShiftLHS, ShiftRHS);
8555 }
8556
8557 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008558 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008559}
8560
8561static SDValue tryCombineToBSL(SDNode *N,
8562 TargetLowering::DAGCombinerInfo &DCI) {
8563 EVT VT = N->getValueType(0);
8564 SelectionDAG &DAG = DCI.DAG;
8565 SDLoc DL(N);
8566
8567 if (!VT.isVector())
8568 return SDValue();
8569
8570 SDValue N0 = N->getOperand(0);
8571 if (N0.getOpcode() != ISD::AND)
8572 return SDValue();
8573
8574 SDValue N1 = N->getOperand(1);
8575 if (N1.getOpcode() != ISD::AND)
8576 return SDValue();
8577
8578 // We only have to look for constant vectors here since the general, variable
8579 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008580 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008581 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8582 for (int i = 1; i >= 0; --i)
8583 for (int j = 1; j >= 0; --j) {
8584 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8585 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8586 if (!BVN0 || !BVN1)
8587 continue;
8588
8589 bool FoundMatch = true;
8590 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8591 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8592 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8593 if (!CN0 || !CN1 ||
8594 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8595 FoundMatch = false;
8596 break;
8597 }
8598 }
8599
8600 if (FoundMatch)
8601 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8602 N0->getOperand(1 - i), N1->getOperand(1 - j));
8603 }
8604
8605 return SDValue();
8606}
8607
8608static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8609 const AArch64Subtarget *Subtarget) {
8610 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00008611 SelectionDAG &DAG = DCI.DAG;
8612 EVT VT = N->getValueType(0);
8613
8614 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8615 return SDValue();
8616
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008617 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008618 return Res;
8619
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008620 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008621 return Res;
8622
8623 return SDValue();
8624}
8625
Chad Rosier14aa2ad2016-05-26 19:41:33 +00008626static SDValue performSRLCombine(SDNode *N,
8627 TargetLowering::DAGCombinerInfo &DCI) {
8628 SelectionDAG &DAG = DCI.DAG;
8629 EVT VT = N->getValueType(0);
8630 if (VT != MVT::i32 && VT != MVT::i64)
8631 return SDValue();
8632
8633 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8634 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8635 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8636 SDValue N0 = N->getOperand(0);
8637 if (N0.getOpcode() == ISD::BSWAP) {
8638 SDLoc DL(N);
8639 SDValue N1 = N->getOperand(1);
8640 SDValue N00 = N0.getOperand(0);
8641 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8642 uint64_t ShiftAmt = C->getZExtValue();
8643 if (VT == MVT::i32 && ShiftAmt == 16 &&
8644 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8645 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8646 if (VT == MVT::i64 && ShiftAmt == 32 &&
8647 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8648 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8649 }
8650 }
8651 return SDValue();
8652}
8653
Tim Northover3b0846e2014-05-24 12:50:23 +00008654static SDValue performBitcastCombine(SDNode *N,
8655 TargetLowering::DAGCombinerInfo &DCI,
8656 SelectionDAG &DAG) {
8657 // Wait 'til after everything is legalized to try this. That way we have
8658 // legal vector types and such.
8659 if (DCI.isBeforeLegalizeOps())
8660 return SDValue();
8661
8662 // Remove extraneous bitcasts around an extract_subvector.
8663 // For example,
8664 // (v4i16 (bitconvert
8665 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8666 // becomes
8667 // (extract_subvector ((v8i16 ...), (i64 4)))
8668
8669 // Only interested in 64-bit vectors as the ultimate result.
8670 EVT VT = N->getValueType(0);
8671 if (!VT.isVector())
8672 return SDValue();
8673 if (VT.getSimpleVT().getSizeInBits() != 64)
8674 return SDValue();
8675 // Is the operand an extract_subvector starting at the beginning or halfway
8676 // point of the vector? A low half may also come through as an
8677 // EXTRACT_SUBREG, so look for that, too.
8678 SDValue Op0 = N->getOperand(0);
8679 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8680 !(Op0->isMachineOpcode() &&
8681 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8682 return SDValue();
8683 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8684 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8685 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8686 return SDValue();
8687 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8688 if (idx != AArch64::dsub)
8689 return SDValue();
8690 // The dsub reference is equivalent to a lane zero subvector reference.
8691 idx = 0;
8692 }
8693 // Look through the bitcast of the input to the extract.
8694 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8695 return SDValue();
8696 SDValue Source = Op0->getOperand(0)->getOperand(0);
8697 // If the source type has twice the number of elements as our destination
8698 // type, we know this is an extract of the high or low half of the vector.
8699 EVT SVT = Source->getValueType(0);
8700 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8701 return SDValue();
8702
8703 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8704
8705 // Create the simplified form to just extract the low or high half of the
8706 // vector directly rather than bothering with the bitcasts.
8707 SDLoc dl(N);
8708 unsigned NumElements = VT.getVectorNumElements();
8709 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008710 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008711 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8712 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008713 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008714 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8715 Source, SubReg),
8716 0);
8717 }
8718}
8719
8720static SDValue performConcatVectorsCombine(SDNode *N,
8721 TargetLowering::DAGCombinerInfo &DCI,
8722 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008723 SDLoc dl(N);
8724 EVT VT = N->getValueType(0);
8725 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8726
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008727 // Optimize concat_vectors of truncated vectors, where the intermediate
8728 // type is illegal, to avoid said illegality, e.g.,
8729 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8730 // (v2i16 (truncate (v2i64)))))
8731 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008732 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8733 // (v4i32 (bitcast (v2i64))),
8734 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008735 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8736 // on both input and result type, so we might generate worse code.
8737 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8738 if (N->getNumOperands() == 2 &&
8739 N0->getOpcode() == ISD::TRUNCATE &&
8740 N1->getOpcode() == ISD::TRUNCATE) {
8741 SDValue N00 = N0->getOperand(0);
8742 SDValue N10 = N1->getOperand(0);
8743 EVT N00VT = N00.getValueType();
8744
8745 if (N00VT == N10.getValueType() &&
8746 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8747 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008748 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8749 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8750 for (size_t i = 0; i < Mask.size(); ++i)
8751 Mask[i] = i * 2;
8752 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8753 DAG.getVectorShuffle(
8754 MidVT, dl,
8755 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8756 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008757 }
8758 }
8759
Tim Northover3b0846e2014-05-24 12:50:23 +00008760 // Wait 'til after everything is legalized to try this. That way we have
8761 // legal vector types and such.
8762 if (DCI.isBeforeLegalizeOps())
8763 return SDValue();
8764
Tim Northover3b0846e2014-05-24 12:50:23 +00008765 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8766 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8767 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008768 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008769 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008770 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008771 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008772 }
8773
8774 // Canonicalise concat_vectors so that the right-hand vector has as few
8775 // bit-casts as possible before its real operation. The primary matching
8776 // destination for these operations will be the narrowing "2" instructions,
8777 // which depend on the operation being performed on this right-hand vector.
8778 // For example,
8779 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8780 // becomes
8781 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8782
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008783 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008784 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008785 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008786 MVT RHSTy = RHS.getValueType().getSimpleVT();
8787 // If the RHS is not a vector, this is not the pattern we're looking for.
8788 if (!RHSTy.isVector())
8789 return SDValue();
8790
8791 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8792
8793 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8794 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008795 return DAG.getNode(ISD::BITCAST, dl, VT,
8796 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8797 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8798 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008799}
8800
8801static SDValue tryCombineFixedPointConvert(SDNode *N,
8802 TargetLowering::DAGCombinerInfo &DCI,
8803 SelectionDAG &DAG) {
8804 // Wait 'til after everything is legalized to try this. That way we have
8805 // legal vector types and such.
8806 if (DCI.isBeforeLegalizeOps())
8807 return SDValue();
8808 // Transform a scalar conversion of a value from a lane extract into a
8809 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8810 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8811 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8812 //
8813 // The second form interacts better with instruction selection and the
8814 // register allocator to avoid cross-class register copies that aren't
8815 // coalescable due to a lane reference.
8816
8817 // Check the operand and see if it originates from a lane extract.
8818 SDValue Op1 = N->getOperand(1);
8819 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8820 // Yep, no additional predication needed. Perform the transform.
8821 SDValue IID = N->getOperand(0);
8822 SDValue Shift = N->getOperand(2);
8823 SDValue Vec = Op1.getOperand(0);
8824 SDValue Lane = Op1.getOperand(1);
8825 EVT ResTy = N->getValueType(0);
8826 EVT VecResTy;
8827 SDLoc DL(N);
8828
8829 // The vector width should be 128 bits by the time we get here, even
8830 // if it started as 64 bits (the extract_vector handling will have
8831 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008832 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008833 "unexpected vector size on extract_vector_elt!");
8834 if (Vec.getValueType() == MVT::v4i32)
8835 VecResTy = MVT::v4f32;
8836 else if (Vec.getValueType() == MVT::v2i64)
8837 VecResTy = MVT::v2f64;
8838 else
Craig Topper2a30d782014-06-18 05:05:13 +00008839 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008840
8841 SDValue Convert =
8842 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8843 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8844 }
8845 return SDValue();
8846}
8847
8848// AArch64 high-vector "long" operations are formed by performing the non-high
8849// version on an extract_subvector of each operand which gets the high half:
8850//
8851// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8852//
8853// However, there are cases which don't have an extract_high explicitly, but
8854// have another operation that can be made compatible with one for free. For
8855// example:
8856//
8857// (dupv64 scalar) --> (extract_high (dup128 scalar))
8858//
8859// This routine does the actual conversion of such DUPs, once outer routines
8860// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008861// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8862// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008863static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008864 switch (N.getOpcode()) {
8865 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008866 case AArch64ISD::DUPLANE8:
8867 case AArch64ISD::DUPLANE16:
8868 case AArch64ISD::DUPLANE32:
8869 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008870 case AArch64ISD::MOVI:
8871 case AArch64ISD::MOVIshift:
8872 case AArch64ISD::MOVIedit:
8873 case AArch64ISD::MOVImsl:
8874 case AArch64ISD::MVNIshift:
8875 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008876 break;
8877 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008878 // FMOV could be supported, but isn't very useful, as it would only occur
8879 // if you passed a bitcast' floating point immediate to an eligible long
8880 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008881 return SDValue();
8882 }
8883
8884 MVT NarrowTy = N.getSimpleValueType();
8885 if (!NarrowTy.is64BitVector())
8886 return SDValue();
8887
8888 MVT ElementTy = NarrowTy.getVectorElementType();
8889 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008890 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008891
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008892 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008893 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8894 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008895 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008896}
8897
8898static bool isEssentiallyExtractSubvector(SDValue N) {
8899 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8900 return true;
8901
8902 return N.getOpcode() == ISD::BITCAST &&
8903 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8904}
8905
8906/// \brief Helper structure to keep track of ISD::SET_CC operands.
8907struct GenericSetCCInfo {
8908 const SDValue *Opnd0;
8909 const SDValue *Opnd1;
8910 ISD::CondCode CC;
8911};
8912
8913/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8914struct AArch64SetCCInfo {
8915 const SDValue *Cmp;
8916 AArch64CC::CondCode CC;
8917};
8918
8919/// \brief Helper structure to keep track of SetCC information.
8920union SetCCInfo {
8921 GenericSetCCInfo Generic;
8922 AArch64SetCCInfo AArch64;
8923};
8924
8925/// \brief Helper structure to be able to read SetCC information. If set to
8926/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8927/// GenericSetCCInfo.
8928struct SetCCInfoAndKind {
8929 SetCCInfo Info;
8930 bool IsAArch64;
8931};
8932
8933/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8934/// an
8935/// AArch64 lowered one.
8936/// \p SetCCInfo is filled accordingly.
8937/// \post SetCCInfo is meanginfull only when this function returns true.
8938/// \return True when Op is a kind of SET_CC operation.
8939static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8940 // If this is a setcc, this is straight forward.
8941 if (Op.getOpcode() == ISD::SETCC) {
8942 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8943 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8944 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8945 SetCCInfo.IsAArch64 = false;
8946 return true;
8947 }
8948 // Otherwise, check if this is a matching csel instruction.
8949 // In other words:
8950 // - csel 1, 0, cc
8951 // - csel 0, 1, !cc
8952 if (Op.getOpcode() != AArch64ISD::CSEL)
8953 return false;
8954 // Set the information about the operands.
8955 // TODO: we want the operands of the Cmp not the csel
8956 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8957 SetCCInfo.IsAArch64 = true;
8958 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8959 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8960
8961 // Check that the operands matches the constraints:
8962 // (1) Both operands must be constants.
8963 // (2) One must be 1 and the other must be 0.
8964 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8965 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8966
8967 // Check (1).
8968 if (!TValue || !FValue)
8969 return false;
8970
8971 // Check (2).
8972 if (!TValue->isOne()) {
8973 // Update the comparison when we are interested in !cc.
8974 std::swap(TValue, FValue);
8975 SetCCInfo.Info.AArch64.CC =
8976 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8977 }
8978 return TValue->isOne() && FValue->isNullValue();
8979}
8980
8981// Returns true if Op is setcc or zext of setcc.
8982static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8983 if (isSetCC(Op, Info))
8984 return true;
8985 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8986 isSetCC(Op->getOperand(0), Info));
8987}
8988
8989// The folding we want to perform is:
8990// (add x, [zext] (setcc cc ...) )
8991// -->
8992// (csel x, (add x, 1), !cc ...)
8993//
8994// The latter will get matched to a CSINC instruction.
8995static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8996 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8997 SDValue LHS = Op->getOperand(0);
8998 SDValue RHS = Op->getOperand(1);
8999 SetCCInfoAndKind InfoAndKind;
9000
9001 // If neither operand is a SET_CC, give up.
9002 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9003 std::swap(LHS, RHS);
9004 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9005 return SDValue();
9006 }
9007
9008 // FIXME: This could be generatized to work for FP comparisons.
9009 EVT CmpVT = InfoAndKind.IsAArch64
9010 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9011 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9012 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9013 return SDValue();
9014
9015 SDValue CCVal;
9016 SDValue Cmp;
9017 SDLoc dl(Op);
9018 if (InfoAndKind.IsAArch64) {
9019 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009020 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9021 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009022 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9023 } else
9024 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9025 *InfoAndKind.Info.Generic.Opnd1,
9026 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9027 CCVal, DAG, dl);
9028
9029 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009030 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009031 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9032}
9033
9034// The basic add/sub long vector instructions have variants with "2" on the end
9035// which act on the high-half of their inputs. They are normally matched by
9036// patterns like:
9037//
9038// (add (zeroext (extract_high LHS)),
9039// (zeroext (extract_high RHS)))
9040// -> uaddl2 vD, vN, vM
9041//
9042// However, if one of the extracts is something like a duplicate, this
9043// instruction can still be used profitably. This function puts the DAG into a
9044// more appropriate form for those patterns to trigger.
9045static SDValue performAddSubLongCombine(SDNode *N,
9046 TargetLowering::DAGCombinerInfo &DCI,
9047 SelectionDAG &DAG) {
9048 if (DCI.isBeforeLegalizeOps())
9049 return SDValue();
9050
9051 MVT VT = N->getSimpleValueType(0);
9052 if (!VT.is128BitVector()) {
9053 if (N->getOpcode() == ISD::ADD)
9054 return performSetccAddFolding(N, DAG);
9055 return SDValue();
9056 }
9057
9058 // Make sure both branches are extended in the same way.
9059 SDValue LHS = N->getOperand(0);
9060 SDValue RHS = N->getOperand(1);
9061 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9062 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9063 LHS.getOpcode() != RHS.getOpcode())
9064 return SDValue();
9065
9066 unsigned ExtType = LHS.getOpcode();
9067
9068 // It's not worth doing if at least one of the inputs isn't already an
9069 // extract, but we don't know which it'll be so we have to try both.
9070 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9071 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9072 if (!RHS.getNode())
9073 return SDValue();
9074
9075 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9076 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9077 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9078 if (!LHS.getNode())
9079 return SDValue();
9080
9081 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9082 }
9083
9084 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9085}
9086
9087// Massage DAGs which we can use the high-half "long" operations on into
9088// something isel will recognize better. E.g.
9089//
9090// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9091// (aarch64_neon_umull (extract_high (v2i64 vec)))
9092// (extract_high (v2i64 (dup128 scalar)))))
9093//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009094static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009095 TargetLowering::DAGCombinerInfo &DCI,
9096 SelectionDAG &DAG) {
9097 if (DCI.isBeforeLegalizeOps())
9098 return SDValue();
9099
Hal Finkelcd8664c2015-12-11 23:11:52 +00009100 SDValue LHS = N->getOperand(1);
9101 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009102 assert(LHS.getValueType().is64BitVector() &&
9103 RHS.getValueType().is64BitVector() &&
9104 "unexpected shape for long operation");
9105
9106 // Either node could be a DUP, but it's not worth doing both of them (you'd
9107 // just as well use the non-high version) so look for a corresponding extract
9108 // operation on the other "wing".
9109 if (isEssentiallyExtractSubvector(LHS)) {
9110 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9111 if (!RHS.getNode())
9112 return SDValue();
9113 } else if (isEssentiallyExtractSubvector(RHS)) {
9114 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9115 if (!LHS.getNode())
9116 return SDValue();
9117 }
9118
Hal Finkelcd8664c2015-12-11 23:11:52 +00009119 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9120 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009121}
9122
9123static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9124 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9125 unsigned ElemBits = ElemTy.getSizeInBits();
9126
9127 int64_t ShiftAmount;
9128 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9129 APInt SplatValue, SplatUndef;
9130 unsigned SplatBitSize;
9131 bool HasAnyUndefs;
9132 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9133 HasAnyUndefs, ElemBits) ||
9134 SplatBitSize != ElemBits)
9135 return SDValue();
9136
9137 ShiftAmount = SplatValue.getSExtValue();
9138 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9139 ShiftAmount = CVN->getSExtValue();
9140 } else
9141 return SDValue();
9142
9143 unsigned Opcode;
9144 bool IsRightShift;
9145 switch (IID) {
9146 default:
9147 llvm_unreachable("Unknown shift intrinsic");
9148 case Intrinsic::aarch64_neon_sqshl:
9149 Opcode = AArch64ISD::SQSHL_I;
9150 IsRightShift = false;
9151 break;
9152 case Intrinsic::aarch64_neon_uqshl:
9153 Opcode = AArch64ISD::UQSHL_I;
9154 IsRightShift = false;
9155 break;
9156 case Intrinsic::aarch64_neon_srshl:
9157 Opcode = AArch64ISD::SRSHR_I;
9158 IsRightShift = true;
9159 break;
9160 case Intrinsic::aarch64_neon_urshl:
9161 Opcode = AArch64ISD::URSHR_I;
9162 IsRightShift = true;
9163 break;
9164 case Intrinsic::aarch64_neon_sqshlu:
9165 Opcode = AArch64ISD::SQSHLU_I;
9166 IsRightShift = false;
9167 break;
9168 }
9169
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009170 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9171 SDLoc dl(N);
9172 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9173 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9174 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9175 SDLoc dl(N);
9176 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9177 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9178 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009179
9180 return SDValue();
9181}
9182
9183// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9184// the intrinsics must be legal and take an i32, this means there's almost
9185// certainly going to be a zext in the DAG which we can eliminate.
9186static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9187 SDValue AndN = N->getOperand(2);
9188 if (AndN.getOpcode() != ISD::AND)
9189 return SDValue();
9190
9191 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9192 if (!CMask || CMask->getZExtValue() != Mask)
9193 return SDValue();
9194
9195 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9196 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9197}
9198
Ahmed Bougachafab58922015-03-10 20:45:38 +00009199static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9200 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009201 SDLoc dl(N);
9202 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9203 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009204 N->getOperand(1).getSimpleValueType(),
9205 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009206 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009207}
9208
Tim Northover3b0846e2014-05-24 12:50:23 +00009209static SDValue performIntrinsicCombine(SDNode *N,
9210 TargetLowering::DAGCombinerInfo &DCI,
9211 const AArch64Subtarget *Subtarget) {
9212 SelectionDAG &DAG = DCI.DAG;
9213 unsigned IID = getIntrinsicID(N);
9214 switch (IID) {
9215 default:
9216 break;
9217 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9218 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9219 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00009220 case Intrinsic::aarch64_neon_saddv:
9221 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9222 case Intrinsic::aarch64_neon_uaddv:
9223 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9224 case Intrinsic::aarch64_neon_sminv:
9225 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9226 case Intrinsic::aarch64_neon_uminv:
9227 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9228 case Intrinsic::aarch64_neon_smaxv:
9229 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9230 case Intrinsic::aarch64_neon_umaxv:
9231 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009232 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00009233 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009234 N->getOperand(1), N->getOperand(2));
9235 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00009236 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009237 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00009238 case Intrinsic::aarch64_neon_fmaxnm:
9239 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9240 N->getOperand(1), N->getOperand(2));
9241 case Intrinsic::aarch64_neon_fminnm:
9242 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9243 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009244 case Intrinsic::aarch64_neon_smull:
9245 case Intrinsic::aarch64_neon_umull:
9246 case Intrinsic::aarch64_neon_pmull:
9247 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00009248 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009249 case Intrinsic::aarch64_neon_sqshl:
9250 case Intrinsic::aarch64_neon_uqshl:
9251 case Intrinsic::aarch64_neon_sqshlu:
9252 case Intrinsic::aarch64_neon_srshl:
9253 case Intrinsic::aarch64_neon_urshl:
9254 return tryCombineShiftImm(IID, N, DAG);
9255 case Intrinsic::aarch64_crc32b:
9256 case Intrinsic::aarch64_crc32cb:
9257 return tryCombineCRC32(0xff, N, DAG);
9258 case Intrinsic::aarch64_crc32h:
9259 case Intrinsic::aarch64_crc32ch:
9260 return tryCombineCRC32(0xffff, N, DAG);
9261 }
9262 return SDValue();
9263}
9264
9265static SDValue performExtendCombine(SDNode *N,
9266 TargetLowering::DAGCombinerInfo &DCI,
9267 SelectionDAG &DAG) {
9268 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9269 // we can convert that DUP into another extract_high (of a bigger DUP), which
9270 // helps the backend to decide that an sabdl2 would be useful, saving a real
9271 // extract_high operation.
9272 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00009273 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009274 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00009275 unsigned IID = getIntrinsicID(ABDNode);
9276 if (IID == Intrinsic::aarch64_neon_sabd ||
9277 IID == Intrinsic::aarch64_neon_uabd) {
9278 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9279 if (!NewABD.getNode())
9280 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009281
Hal Finkelcd8664c2015-12-11 23:11:52 +00009282 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9283 NewABD);
9284 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009285 }
9286
9287 // This is effectively a custom type legalization for AArch64.
9288 //
9289 // Type legalization will split an extend of a small, legal, type to a larger
9290 // illegal type by first splitting the destination type, often creating
9291 // illegal source types, which then get legalized in isel-confusing ways,
9292 // leading to really terrible codegen. E.g.,
9293 // %result = v8i32 sext v8i8 %value
9294 // becomes
9295 // %losrc = extract_subreg %value, ...
9296 // %hisrc = extract_subreg %value, ...
9297 // %lo = v4i32 sext v4i8 %losrc
9298 // %hi = v4i32 sext v4i8 %hisrc
9299 // Things go rapidly downhill from there.
9300 //
9301 // For AArch64, the [sz]ext vector instructions can only go up one element
9302 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9303 // take two instructions.
9304 //
9305 // This implies that the most efficient way to do the extend from v8i8
9306 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9307 // the normal splitting to happen for the v8i16->v8i32.
9308
9309 // This is pre-legalization to catch some cases where the default
9310 // type legalization will create ill-tempered code.
9311 if (!DCI.isBeforeLegalizeOps())
9312 return SDValue();
9313
9314 // We're only interested in cleaning things up for non-legal vector types
9315 // here. If both the source and destination are legal, things will just
9316 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00009317 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00009318 EVT ResVT = N->getValueType(0);
9319 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9320 return SDValue();
9321 // If the vector type isn't a simple VT, it's beyond the scope of what
9322 // we're worried about here. Let legalization do its thing and hope for
9323 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00009324 SDValue Src = N->getOperand(0);
9325 EVT SrcVT = Src->getValueType(0);
9326 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00009327 return SDValue();
9328
Tim Northover3b0846e2014-05-24 12:50:23 +00009329 // If the source VT is a 64-bit vector, we can play games and get the
9330 // better results we want.
9331 if (SrcVT.getSizeInBits() != 64)
9332 return SDValue();
9333
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009334 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009335 unsigned ElementCount = SrcVT.getVectorNumElements();
9336 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9337 SDLoc DL(N);
9338 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9339
9340 // Now split the rest of the operation into two halves, each with a 64
9341 // bit source.
9342 EVT LoVT, HiVT;
9343 SDValue Lo, Hi;
9344 unsigned NumElements = ResVT.getVectorNumElements();
9345 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9346 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9347 ResVT.getVectorElementType(), NumElements / 2);
9348
9349 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9350 LoVT.getVectorNumElements());
9351 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009352 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009353 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009354 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009355 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9356 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9357
9358 // Now combine the parts back together so we still have a single result
9359 // like the combiner expects.
9360 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9361}
9362
Geoff Berry8301c642016-11-16 19:35:19 +00009363static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9364 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009365 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +00009366 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009367
9368 // Create scalar stores. This is at least as good as the code sequence for a
9369 // split unaligned store which is a dup.s, ext.b, and two stores.
9370 // Most of the time the three stores should be replaced by store pair
9371 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009372 SDLoc DL(&St);
9373 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009374 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +00009375
John Brawn3a9c8422017-02-06 18:07:20 +00009376 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009377 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +00009378 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +00009379 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009380
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009381 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +00009382 if (BasePtr->getOpcode() == ISD::ADD &&
9383 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9384 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9385 BasePtr = BasePtr->getOperand(0);
9386 }
9387
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009388 unsigned Offset = EltOffset;
9389 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +00009390 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009391 SDValue OffsetPtr =
9392 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9393 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009394 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +00009395 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009396 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009397 Offset += EltOffset;
9398 }
9399 return NewST1;
9400}
9401
Geoff Berry526c5052016-11-14 19:39:04 +00009402/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9403/// load store optimizer pass will merge them to store pair stores. This should
9404/// be better than a movi to create the vector zero followed by a vector store
9405/// if the zero constant is not re-used, since one instructions and one register
9406/// live range will be removed.
9407///
9408/// For example, the final generated code should be:
9409///
9410/// stp xzr, xzr, [x0]
9411///
9412/// instead of:
9413///
9414/// movi v0.2d, #0
9415/// str q0, [x0]
9416///
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009417static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9418 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +00009419 EVT VT = StVal.getValueType();
9420
Geoff Berry8301c642016-11-16 19:35:19 +00009421 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9422 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +00009423 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +00009424 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9425 VT.getVectorElementType().getSizeInBits() == 64) ||
9426 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9427 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +00009428 return SDValue();
9429
9430 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9431 return SDValue();
9432
9433 // If the zero constant has more than one use then the vector store could be
9434 // better since the constant mov will be amortized and stp q instructions
9435 // should be able to be formed.
9436 if (!StVal.hasOneUse())
9437 return SDValue();
9438
9439 // If the immediate offset of the address operand is too large for the stp
9440 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009441 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9442 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +00009443 if (Offset < -512 || Offset > 504)
9444 return SDValue();
9445 }
9446
9447 for (int I = 0; I < NumVecElts; ++I) {
9448 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +00009449 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +00009450 return SDValue();
9451 }
Geoff Berry8301c642016-11-16 19:35:19 +00009452
Geoff Berry526c5052016-11-14 19:39:04 +00009453 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9454 // undoing this transformation.
Geoff Berry8301c642016-11-16 19:35:19 +00009455 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9456 ? DAG.getRegister(AArch64::WZR, MVT::i32)
9457 : DAG.getRegister(AArch64::XZR, MVT::i64);
9458 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +00009459}
9460
Tim Northover3b0846e2014-05-24 12:50:23 +00009461/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9462/// value. The load store optimizer pass will merge them to store pair stores.
9463/// This has better performance than a splat of the scalar followed by a split
9464/// vector store. Even if the stores are not merged it is four stores vs a dup,
9465/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009466static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9467 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009468 EVT VT = StVal.getValueType();
9469
9470 // Don't replace floating point stores, they possibly won't be transformed to
9471 // stp because of the store pair suppress pass.
9472 if (VT.isFloatingPoint())
9473 return SDValue();
9474
Tim Northover3b0846e2014-05-24 12:50:23 +00009475 // We can express a splat as store pair(s) for 2 or 4 elements.
9476 unsigned NumVecElts = VT.getVectorNumElements();
9477 if (NumVecElts != 4 && NumVecElts != 2)
9478 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009479
9480 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +00009481 // Make sure that each of the relevant vector element locations are inserted
9482 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9483 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9484 SDValue SplatVal;
9485 for (unsigned I = 0; I < NumVecElts; ++I) {
9486 // Check for insert vector elements.
9487 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +00009488 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009489
9490 // Check that same value is inserted at each vector element.
9491 if (I == 0)
9492 SplatVal = StVal.getOperand(1);
9493 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +00009494 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009495
9496 // Check insert element index.
9497 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9498 if (!CIndex)
9499 return SDValue();
9500 uint64_t IndexVal = CIndex->getZExtValue();
9501 if (IndexVal >= NumVecElts)
9502 return SDValue();
9503 IndexNotInserted.reset(IndexVal);
9504
9505 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009506 }
Geoff Berry25fa4992016-11-11 19:25:20 +00009507 // Check that all vector element locations were inserted to.
9508 if (IndexNotInserted.any())
9509 return SDValue();
9510
Geoff Berry8301c642016-11-16 19:35:19 +00009511 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009512}
9513
Geoff Berry8301c642016-11-16 19:35:19 +00009514static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9515 SelectionDAG &DAG,
9516 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009517 if (!DCI.isBeforeLegalize())
9518 return SDValue();
9519
9520 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +00009521 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +00009522 return SDValue();
9523
Geoff Berry526c5052016-11-14 19:39:04 +00009524 SDValue StVal = S->getValue();
9525 EVT VT = StVal.getValueType();
9526 if (!VT.isVector())
9527 return SDValue();
9528
9529 // If we get a splat of zeros, convert this vector store to a store of
9530 // scalars. They will be merged into store pairs of xzr thereby removing one
9531 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009532 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +00009533 return ReplacedZeroSplat;
9534
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00009535 // FIXME: The logic for deciding if an unaligned store should be split should
9536 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9537 // a call to that function here.
9538
Matthias Braun651cff42016-06-02 18:03:53 +00009539 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00009540 return SDValue();
9541
Sanjay Patel924879a2015-08-04 15:49:57 +00009542 // Don't split at -Oz.
9543 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00009544 return SDValue();
9545
Tim Northover3b0846e2014-05-24 12:50:23 +00009546 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9547 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +00009548 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +00009549 return SDValue();
9550
9551 // Split unaligned 16B stores. They are terrible for performance.
9552 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9553 // extensions can use this to mark that it does not want splitting to happen
9554 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9555 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9556 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9557 S->getAlignment() <= 2)
9558 return SDValue();
9559
9560 // If we get a splat of a scalar convert this vector store to a store of
9561 // scalars. They will be merged into store pairs thereby removing two
9562 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009563 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +00009564 return ReplacedSplat;
9565
9566 SDLoc DL(S);
9567 unsigned NumElts = VT.getVectorNumElements() / 2;
9568 // Split VT into two.
9569 EVT HalfVT =
9570 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9571 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009572 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009573 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009574 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009575 SDValue BasePtr = S->getBasePtr();
9576 SDValue NewST1 =
9577 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00009578 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009579 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009580 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009581 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00009582 S->getPointerInfo(), S->getAlignment(),
9583 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009584}
9585
9586/// Target-specific DAG combine function for post-increment LD1 (lane) and
9587/// post-increment LD1R.
9588static SDValue performPostLD1Combine(SDNode *N,
9589 TargetLowering::DAGCombinerInfo &DCI,
9590 bool IsLaneOp) {
9591 if (DCI.isBeforeLegalizeOps())
9592 return SDValue();
9593
9594 SelectionDAG &DAG = DCI.DAG;
9595 EVT VT = N->getValueType(0);
9596
9597 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9598 SDNode *LD = N->getOperand(LoadIdx).getNode();
9599 // If it is not LOAD, can not do such combine.
9600 if (LD->getOpcode() != ISD::LOAD)
9601 return SDValue();
9602
9603 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9604 EVT MemVT = LoadSDN->getMemoryVT();
9605 // Check if memory operand is the same type as the vector element.
9606 if (MemVT != VT.getVectorElementType())
9607 return SDValue();
9608
9609 // Check if there are other uses. If so, do not combine as it will introduce
9610 // an extra load.
9611 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9612 ++UI) {
9613 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9614 continue;
9615 if (*UI != N)
9616 return SDValue();
9617 }
9618
9619 SDValue Addr = LD->getOperand(1);
9620 SDValue Vector = N->getOperand(0);
9621 // Search for a use of the address operand that is an increment.
9622 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9623 Addr.getNode()->use_end(); UI != UE; ++UI) {
9624 SDNode *User = *UI;
9625 if (User->getOpcode() != ISD::ADD
9626 || UI.getUse().getResNo() != Addr.getResNo())
9627 continue;
9628
9629 // Check that the add is independent of the load. Otherwise, folding it
9630 // would create a cycle.
9631 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9632 continue;
9633 // Also check that add is not used in the vector operand. This would also
9634 // create a cycle.
9635 if (User->isPredecessorOf(Vector.getNode()))
9636 continue;
9637
9638 // If the increment is a constant, it must match the memory ref size.
9639 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9640 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9641 uint32_t IncVal = CInc->getZExtValue();
9642 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9643 if (IncVal != NumBytes)
9644 continue;
9645 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9646 }
9647
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00009648 // Finally, check that the vector doesn't depend on the load.
9649 // Again, this would create a cycle.
9650 // The load depending on the vector is fine, as that's the case for the
9651 // LD1*post we'll eventually generate anyway.
9652 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9653 continue;
9654
Tim Northover3b0846e2014-05-24 12:50:23 +00009655 SmallVector<SDValue, 8> Ops;
9656 Ops.push_back(LD->getOperand(0)); // Chain
9657 if (IsLaneOp) {
9658 Ops.push_back(Vector); // The vector to be inserted
9659 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9660 }
9661 Ops.push_back(Addr);
9662 Ops.push_back(Inc);
9663
9664 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00009665 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00009666 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9667 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9668 MemVT,
9669 LoadSDN->getMemOperand());
9670
9671 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00009672 SDValue NewResults[] = {
9673 SDValue(LD, 0), // The result of load
9674 SDValue(UpdN.getNode(), 2) // Chain
9675 };
Tim Northover3b0846e2014-05-24 12:50:23 +00009676 DCI.CombineTo(LD, NewResults);
9677 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9678 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9679
9680 break;
9681 }
9682 return SDValue();
9683}
9684
Joel Jones7466ccf2017-07-10 22:11:50 +00009685/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +00009686/// address translation.
9687static bool performTBISimplification(SDValue Addr,
9688 TargetLowering::DAGCombinerInfo &DCI,
9689 SelectionDAG &DAG) {
9690 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +00009691 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +00009692 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9693 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +00009694 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +00009695 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +00009696 DCI.CommitTargetLoweringOpt(TLO);
9697 return true;
9698 }
9699 return false;
9700}
9701
9702static SDValue performSTORECombine(SDNode *N,
9703 TargetLowering::DAGCombinerInfo &DCI,
9704 SelectionDAG &DAG,
9705 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +00009706 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00009707 return Split;
9708
9709 if (Subtarget->supportsAddressTopByteIgnored() &&
9710 performTBISimplification(N->getOperand(2), DCI, DAG))
9711 return SDValue(N, 0);
9712
9713 return SDValue();
9714}
9715
Chad Rosier6c36eff2015-09-03 18:13:57 +00009716
Tim Northover3b0846e2014-05-24 12:50:23 +00009717/// Target-specific DAG combine function for NEON load/store intrinsics
9718/// to merge base address updates.
9719static SDValue performNEONPostLDSTCombine(SDNode *N,
9720 TargetLowering::DAGCombinerInfo &DCI,
9721 SelectionDAG &DAG) {
9722 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9723 return SDValue();
9724
9725 unsigned AddrOpIdx = N->getNumOperands() - 1;
9726 SDValue Addr = N->getOperand(AddrOpIdx);
9727
9728 // Search for a use of the address operand that is an increment.
9729 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9730 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9731 SDNode *User = *UI;
9732 if (User->getOpcode() != ISD::ADD ||
9733 UI.getUse().getResNo() != Addr.getResNo())
9734 continue;
9735
9736 // Check that the add is independent of the load/store. Otherwise, folding
9737 // it would create a cycle.
9738 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9739 continue;
9740
9741 // Find the new opcode for the updating load/store.
9742 bool IsStore = false;
9743 bool IsLaneOp = false;
9744 bool IsDupOp = false;
9745 unsigned NewOpc = 0;
9746 unsigned NumVecs = 0;
9747 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9748 switch (IntNo) {
9749 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9750 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9751 NumVecs = 2; break;
9752 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9753 NumVecs = 3; break;
9754 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9755 NumVecs = 4; break;
9756 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9757 NumVecs = 2; IsStore = true; break;
9758 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9759 NumVecs = 3; IsStore = true; break;
9760 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9761 NumVecs = 4; IsStore = true; break;
9762 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9763 NumVecs = 2; break;
9764 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9765 NumVecs = 3; break;
9766 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9767 NumVecs = 4; break;
9768 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9769 NumVecs = 2; IsStore = true; break;
9770 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9771 NumVecs = 3; IsStore = true; break;
9772 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9773 NumVecs = 4; IsStore = true; break;
9774 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9775 NumVecs = 2; IsDupOp = true; break;
9776 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9777 NumVecs = 3; IsDupOp = true; break;
9778 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9779 NumVecs = 4; IsDupOp = true; break;
9780 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9781 NumVecs = 2; IsLaneOp = true; break;
9782 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9783 NumVecs = 3; IsLaneOp = true; break;
9784 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9785 NumVecs = 4; IsLaneOp = true; break;
9786 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9787 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9788 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9789 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9790 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9791 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9792 }
9793
9794 EVT VecTy;
9795 if (IsStore)
9796 VecTy = N->getOperand(2).getValueType();
9797 else
9798 VecTy = N->getValueType(0);
9799
9800 // If the increment is a constant, it must match the memory ref size.
9801 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9802 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9803 uint32_t IncVal = CInc->getZExtValue();
9804 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9805 if (IsLaneOp || IsDupOp)
9806 NumBytes /= VecTy.getVectorNumElements();
9807 if (IncVal != NumBytes)
9808 continue;
9809 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9810 }
9811 SmallVector<SDValue, 8> Ops;
9812 Ops.push_back(N->getOperand(0)); // Incoming chain
9813 // Load lane and store have vector list as input.
9814 if (IsLaneOp || IsStore)
9815 for (unsigned i = 2; i < AddrOpIdx; ++i)
9816 Ops.push_back(N->getOperand(i));
9817 Ops.push_back(Addr); // Base register
9818 Ops.push_back(Inc);
9819
9820 // Return Types.
9821 EVT Tys[6];
9822 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9823 unsigned n;
9824 for (n = 0; n < NumResultVecs; ++n)
9825 Tys[n] = VecTy;
9826 Tys[n++] = MVT::i64; // Type of write back register
9827 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009828 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009829
9830 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9831 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9832 MemInt->getMemoryVT(),
9833 MemInt->getMemOperand());
9834
9835 // Update the uses.
9836 std::vector<SDValue> NewResults;
9837 for (unsigned i = 0; i < NumResultVecs; ++i) {
9838 NewResults.push_back(SDValue(UpdN.getNode(), i));
9839 }
9840 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9841 DCI.CombineTo(N, NewResults);
9842 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9843
9844 break;
9845 }
9846 return SDValue();
9847}
9848
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009849// Checks to see if the value is the prescribed width and returns information
9850// about its extension mode.
9851static
9852bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9853 ExtType = ISD::NON_EXTLOAD;
9854 switch(V.getNode()->getOpcode()) {
9855 default:
9856 return false;
9857 case ISD::LOAD: {
9858 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9859 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9860 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9861 ExtType = LoadNode->getExtensionType();
9862 return true;
9863 }
9864 return false;
9865 }
9866 case ISD::AssertSext: {
9867 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9868 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9869 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9870 ExtType = ISD::SEXTLOAD;
9871 return true;
9872 }
9873 return false;
9874 }
9875 case ISD::AssertZext: {
9876 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9877 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9878 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9879 ExtType = ISD::ZEXTLOAD;
9880 return true;
9881 }
9882 return false;
9883 }
9884 case ISD::Constant:
9885 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009886 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9887 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009888 }
9889 }
9890
9891 return true;
9892}
9893
9894// This function does a whole lot of voodoo to determine if the tests are
9895// equivalent without and with a mask. Essentially what happens is that given a
9896// DAG resembling:
9897//
9898// +-------------+ +-------------+ +-------------+ +-------------+
9899// | Input | | AddConstant | | CompConstant| | CC |
9900// +-------------+ +-------------+ +-------------+ +-------------+
9901// | | | |
9902// V V | +----------+
9903// +-------------+ +----+ | |
9904// | ADD | |0xff| | |
9905// +-------------+ +----+ | |
9906// | | | |
9907// V V | |
9908// +-------------+ | |
9909// | AND | | |
9910// +-------------+ | |
9911// | | |
9912// +-----+ | |
9913// | | |
9914// V V V
9915// +-------------+
9916// | CMP |
9917// +-------------+
9918//
9919// The AND node may be safely removed for some combinations of inputs. In
9920// particular we need to take into account the extension type of the Input,
9921// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9922// width of the input (this can work for any width inputs, the above graph is
9923// specific to 8 bits.
9924//
9925// The specific equations were worked out by generating output tables for each
9926// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9927// problem was simplified by working with 4 bit inputs, which means we only
9928// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9929// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9930// patterns present in both extensions (0,7). For every distinct set of
9931// AddConstant and CompConstants bit patterns we can consider the masked and
9932// unmasked versions to be equivalent if the result of this function is true for
9933// all 16 distinct bit patterns of for the current extension type of Input (w0).
9934//
9935// sub w8, w0, w1
9936// and w10, w8, #0x0f
9937// cmp w8, w2
9938// cset w9, AArch64CC
9939// cmp w10, w2
9940// cset w11, AArch64CC
9941// cmp w9, w11
9942// cset w0, eq
9943// ret
9944//
9945// Since the above function shows when the outputs are equivalent it defines
9946// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9947// would be expensive to run during compiles. The equations below were written
9948// in a test harness that confirmed they gave equivalent outputs to the above
9949// for all inputs function, so they can be used determine if the removal is
9950// legal instead.
9951//
9952// isEquivalentMaskless() is the code for testing if the AND can be removed
9953// factored out of the DAG recognition as the DAG can take several forms.
9954
David Majnemere61e4bf2016-06-21 05:10:24 +00009955static bool isEquivalentMaskless(unsigned CC, unsigned width,
9956 ISD::LoadExtType ExtType, int AddConstant,
9957 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009958 // By being careful about our equations and only writing the in term
9959 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9960 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009961 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009962
9963 // For the purposes of these comparisons sign extending the type is
9964 // equivalent to zero extending the add and displacing it by half the integer
9965 // width. Provided we are careful and make sure our equations are valid over
9966 // the whole range we can just adjust the input and avoid writing equations
9967 // for sign extended inputs.
9968 if (ExtType == ISD::SEXTLOAD)
9969 AddConstant -= (1 << (width-1));
9970
9971 switch(CC) {
9972 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009973 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009974 if ((AddConstant == 0) ||
9975 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9976 (AddConstant >= 0 && CompConstant < 0) ||
9977 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9978 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009979 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009980 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009981 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009982 if ((AddConstant == 0) ||
9983 (AddConstant >= 0 && CompConstant <= 0) ||
9984 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9985 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009986 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009987 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009988 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009989 if ((AddConstant >= 0 && CompConstant < 0) ||
9990 (AddConstant <= 0 && CompConstant >= -1 &&
9991 CompConstant < AddConstant + MaxUInt))
9992 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009993 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009994 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009995 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009996 if ((AddConstant == 0) ||
9997 (AddConstant > 0 && CompConstant <= 0) ||
9998 (AddConstant < 0 && CompConstant <= AddConstant))
9999 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010000 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010001 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010002 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010003 if ((AddConstant >= 0 && CompConstant <= 0) ||
10004 (AddConstant <= 0 && CompConstant >= 0 &&
10005 CompConstant <= AddConstant + MaxUInt))
10006 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010007 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010008 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010009 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010010 if ((AddConstant > 0 && CompConstant < 0) ||
10011 (AddConstant < 0 && CompConstant >= 0 &&
10012 CompConstant < AddConstant + MaxUInt) ||
10013 (AddConstant >= 0 && CompConstant >= 0 &&
10014 CompConstant >= AddConstant) ||
10015 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010016 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010017 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010018 case AArch64CC::VS:
10019 case AArch64CC::VC:
10020 case AArch64CC::AL:
10021 case AArch64CC::NV:
10022 return true;
10023 case AArch64CC::Invalid:
10024 break;
10025 }
10026
10027 return false;
10028}
10029
10030static
10031SDValue performCONDCombine(SDNode *N,
10032 TargetLowering::DAGCombinerInfo &DCI,
10033 SelectionDAG &DAG, unsigned CCIndex,
10034 unsigned CmpIndex) {
10035 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10036 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10037 unsigned CondOpcode = SubsNode->getOpcode();
10038
10039 if (CondOpcode != AArch64ISD::SUBS)
10040 return SDValue();
10041
10042 // There is a SUBS feeding this condition. Is it fed by a mask we can
10043 // use?
10044
10045 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10046 unsigned MaskBits = 0;
10047
10048 if (AndNode->getOpcode() != ISD::AND)
10049 return SDValue();
10050
10051 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10052 uint32_t CNV = CN->getZExtValue();
10053 if (CNV == 255)
10054 MaskBits = 8;
10055 else if (CNV == 65535)
10056 MaskBits = 16;
10057 }
10058
10059 if (!MaskBits)
10060 return SDValue();
10061
10062 SDValue AddValue = AndNode->getOperand(0);
10063
10064 if (AddValue.getOpcode() != ISD::ADD)
10065 return SDValue();
10066
10067 // The basic dag structure is correct, grab the inputs and validate them.
10068
10069 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10070 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10071 SDValue SubsInputValue = SubsNode->getOperand(1);
10072
10073 // The mask is present and the provenance of all the values is a smaller type,
10074 // lets see if the mask is superfluous.
10075
10076 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10077 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10078 return SDValue();
10079
10080 ISD::LoadExtType ExtType;
10081
10082 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10083 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10084 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10085 return SDValue();
10086
10087 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10088 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10089 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10090 return SDValue();
10091
10092 // The AND is not necessary, remove it.
10093
10094 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10095 SubsNode->getValueType(1));
10096 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10097
10098 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10099 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10100
10101 return SDValue(N, 0);
10102}
10103
Tim Northover3b0846e2014-05-24 12:50:23 +000010104// Optimize compare with zero and branch.
10105static SDValue performBRCONDCombine(SDNode *N,
10106 TargetLowering::DAGCombinerInfo &DCI,
10107 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010108 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010109 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010110 SDValue Chain = N->getOperand(0);
10111 SDValue Dest = N->getOperand(1);
10112 SDValue CCVal = N->getOperand(2);
10113 SDValue Cmp = N->getOperand(3);
10114
10115 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10116 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10117 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10118 return SDValue();
10119
10120 unsigned CmpOpc = Cmp.getOpcode();
10121 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10122 return SDValue();
10123
10124 // Only attempt folding if there is only one use of the flag and no use of the
10125 // value.
10126 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10127 return SDValue();
10128
10129 SDValue LHS = Cmp.getOperand(0);
10130 SDValue RHS = Cmp.getOperand(1);
10131
10132 assert(LHS.getValueType() == RHS.getValueType() &&
10133 "Expected the value type to be the same for both operands!");
10134 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10135 return SDValue();
10136
Artyom Skrobov314ee042015-11-25 19:41:11 +000010137 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010138 std::swap(LHS, RHS);
10139
Artyom Skrobov314ee042015-11-25 19:41:11 +000010140 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010141 return SDValue();
10142
10143 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10144 LHS.getOpcode() == ISD::SRL)
10145 return SDValue();
10146
10147 // Fold the compare into the branch instruction.
10148 SDValue BR;
10149 if (CC == AArch64CC::EQ)
10150 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10151 else
10152 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10153
10154 // Do not add new nodes to DAG combiner worklist.
10155 DCI.CombineTo(N, BR, false);
10156
10157 return SDValue();
10158}
10159
Geoff Berry9e934b02016-01-04 18:55:47 +000010160// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10161// as well as whether the test should be inverted. This code is required to
10162// catch these cases (as opposed to standard dag combines) because
10163// AArch64ISD::TBZ is matched during legalization.
10164static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10165 SelectionDAG &DAG) {
10166
10167 if (!Op->hasOneUse())
10168 return Op;
10169
10170 // We don't handle undef/constant-fold cases below, as they should have
10171 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10172 // etc.)
10173
10174 // (tbz (trunc x), b) -> (tbz x, b)
10175 // This case is just here to enable more of the below cases to be caught.
10176 if (Op->getOpcode() == ISD::TRUNCATE &&
10177 Bit < Op->getValueType(0).getSizeInBits()) {
10178 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10179 }
10180
10181 if (Op->getNumOperands() != 2)
10182 return Op;
10183
10184 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10185 if (!C)
10186 return Op;
10187
10188 switch (Op->getOpcode()) {
10189 default:
10190 return Op;
10191
10192 // (tbz (and x, m), b) -> (tbz x, b)
10193 case ISD::AND:
10194 if ((C->getZExtValue() >> Bit) & 1)
10195 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10196 return Op;
10197
10198 // (tbz (shl x, c), b) -> (tbz x, b-c)
10199 case ISD::SHL:
10200 if (C->getZExtValue() <= Bit &&
10201 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10202 Bit = Bit - C->getZExtValue();
10203 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10204 }
10205 return Op;
10206
10207 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10208 case ISD::SRA:
10209 Bit = Bit + C->getZExtValue();
10210 if (Bit >= Op->getValueType(0).getSizeInBits())
10211 Bit = Op->getValueType(0).getSizeInBits() - 1;
10212 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10213
10214 // (tbz (srl x, c), b) -> (tbz x, b+c)
10215 case ISD::SRL:
10216 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10217 Bit = Bit + C->getZExtValue();
10218 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10219 }
10220 return Op;
10221
10222 // (tbz (xor x, -1), b) -> (tbnz x, b)
10223 case ISD::XOR:
10224 if ((C->getZExtValue() >> Bit) & 1)
10225 Invert = !Invert;
10226 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10227 }
10228}
10229
10230// Optimize test single bit zero/non-zero and branch.
10231static SDValue performTBZCombine(SDNode *N,
10232 TargetLowering::DAGCombinerInfo &DCI,
10233 SelectionDAG &DAG) {
10234 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10235 bool Invert = false;
10236 SDValue TestSrc = N->getOperand(1);
10237 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10238
10239 if (TestSrc == NewTestSrc)
10240 return SDValue();
10241
10242 unsigned NewOpc = N->getOpcode();
10243 if (Invert) {
10244 if (NewOpc == AArch64ISD::TBZ)
10245 NewOpc = AArch64ISD::TBNZ;
10246 else {
10247 assert(NewOpc == AArch64ISD::TBNZ);
10248 NewOpc = AArch64ISD::TBZ;
10249 }
10250 }
10251
10252 SDLoc DL(N);
10253 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10254 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10255}
10256
Tim Northover3b0846e2014-05-24 12:50:23 +000010257// vselect (v1i1 setcc) ->
10258// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10259// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10260// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10261// such VSELECT.
10262static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10263 SDValue N0 = N->getOperand(0);
10264 EVT CCVT = N0.getValueType();
10265
10266 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10267 CCVT.getVectorElementType() != MVT::i1)
10268 return SDValue();
10269
10270 EVT ResVT = N->getValueType(0);
10271 EVT CmpVT = N0.getOperand(0).getValueType();
10272 // Only combine when the result type is of the same size as the compared
10273 // operands.
10274 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10275 return SDValue();
10276
10277 SDValue IfTrue = N->getOperand(1);
10278 SDValue IfFalse = N->getOperand(2);
10279 SDValue SetCC =
10280 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10281 N0.getOperand(0), N0.getOperand(1),
10282 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10283 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10284 IfTrue, IfFalse);
10285}
10286
10287/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10288/// the compare-mask instructions rather than going via NZCV, even if LHS and
10289/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10290/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010291static SDValue performSelectCombine(SDNode *N,
10292 TargetLowering::DAGCombinerInfo &DCI) {
10293 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010294 SDValue N0 = N->getOperand(0);
10295 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010296
Ahmed Bougachac004c602015-04-27 21:43:12 +000010297 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010298 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010299
Ahmed Bougachac004c602015-04-27 21:43:12 +000010300 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10301 // scalar SetCCResultType. We also don't expect vectors, because we assume
10302 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10303 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10304 "Scalar-SETCC feeding SELECT has unexpected result type!");
10305
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010306 // If NumMaskElts == 0, the comparison is larger than select result. The
10307 // largest real NEON comparison is 64-bits per lane, which means the result is
10308 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010309 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000010310
10311 // Don't try to do this optimization when the setcc itself has i1 operands.
10312 // There are no legal vectors of i1, so this would be pointless.
10313 if (SrcVT == MVT::i1)
10314 return SDValue();
10315
Tim Northover3c0915e2014-08-29 15:34:58 +000010316 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010317 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000010318 return SDValue();
10319
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010320 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010321 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10322
Ahmed Bougacha89bba612015-04-27 21:01:20 +000010323 // Also bail out if the vector CCVT isn't the same size as ResVT.
10324 // This can happen if the SETCC operand size doesn't divide the ResVT size
10325 // (e.g., f64 vs v3f32).
10326 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10327 return SDValue();
10328
Ahmed Bougachac004c602015-04-27 21:43:12 +000010329 // Make sure we didn't create illegal types, if we're not supposed to.
10330 assert(DCI.isBeforeLegalize() ||
10331 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10332
Tim Northover3b0846e2014-05-24 12:50:23 +000010333 // First perform a vector comparison, where lane 0 is the one we're interested
10334 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010335 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010336 SDValue LHS =
10337 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10338 SDValue RHS =
10339 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10340 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10341
10342 // Now duplicate the comparison mask we want across all other lanes.
10343 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000010344 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010345 Mask = DAG.getNode(ISD::BITCAST, DL,
10346 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000010347
10348 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10349}
10350
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010351/// Get rid of unnecessary NVCASTs (that don't change the type).
10352static SDValue performNVCASTCombine(SDNode *N) {
10353 if (N->getValueType(0) == N->getOperand(0).getValueType())
10354 return N->getOperand(0);
10355
10356 return SDValue();
10357}
10358
Tim Northover3b0846e2014-05-24 12:50:23 +000010359SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10360 DAGCombinerInfo &DCI) const {
10361 SelectionDAG &DAG = DCI.DAG;
10362 switch (N->getOpcode()) {
10363 default:
Sjoerd Meijer24c98182017-08-23 08:18:37 +000010364 DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000010365 break;
10366 case ISD::ADD:
10367 case ISD::SUB:
10368 return performAddSubLongCombine(N, DCI, DAG);
10369 case ISD::XOR:
10370 return performXorCombine(N, DAG, DCI, Subtarget);
10371 case ISD::MUL:
10372 return performMulCombine(N, DAG, DCI, Subtarget);
10373 case ISD::SINT_TO_FP:
10374 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000010375 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000010376 case ISD::FP_TO_SINT:
10377 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000010378 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000010379 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000010380 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010381 case ISD::OR:
10382 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000010383 case ISD::SRL:
10384 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010385 case ISD::INTRINSIC_WO_CHAIN:
10386 return performIntrinsicCombine(N, DCI, Subtarget);
10387 case ISD::ANY_EXTEND:
10388 case ISD::ZERO_EXTEND:
10389 case ISD::SIGN_EXTEND:
10390 return performExtendCombine(N, DCI, DAG);
10391 case ISD::BITCAST:
10392 return performBitcastCombine(N, DCI, DAG);
10393 case ISD::CONCAT_VECTORS:
10394 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000010395 case ISD::SELECT:
10396 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010397 case ISD::VSELECT:
10398 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000010399 case ISD::LOAD:
10400 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10401 return SDValue(N, 0);
10402 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000010403 case ISD::STORE:
10404 return performSTORECombine(N, DCI, DAG, Subtarget);
10405 case AArch64ISD::BRCOND:
10406 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000010407 case AArch64ISD::TBNZ:
10408 case AArch64ISD::TBZ:
10409 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010410 case AArch64ISD::CSEL:
10411 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000010412 case AArch64ISD::DUP:
10413 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010414 case AArch64ISD::NVCAST:
10415 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000010416 case ISD::INSERT_VECTOR_ELT:
10417 return performPostLD1Combine(N, DCI, true);
10418 case ISD::INTRINSIC_VOID:
10419 case ISD::INTRINSIC_W_CHAIN:
10420 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10421 case Intrinsic::aarch64_neon_ld2:
10422 case Intrinsic::aarch64_neon_ld3:
10423 case Intrinsic::aarch64_neon_ld4:
10424 case Intrinsic::aarch64_neon_ld1x2:
10425 case Intrinsic::aarch64_neon_ld1x3:
10426 case Intrinsic::aarch64_neon_ld1x4:
10427 case Intrinsic::aarch64_neon_ld2lane:
10428 case Intrinsic::aarch64_neon_ld3lane:
10429 case Intrinsic::aarch64_neon_ld4lane:
10430 case Intrinsic::aarch64_neon_ld2r:
10431 case Intrinsic::aarch64_neon_ld3r:
10432 case Intrinsic::aarch64_neon_ld4r:
10433 case Intrinsic::aarch64_neon_st2:
10434 case Intrinsic::aarch64_neon_st3:
10435 case Intrinsic::aarch64_neon_st4:
10436 case Intrinsic::aarch64_neon_st1x2:
10437 case Intrinsic::aarch64_neon_st1x3:
10438 case Intrinsic::aarch64_neon_st1x4:
10439 case Intrinsic::aarch64_neon_st2lane:
10440 case Intrinsic::aarch64_neon_st3lane:
10441 case Intrinsic::aarch64_neon_st4lane:
10442 return performNEONPostLDSTCombine(N, DCI, DAG);
10443 default:
10444 break;
10445 }
10446 }
10447 return SDValue();
10448}
10449
10450// Check if the return value is used as only a return value, as otherwise
10451// we can't perform a tail-call. In particular, we need to check for
10452// target ISD nodes that are returns and any other "odd" constructs
10453// that the generic analysis code won't necessarily catch.
10454bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10455 SDValue &Chain) const {
10456 if (N->getNumValues() != 1)
10457 return false;
10458 if (!N->hasNUsesOfValue(1, 0))
10459 return false;
10460
10461 SDValue TCChain = Chain;
10462 SDNode *Copy = *N->use_begin();
10463 if (Copy->getOpcode() == ISD::CopyToReg) {
10464 // If the copy has a glue operand, we conservatively assume it isn't safe to
10465 // perform a tail call.
10466 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10467 MVT::Glue)
10468 return false;
10469 TCChain = Copy->getOperand(0);
10470 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10471 return false;
10472
10473 bool HasRet = false;
10474 for (SDNode *Node : Copy->uses()) {
10475 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10476 return false;
10477 HasRet = true;
10478 }
10479
10480 if (!HasRet)
10481 return false;
10482
10483 Chain = TCChain;
10484 return true;
10485}
10486
10487// Return whether the an instruction can potentially be optimized to a tail
10488// call. This will cause the optimizers to attempt to move, or duplicate,
10489// return instructions to help enable tail call optimizations for this
10490// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000010491bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010492 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010493}
10494
10495bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10496 SDValue &Offset,
10497 ISD::MemIndexedMode &AM,
10498 bool &IsInc,
10499 SelectionDAG &DAG) const {
10500 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10501 return false;
10502
10503 Base = Op->getOperand(0);
10504 // All of the indexed addressing mode instructions take a signed
10505 // 9 bit immediate offset.
10506 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000010507 int64_t RHSC = RHS->getSExtValue();
10508 if (Op->getOpcode() == ISD::SUB)
10509 RHSC = -(uint64_t)RHSC;
10510 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000010511 return false;
10512 IsInc = (Op->getOpcode() == ISD::ADD);
10513 Offset = Op->getOperand(1);
10514 return true;
10515 }
10516 return false;
10517}
10518
10519bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10520 SDValue &Offset,
10521 ISD::MemIndexedMode &AM,
10522 SelectionDAG &DAG) const {
10523 EVT VT;
10524 SDValue Ptr;
10525 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10526 VT = LD->getMemoryVT();
10527 Ptr = LD->getBasePtr();
10528 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10529 VT = ST->getMemoryVT();
10530 Ptr = ST->getBasePtr();
10531 } else
10532 return false;
10533
10534 bool IsInc;
10535 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10536 return false;
10537 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10538 return true;
10539}
10540
10541bool AArch64TargetLowering::getPostIndexedAddressParts(
10542 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10543 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10544 EVT VT;
10545 SDValue Ptr;
10546 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10547 VT = LD->getMemoryVT();
10548 Ptr = LD->getBasePtr();
10549 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10550 VT = ST->getMemoryVT();
10551 Ptr = ST->getBasePtr();
10552 } else
10553 return false;
10554
10555 bool IsInc;
10556 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10557 return false;
10558 // Post-indexing updates the base, so it's not a valid transform
10559 // if that's not the same as the load's pointer.
10560 if (Ptr != Base)
10561 return false;
10562 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10563 return true;
10564}
10565
Tim Northoverf8bfe212014-07-18 13:07:05 +000010566static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10567 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010568 SDLoc DL(N);
10569 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010570
10571 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10572 return;
10573
Tim Northoverf8bfe212014-07-18 13:07:05 +000010574 Op = SDValue(
10575 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10576 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010577 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010578 0);
10579 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10580 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10581}
10582
Charlie Turner434d4592015-10-16 15:38:25 +000010583static void ReplaceReductionResults(SDNode *N,
10584 SmallVectorImpl<SDValue> &Results,
10585 SelectionDAG &DAG, unsigned InterOp,
10586 unsigned AcrossOp) {
10587 EVT LoVT, HiVT;
10588 SDValue Lo, Hi;
10589 SDLoc dl(N);
10590 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10591 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10592 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10593 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10594 Results.push_back(SplitVal);
10595}
10596
Tim Northover2f32e7f2016-08-04 19:32:28 +000010597static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10598 SDLoc DL(N);
10599 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10600 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10601 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10602 DAG.getConstant(64, DL, MVT::i64)));
10603 return std::make_pair(Lo, Hi);
10604}
10605
Tim Northovercdf15292016-04-14 17:03:29 +000010606static void ReplaceCMP_SWAP_128Results(SDNode *N,
10607 SmallVectorImpl<SDValue> & Results,
10608 SelectionDAG &DAG) {
10609 assert(N->getValueType(0) == MVT::i128 &&
10610 "AtomicCmpSwap on types less than 128 should be legal");
Tim Northover2f32e7f2016-08-04 19:32:28 +000010611 auto Desired = splitInt128(N->getOperand(2), DAG);
10612 auto New = splitInt128(N->getOperand(3), DAG);
10613 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10614 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010615 SDNode *CmpSwap = DAG.getMachineNode(
10616 AArch64::CMP_SWAP_128, SDLoc(N),
10617 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10618
10619 MachineFunction &MF = DAG.getMachineFunction();
10620 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10621 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10622 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10623
10624 Results.push_back(SDValue(CmpSwap, 0));
10625 Results.push_back(SDValue(CmpSwap, 1));
10626 Results.push_back(SDValue(CmpSwap, 3));
10627}
10628
Tim Northover3b0846e2014-05-24 12:50:23 +000010629void AArch64TargetLowering::ReplaceNodeResults(
10630 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10631 switch (N->getOpcode()) {
10632 default:
10633 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010634 case ISD::BITCAST:
10635 ReplaceBITCASTResults(N, Results, DAG);
10636 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000010637 case ISD::VECREDUCE_ADD:
10638 case ISD::VECREDUCE_SMAX:
10639 case ISD::VECREDUCE_SMIN:
10640 case ISD::VECREDUCE_UMAX:
10641 case ISD::VECREDUCE_UMIN:
10642 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
10643 return;
10644
Charlie Turner434d4592015-10-16 15:38:25 +000010645 case AArch64ISD::SADDV:
10646 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10647 return;
10648 case AArch64ISD::UADDV:
10649 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10650 return;
10651 case AArch64ISD::SMINV:
10652 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10653 return;
10654 case AArch64ISD::UMINV:
10655 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10656 return;
10657 case AArch64ISD::SMAXV:
10658 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10659 return;
10660 case AArch64ISD::UMAXV:
10661 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10662 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010663 case ISD::FP_TO_UINT:
10664 case ISD::FP_TO_SINT:
10665 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10666 // Let normal code take care of it by not adding anything to Results.
10667 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010668 case ISD::ATOMIC_CMP_SWAP:
10669 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10670 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010671 }
10672}
10673
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010674bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000010675 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10676 return TargetLowering::useLoadStackGuardNode();
10677 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010678}
10679
Sanjay Patel1dd15592015-07-28 23:05:48 +000010680unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010681 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10682 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010683 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010684}
10685
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010686TargetLoweringBase::LegalizeTypeAction
10687AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10688 MVT SVT = VT.getSimpleVT();
10689 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10690 // v4i16, v2i32 instead of to promote.
10691 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10692 || SVT == MVT::v1f32)
10693 return TypeWidenVector;
10694
10695 return TargetLoweringBase::getPreferredVectorAction(VT);
10696}
10697
Robin Morisseted3d48f2014-09-03 21:29:59 +000010698// Loads and stores less than 128-bits are already atomic; ones above that
10699// are doomed anyway, so defer to the default libcall and blame the OS when
10700// things go wrong.
10701bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10702 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10703 return Size == 128;
10704}
10705
10706// Loads and stores less than 128-bits are already atomic; ones above that
10707// are doomed anyway, so defer to the default libcall and blame the OS when
10708// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010709TargetLowering::AtomicExpansionKind
10710AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010711 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010712 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010713}
10714
10715// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010716TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010717AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010718 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000010719 if (Size > 128) return AtomicExpansionKind::None;
10720 // Nand not supported in LSE.
10721 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000010722 // Leave 128 bits to LLSC.
10723 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010724}
10725
Ahmed Bougacha52468672015-09-11 17:08:28 +000010726bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10727 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000010728 // If subtarget has LSE, leave cmpxchg intact for codegen.
10729 if (Subtarget->hasLSE()) return false;
Tim Northovercdf15292016-04-14 17:03:29 +000010730 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10731 // implement cmpxchg without spilling. If the address being exchanged is also
10732 // on the stack and close enough to the spill slot, this can lead to a
10733 // situation where the monitor always gets cleared and the atomic operation
10734 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10735 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010736}
10737
Tim Northover3b0846e2014-05-24 12:50:23 +000010738Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10739 AtomicOrdering Ord) const {
10740 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10741 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010742 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010743
10744 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10745 // intrinsic must return {i64, i64} and we have to recombine them into a
10746 // single i128 here.
10747 if (ValTy->getPrimitiveSizeInBits() == 128) {
10748 Intrinsic::ID Int =
10749 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010750 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000010751
10752 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10753 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10754
10755 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10756 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10757 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10758 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10759 return Builder.CreateOr(
10760 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10761 }
10762
10763 Type *Tys[] = { Addr->getType() };
10764 Intrinsic::ID Int =
10765 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010766 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010767
10768 return Builder.CreateTruncOrBitCast(
10769 Builder.CreateCall(Ldxr, Addr),
10770 cast<PointerType>(Addr->getType())->getElementType());
10771}
10772
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010773void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10774 IRBuilder<> &Builder) const {
10775 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000010776 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010777}
10778
Tim Northover3b0846e2014-05-24 12:50:23 +000010779Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10780 Value *Val, Value *Addr,
10781 AtomicOrdering Ord) const {
10782 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010783 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010784
10785 // Since the intrinsics must have legal type, the i128 intrinsics take two
10786 // parameters: "i64, i64". We must marshal Val into the appropriate form
10787 // before the call.
10788 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10789 Intrinsic::ID Int =
10790 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10791 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10792 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10793
10794 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10795 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10796 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010797 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010798 }
10799
10800 Intrinsic::ID Int =
10801 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10802 Type *Tys[] = { Addr->getType() };
10803 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10804
David Blaikieff6409d2015-05-18 22:13:54 +000010805 return Builder.CreateCall(Stxr,
10806 {Builder.CreateZExtOrBitCast(
10807 Val, Stxr->getFunctionType()->getParamType(0)),
10808 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010809}
Tim Northover3c55cca2014-11-27 21:02:42 +000010810
10811bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10812 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10813 return Ty->isArrayTy();
10814}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010815
10816bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10817 EVT) const {
10818 return false;
10819}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010820
Petr Hoseka7d59162017-02-24 03:10:10 +000010821static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010822 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10823 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010824 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010825 return IRB.CreatePointerCast(
Petr Hoseka7d59162017-02-24 03:10:10 +000010826 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010827 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10828}
10829
Petr Hoseka7d59162017-02-24 03:10:10 +000010830Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10831 // Android provides a fixed TLS slot for the stack cookie. See the definition
10832 // of TLS_SLOT_STACK_GUARD in
10833 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10834 if (Subtarget->isTargetAndroid())
10835 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010836
Petr Hoseka7d59162017-02-24 03:10:10 +000010837 // Fuchsia is similar.
10838 // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10839 if (Subtarget->isTargetFuchsia())
10840 return UseTlsOffset(IRB, -0x10);
10841
10842 return TargetLowering::getIRStackGuard(IRB);
10843}
10844
10845Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010846 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10847 // definition of TLS_SLOT_SAFESTACK in
10848 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000010849 if (Subtarget->isTargetAndroid())
10850 return UseTlsOffset(IRB, 0x48);
10851
10852 // Fuchsia is similar.
10853 // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10854 if (Subtarget->isTargetFuchsia())
10855 return UseTlsOffset(IRB, -0x8);
10856
10857 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010858}
Manman Rencbe4f942015-12-16 21:04:19 +000010859
Geoff Berry5d534b62017-02-21 18:53:14 +000010860bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10861 const Instruction &AndI) const {
10862 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10863 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10864 // may be beneficial to sink in other cases, but we would have to check that
10865 // the cmp would not get folded into the br to form a cbz for these to be
10866 // beneficial.
10867 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10868 if (!Mask)
10869 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000010870 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000010871}
10872
Manman Rencbe4f942015-12-16 21:04:19 +000010873void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10874 // Update IsSplitCSR in AArch64unctionInfo.
10875 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10876 AFI->setIsSplitCSR(true);
10877}
10878
10879void AArch64TargetLowering::insertCopiesSplitCSR(
10880 MachineBasicBlock *Entry,
10881 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10882 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10883 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10884 if (!IStart)
10885 return;
10886
10887 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10888 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010889 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010890 for (const MCPhysReg *I = IStart; *I; ++I) {
10891 const TargetRegisterClass *RC = nullptr;
10892 if (AArch64::GPR64RegClass.contains(*I))
10893 RC = &AArch64::GPR64RegClass;
10894 else if (AArch64::FPR64RegClass.contains(*I))
10895 RC = &AArch64::FPR64RegClass;
10896 else
10897 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10898
10899 unsigned NewVR = MRI->createVirtualRegister(RC);
10900 // Create copy from CSR to a virtual register.
10901 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10902 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10903 // nounwind. If we want to generalize this later, we may need to emit
10904 // CFI pseudo-instructions.
10905 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10906 Attribute::NoUnwind) &&
10907 "Function should be nounwind in insertCopiesSplitCSR!");
10908 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010909 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010910 .addReg(*I);
10911
Manman Ren4632e8e2016-01-15 20:13:28 +000010912 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010913 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010914 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10915 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010916 .addReg(NewVR);
10917 }
10918}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010919
Reid Klecknerb5180542017-03-21 16:57:19 +000010920bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010921 // Integer division on AArch64 is expensive. However, when aggressively
10922 // optimizing for code size, we prefer to use a div instruction, as it is
10923 // usually smaller than the alternative sequence.
10924 // The exception to this is vector division. Since AArch64 doesn't have vector
10925 // integer division, leaving the division as-is is a loss even in terms of
10926 // size, because it will have to be scalarized, while the alternative code
10927 // sequence can be performed in vector form.
10928 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000010929 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010930 return OptSize && !VT.isVector();
10931}
Tim Northoverf19d4672017-02-08 17:57:20 +000010932
10933unsigned
10934AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000010935 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000010936 return getPointerTy(DL).getSizeInBits();
10937
10938 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
10939}