blob: b78837aae836a1f1f41fd0bf50b29e0fc52e13d5 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AArch64TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +000013#include "AArch64ExpandImm.h"
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/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000044#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000046#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000047#include "llvm/IR/Attributes.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000052#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000054#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000055#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000056#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
Florian Hahn3b251962019-02-05 10:27:40 +000058#include "llvm/IR/IntrinsicInst.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000059#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000060#include "llvm/IR/Module.h"
61#include "llvm/IR/OperandTraits.h"
Florian Hahn3b251962019-02-05 10:27:40 +000062#include "llvm/IR/PatternMatch.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000063#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000064#include "llvm/IR/Use.h"
65#include "llvm/IR/Value.h"
66#include "llvm/MC/MCRegisterInfo.h"
67#include "llvm/Support/Casting.h"
68#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000069#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000070#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000071#include "llvm/Support/Debug.h"
72#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000073#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000074#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000075#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000076#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000077#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000078#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000079#include <algorithm>
80#include <bitset>
81#include <cassert>
82#include <cctype>
83#include <cstdint>
84#include <cstdlib>
85#include <iterator>
86#include <limits>
87#include <tuple>
88#include <utility>
89#include <vector>
90
Tim Northover3b0846e2014-05-24 12:50:23 +000091using namespace llvm;
Florian Hahn3b251962019-02-05 10:27:40 +000092using namespace llvm::PatternMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +000093
94#define DEBUG_TYPE "aarch64-lower"
95
96STATISTIC(NumTailCalls, "Number of tail calls");
97STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000098STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000099
Tim Northover3b0846e2014-05-24 12:50:23 +0000100static cl::opt<bool>
101EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +0000102 cl::desc("Allow AArch64 SLI/SRI formation"),
103 cl::init(false));
104
105// FIXME: The necessary dtprel relocations don't seem to be supported
106// well in the GNU bfd and gold linkers at the moment. Therefore, by
107// default, for now, fall back to GeneralDynamic code generation.
108cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109 "aarch64-elf-ldtls-generation", cl::Hidden,
110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000112
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000113static cl::opt<bool>
114EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
115 cl::desc("Enable AArch64 logical imm instruction "
116 "optimization"),
117 cl::init(true));
118
Matthias Braunaf7d7702015-07-16 20:02:37 +0000119/// Value type used for condition codes.
120static const MVT MVT_CC = MVT::i32;
121
Eric Christopher905f12d2015-01-29 00:19:42 +0000122AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
123 const AArch64Subtarget &STI)
124 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126 // we have to make something up. Arbitrarily, choose ZeroOrOne.
127 setBooleanContents(ZeroOrOneBooleanContent);
128 // When comparing vectors the result sets the different elements in the
129 // vector to all-one or all-zero.
130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
131
132 // Set up the register classes.
133 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
134 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
135
136 if (Subtarget->hasFPARMv8()) {
137 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
138 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
139 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
140 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
141 }
142
143 if (Subtarget->hasNEON()) {
144 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
145 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
146 // Someone set us up the NEON.
147 addDRTypeForNEON(MVT::v2f32);
148 addDRTypeForNEON(MVT::v8i8);
149 addDRTypeForNEON(MVT::v4i16);
150 addDRTypeForNEON(MVT::v2i32);
151 addDRTypeForNEON(MVT::v1i64);
152 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000153 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000154
155 addQRTypeForNEON(MVT::v4f32);
156 addQRTypeForNEON(MVT::v2f64);
157 addQRTypeForNEON(MVT::v16i8);
158 addQRTypeForNEON(MVT::v8i16);
159 addQRTypeForNEON(MVT::v4i32);
160 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000161 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000162 }
163
164 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000165 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000166
167 // Provide all sorts of operation actions
168 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
169 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
170 setOperationAction(ISD::SETCC, MVT::i32, Custom);
171 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000172 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000173 setOperationAction(ISD::SETCC, MVT::f32, Custom);
174 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000175 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
176 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000177 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
178 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
179 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000180 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000181 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
182 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
183 setOperationAction(ISD::SELECT, MVT::i32, Custom);
184 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000185 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 setOperationAction(ISD::SELECT, MVT::f32, Custom);
187 setOperationAction(ISD::SELECT, MVT::f64, Custom);
188 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
189 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000190 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
192 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000193 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
195
196 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
197 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
198 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
199
200 setOperationAction(ISD::FREM, MVT::f32, Expand);
201 setOperationAction(ISD::FREM, MVT::f64, Expand);
202 setOperationAction(ISD::FREM, MVT::f80, Expand);
203
Amara Emersone27d5012018-04-10 19:01:58 +0000204 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
205
Tim Northover3b0846e2014-05-24 12:50:23 +0000206 // Custom lowering hooks are needed for XOR
207 // to fold it into CSINC/CSINV.
208 setOperationAction(ISD::XOR, MVT::i32, Custom);
209 setOperationAction(ISD::XOR, MVT::i64, Custom);
210
211 // Virtually no operation on f128 is legal, but LLVM can't expand them when
212 // there's a valid register class, so we need custom operations in most cases.
213 setOperationAction(ISD::FABS, MVT::f128, Expand);
214 setOperationAction(ISD::FADD, MVT::f128, Custom);
215 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
216 setOperationAction(ISD::FCOS, MVT::f128, Expand);
217 setOperationAction(ISD::FDIV, MVT::f128, Custom);
218 setOperationAction(ISD::FMA, MVT::f128, Expand);
219 setOperationAction(ISD::FMUL, MVT::f128, Custom);
220 setOperationAction(ISD::FNEG, MVT::f128, Expand);
221 setOperationAction(ISD::FPOW, MVT::f128, Expand);
222 setOperationAction(ISD::FREM, MVT::f128, Expand);
223 setOperationAction(ISD::FRINT, MVT::f128, Expand);
224 setOperationAction(ISD::FSIN, MVT::f128, Expand);
225 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
226 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
227 setOperationAction(ISD::FSUB, MVT::f128, Custom);
228 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
229 setOperationAction(ISD::SETCC, MVT::f128, Custom);
230 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
231 setOperationAction(ISD::SELECT, MVT::f128, Custom);
232 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
233 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
234
235 // Lowering for many of the conversions is actually specified by the non-f128
236 // type. The LowerXXX function will be trivial when f128 isn't involved.
237 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
238 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
239 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
240 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
241 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
242 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
243 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
244 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
245 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
246 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
247 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
248 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
249 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
250 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
251
252 // Variable arguments.
253 setOperationAction(ISD::VASTART, MVT::Other, Custom);
254 setOperationAction(ISD::VAARG, MVT::Other, Custom);
255 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
256 setOperationAction(ISD::VAEND, MVT::Other, Expand);
257
258 // Variable-sized objects.
259 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
260 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000261
262 if (Subtarget->isTargetWindows())
263 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
264 else
265 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000266
Tim Northover3b0846e2014-05-24 12:50:23 +0000267 // Constant pool entries
268 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
269
270 // BlockAddress
271 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
272
273 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
274 setOperationAction(ISD::ADDC, MVT::i32, Custom);
275 setOperationAction(ISD::ADDE, MVT::i32, Custom);
276 setOperationAction(ISD::SUBC, MVT::i32, Custom);
277 setOperationAction(ISD::SUBE, MVT::i32, Custom);
278 setOperationAction(ISD::ADDC, MVT::i64, Custom);
279 setOperationAction(ISD::ADDE, MVT::i64, Custom);
280 setOperationAction(ISD::SUBC, MVT::i64, Custom);
281 setOperationAction(ISD::SUBE, MVT::i64, Custom);
282
283 // AArch64 lacks both left-rotate and popcount instructions.
284 setOperationAction(ISD::ROTL, MVT::i32, Expand);
285 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000286 for (MVT VT : MVT::vector_valuetypes()) {
287 setOperationAction(ISD::ROTL, VT, Expand);
288 setOperationAction(ISD::ROTR, VT, Expand);
289 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000290
291 // AArch64 doesn't have {U|S}MUL_LOHI.
292 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
293 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
294
Tim Northover3b0846e2014-05-24 12:50:23 +0000295 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
296 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
297
298 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
299 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000300 for (MVT VT : MVT::vector_valuetypes()) {
301 setOperationAction(ISD::SDIVREM, VT, Expand);
302 setOperationAction(ISD::UDIVREM, VT, Expand);
303 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000304 setOperationAction(ISD::SREM, MVT::i32, Expand);
305 setOperationAction(ISD::SREM, MVT::i64, Expand);
306 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
307 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
308 setOperationAction(ISD::UREM, MVT::i32, Expand);
309 setOperationAction(ISD::UREM, MVT::i64, Expand);
310
311 // Custom lower Add/Sub/Mul with overflow.
312 setOperationAction(ISD::SADDO, MVT::i32, Custom);
313 setOperationAction(ISD::SADDO, MVT::i64, Custom);
314 setOperationAction(ISD::UADDO, MVT::i32, Custom);
315 setOperationAction(ISD::UADDO, MVT::i64, Custom);
316 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
317 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
318 setOperationAction(ISD::USUBO, MVT::i32, Custom);
319 setOperationAction(ISD::USUBO, MVT::i64, Custom);
320 setOperationAction(ISD::SMULO, MVT::i32, Custom);
321 setOperationAction(ISD::SMULO, MVT::i64, Custom);
322 setOperationAction(ISD::UMULO, MVT::i32, Custom);
323 setOperationAction(ISD::UMULO, MVT::i64, Custom);
324
325 setOperationAction(ISD::FSIN, MVT::f32, Expand);
326 setOperationAction(ISD::FSIN, MVT::f64, Expand);
327 setOperationAction(ISD::FCOS, MVT::f32, Expand);
328 setOperationAction(ISD::FCOS, MVT::f64, Expand);
329 setOperationAction(ISD::FPOW, MVT::f32, Expand);
330 setOperationAction(ISD::FPOW, MVT::f64, Expand);
331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000333 if (Subtarget->hasFullFP16())
334 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
335 else
336 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000337
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000338 setOperationAction(ISD::FREM, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000339 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
340 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000341 setOperationAction(ISD::FPOW, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000342 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
343 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000344 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000345 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
346 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000347 setOperationAction(ISD::FCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000348 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
349 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000350 setOperationAction(ISD::FSIN, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000351 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
352 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000353 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000354 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
355 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000356 setOperationAction(ISD::FEXP, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000357 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
358 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000359 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000360 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
361 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000362 setOperationAction(ISD::FLOG, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000363 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
364 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000365 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000366 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
367 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000368 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000369 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
370 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000371
372 if (!Subtarget->hasFullFP16()) {
373 setOperationAction(ISD::SELECT, MVT::f16, Promote);
374 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
375 setOperationAction(ISD::SETCC, MVT::f16, Promote);
376 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
377 setOperationAction(ISD::FADD, MVT::f16, Promote);
378 setOperationAction(ISD::FSUB, MVT::f16, Promote);
379 setOperationAction(ISD::FMUL, MVT::f16, Promote);
380 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000381 setOperationAction(ISD::FMA, MVT::f16, Promote);
382 setOperationAction(ISD::FNEG, MVT::f16, Promote);
383 setOperationAction(ISD::FABS, MVT::f16, Promote);
384 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
385 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000386 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
387 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
388 setOperationAction(ISD::FRINT, MVT::f16, Promote);
389 setOperationAction(ISD::FROUND, MVT::f16, Promote);
390 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
391 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
392 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000393 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
394 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000395
396 // promote v4f16 to v4f32 when that is known to be safe.
397 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
398 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
399 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
400 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
401 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
402 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
403 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
404 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
405 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
406 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
407 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
408 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
409
410 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
411 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
412 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
413 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
414 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
415 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
416 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
417 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
418 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
419 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
420 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
421 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
422 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
423 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
424 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000425
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000426 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
427 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
428 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
429 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
430 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
431 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
432 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
433 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
434 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
435 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
436 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
437 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
438 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
439 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
440 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
441 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
442 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
443 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
444 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
445 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
446 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000447
Tim Northover3b0846e2014-05-24 12:50:23 +0000448 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000449 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 setOperationAction(ISD::FFLOOR, Ty, Legal);
451 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
452 setOperationAction(ISD::FCEIL, Ty, Legal);
453 setOperationAction(ISD::FRINT, Ty, Legal);
454 setOperationAction(ISD::FTRUNC, Ty, Legal);
455 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000456 setOperationAction(ISD::FMINNUM, Ty, Legal);
457 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000458 setOperationAction(ISD::FMINIMUM, Ty, Legal);
459 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Adhemerval Zanella2d28db62019-05-16 13:30:18 +0000460 setOperationAction(ISD::LROUND, Ty, Legal);
461 setOperationAction(ISD::LLROUND, Ty, Legal);
Adhemerval Zanella34d8daa2019-05-28 21:04:29 +0000462 setOperationAction(ISD::LRINT, Ty, Legal);
463 setOperationAction(ISD::LLRINT, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000464 }
465
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000466 if (Subtarget->hasFullFP16()) {
467 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
468 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
469 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
470 setOperationAction(ISD::FRINT, MVT::f16, Legal);
471 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
472 setOperationAction(ISD::FROUND, MVT::f16, Legal);
473 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
474 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000475 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
476 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000477 }
478
Tim Northover3b0846e2014-05-24 12:50:23 +0000479 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
480
Tim Northover70666e72018-06-20 12:09:01 +0000481 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
482
Tim Northovercdf15292016-04-14 17:03:29 +0000483 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000484 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000488
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000489 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
490 // This requires the Performance Monitors extension.
491 if (Subtarget->hasPerfMon())
492 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
493
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000494 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
495 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
496 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000497 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
498 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
499 } else {
500 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
501 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
502 }
503
Juergen Ributzka23266502014-12-10 19:43:32 +0000504 // Make floating-point constants legal for the large code model, so they don't
505 // become loads from the constant pool.
506 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
507 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
508 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
509 }
510
Tim Northover3b0846e2014-05-24 12:50:23 +0000511 // AArch64 does not have floating-point extending loads, i1 sign-extending
512 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000513 for (MVT VT : MVT::fp_valuetypes()) {
514 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
515 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
516 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
517 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
518 }
519 for (MVT VT : MVT::integer_valuetypes())
520 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
521
Tim Northover3b0846e2014-05-24 12:50:23 +0000522 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
523 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
524 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
525 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
526 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
527 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
528 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000529
530 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
531 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
532
Tim Northover3b0846e2014-05-24 12:50:23 +0000533 // Indexed loads and stores are supported.
534 for (unsigned im = (unsigned)ISD::PRE_INC;
535 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
536 setIndexedLoadAction(im, MVT::i8, Legal);
537 setIndexedLoadAction(im, MVT::i16, Legal);
538 setIndexedLoadAction(im, MVT::i32, Legal);
539 setIndexedLoadAction(im, MVT::i64, Legal);
540 setIndexedLoadAction(im, MVT::f64, Legal);
541 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000542 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000543 setIndexedStoreAction(im, MVT::i8, Legal);
544 setIndexedStoreAction(im, MVT::i16, Legal);
545 setIndexedStoreAction(im, MVT::i32, Legal);
546 setIndexedStoreAction(im, MVT::i64, Legal);
547 setIndexedStoreAction(im, MVT::f64, Legal);
548 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000549 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000550 }
551
552 // Trap.
553 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Tom Tan7ecb5142019-06-21 23:38:05 +0000554 if (Subtarget->isTargetWindows())
555 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000556
557 // We combine OR nodes for bitfield operations.
558 setTargetDAGCombine(ISD::OR);
Nikita Popov1a261442019-03-15 21:04:34 +0000559 // Try to create BICs for vector ANDs.
560 setTargetDAGCombine(ISD::AND);
Tim Northover3b0846e2014-05-24 12:50:23 +0000561
562 // Vector add and sub nodes may conceal a high-half opportunity.
563 // Also, try to fold ADD into CSINC/CSINV..
564 setTargetDAGCombine(ISD::ADD);
565 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000566 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000567 setTargetDAGCombine(ISD::XOR);
568 setTargetDAGCombine(ISD::SINT_TO_FP);
569 setTargetDAGCombine(ISD::UINT_TO_FP);
570
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000571 setTargetDAGCombine(ISD::FP_TO_SINT);
572 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000573 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000574
Tim Northover3b0846e2014-05-24 12:50:23 +0000575 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
576
577 setTargetDAGCombine(ISD::ANY_EXTEND);
578 setTargetDAGCombine(ISD::ZERO_EXTEND);
579 setTargetDAGCombine(ISD::SIGN_EXTEND);
580 setTargetDAGCombine(ISD::BITCAST);
581 setTargetDAGCombine(ISD::CONCAT_VECTORS);
582 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000583 if (Subtarget->supportsAddressTopByteIgnored())
584 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000585
586 setTargetDAGCombine(ISD::MUL);
587
588 setTargetDAGCombine(ISD::SELECT);
589 setTargetDAGCombine(ISD::VSELECT);
590
591 setTargetDAGCombine(ISD::INTRINSIC_VOID);
592 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
594
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000595 setTargetDAGCombine(ISD::GlobalAddress);
596
Evandro Menezesf8425342018-05-29 15:58:50 +0000597 // In case of strict alignment, avoid an excessive number of byte wide stores.
598 MaxStoresPerMemsetOptSize = 8;
599 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
600 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000601
Evandro Menezesf8425342018-05-29 15:58:50 +0000602 MaxGluedStoresPerMemcpy = 4;
603 MaxStoresPerMemcpyOptSize = 4;
604 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
605 ? MaxStoresPerMemcpyOptSize : 16;
606
607 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000608
609 setStackPointerRegisterToSaveRestore(AArch64::SP);
610
611 setSchedulingPreference(Sched::Hybrid);
612
Quentin Colombet6843ac42015-03-31 20:52:32 +0000613 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000614
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000615 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000616 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000617 // Set preferred alignments.
618 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
619 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000620
Evandro Menezese45de8a2016-09-26 15:32:33 +0000621 // Only change the limit for entries in a jump table if specified by
Evandro Menezes0f797b82019-03-29 17:28:11 +0000622 // the sub target, but not at the command line.
Evandro Menezese45de8a2016-09-26 15:32:33 +0000623 unsigned MaxJT = STI.getMaximumJumpTableSize();
Evandro Menezes0f797b82019-03-29 17:28:11 +0000624 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
Evandro Menezese45de8a2016-09-26 15:32:33 +0000625 setMaximumJumpTableSize(MaxJT);
626
Tim Northover3b0846e2014-05-24 12:50:23 +0000627 setHasExtractBitsInsn(true);
628
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000629 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
630
Tim Northover3b0846e2014-05-24 12:50:23 +0000631 if (Subtarget->hasNEON()) {
632 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
633 // silliness like this:
634 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
635 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
636 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
637 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
638 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
639 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
640 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
641 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
642 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
643 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
644 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
645 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
646 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
647 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
648 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
649 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
650 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
651 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
652 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
653 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
654 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
655 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
656 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
657 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
658 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
659
660 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
661 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
662 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
663 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
664 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
665
666 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
667
668 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
669 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000670 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
671 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000672 // i8 vector elements also need promotion to i32 for v8i8
Craig Toppera4f99972018-01-01 19:21:35 +0000673 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
674 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000675 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
676 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
677 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
678 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
679 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000680 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
681 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
682 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
683 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000684
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000685 if (Subtarget->hasFullFP16()) {
686 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
687 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
688 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
689 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
690 } else {
691 // when AArch64 doesn't have fullfp16 support, promote the input
692 // to i32 first.
693 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
694 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
695 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
696 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
697 }
698
Craig Topperc5551bf2016-04-26 05:26:51 +0000699 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
700 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
701
Tim Northover3b0846e2014-05-24 12:50:23 +0000702 // AArch64 doesn't have MUL.2d:
703 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000704 // Custom handling for some quad-vector types to detect MULL.
705 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
706 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
707 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
708
Amara Emersonc9916d72017-05-16 21:29:22 +0000709 // Vector reductions
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000710 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
711 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000712 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
713 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
714 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
715 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
716 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
717 }
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000718 for (MVT VT : { MVT::v4f16, MVT::v2f32,
719 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000720 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
721 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
722 }
723
Tim Northover3b0846e2014-05-24 12:50:23 +0000724 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
725 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
726 // Likewise, narrowing and extending vector loads/stores aren't handled
727 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000728 for (MVT VT : MVT::vector_valuetypes()) {
729 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000730
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000731 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000732 setOperationAction(ISD::MULHS, VT, Legal);
733 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000734 } else {
735 setOperationAction(ISD::MULHS, VT, Expand);
736 setOperationAction(ISD::MULHU, VT, Expand);
737 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000738 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000739 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000740
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000741 setOperationAction(ISD::BSWAP, VT, Expand);
Nikita Popova3be17e2019-02-12 18:55:53 +0000742 setOperationAction(ISD::CTTZ, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000743
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000744 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000745 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000746 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
747 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
748 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
749 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000750 }
751
752 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000753 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000754 setOperationAction(ISD::FFLOOR, Ty, Legal);
755 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
756 setOperationAction(ISD::FCEIL, Ty, Legal);
757 setOperationAction(ISD::FRINT, Ty, Legal);
758 setOperationAction(ISD::FTRUNC, Ty, Legal);
759 setOperationAction(ISD::FROUND, Ty, Legal);
760 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000761
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +0000762 if (Subtarget->hasFullFP16()) {
763 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
764 setOperationAction(ISD::FFLOOR, Ty, Legal);
765 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
766 setOperationAction(ISD::FCEIL, Ty, Legal);
767 setOperationAction(ISD::FRINT, Ty, Legal);
768 setOperationAction(ISD::FTRUNC, Ty, Legal);
769 setOperationAction(ISD::FROUND, Ty, Legal);
770 }
771 }
772
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000773 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000774 }
James Molloyf089ab72014-08-06 10:42:18 +0000775
Matthias Braun651cff42016-06-02 18:03:53 +0000776 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000777}
778
Craig Topper18e69f42016-04-15 06:20:21 +0000779void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000780 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000781
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000782 if (VT.isFloatingPoint()) {
783 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
784 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
785 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000786 }
787
788 // Mark vector float intrinsics as expand.
789 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000790 setOperationAction(ISD::FSIN, VT, Expand);
791 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000792 setOperationAction(ISD::FPOW, VT, Expand);
793 setOperationAction(ISD::FLOG, VT, Expand);
794 setOperationAction(ISD::FLOG2, VT, Expand);
795 setOperationAction(ISD::FLOG10, VT, Expand);
796 setOperationAction(ISD::FEXP, VT, Expand);
797 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000798
799 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000800 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000801 }
802
Craig Topper18e69f42016-04-15 06:20:21 +0000803 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
804 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
805 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
806 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
807 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
808 setOperationAction(ISD::SRA, VT, Custom);
809 setOperationAction(ISD::SRL, VT, Custom);
810 setOperationAction(ISD::SHL, VT, Custom);
Craig Topper18e69f42016-04-15 06:20:21 +0000811 setOperationAction(ISD::OR, VT, Custom);
812 setOperationAction(ISD::SETCC, VT, Custom);
813 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000814
Craig Topper18e69f42016-04-15 06:20:21 +0000815 setOperationAction(ISD::SELECT, VT, Expand);
816 setOperationAction(ISD::SELECT_CC, VT, Expand);
817 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000818 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000819 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000820
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000821 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000822 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000823 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000824
Craig Topper18e69f42016-04-15 06:20:21 +0000825 setOperationAction(ISD::UDIV, VT, Expand);
826 setOperationAction(ISD::SDIV, VT, Expand);
827 setOperationAction(ISD::UREM, VT, Expand);
828 setOperationAction(ISD::SREM, VT, Expand);
829 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000830
Craig Topper18e69f42016-04-15 06:20:21 +0000831 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
832 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000833
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000834 if (!VT.isFloatingPoint())
835 setOperationAction(ISD::ABS, VT, Legal);
836
Hal Finkelcd8664c2015-12-11 23:11:52 +0000837 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000838 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000839 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000840 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000841
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000842 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
843 if (VT.isFloatingPoint() &&
844 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000845 for (unsigned Opcode :
846 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000847 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000848
Tim Northover3b0846e2014-05-24 12:50:23 +0000849 if (Subtarget->isLittleEndian()) {
850 for (unsigned im = (unsigned)ISD::PRE_INC;
851 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000852 setIndexedLoadAction(im, VT, Legal);
853 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000854 }
855 }
856}
857
858void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
859 addRegisterClass(VT, &AArch64::FPR64RegClass);
860 addTypeForNEON(VT, MVT::v2i32);
861}
862
863void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
864 addRegisterClass(VT, &AArch64::FPR128RegClass);
865 addTypeForNEON(VT, MVT::v4i32);
866}
867
Mehdi Amini44ede332015-07-09 02:09:04 +0000868EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
869 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000870 if (!VT.isVector())
871 return MVT::i32;
872 return VT.changeVectorElementTypeToInteger();
873}
874
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000875static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
876 const APInt &Demanded,
877 TargetLowering::TargetLoweringOpt &TLO,
878 unsigned NewOpc) {
879 uint64_t OldImm = Imm, NewImm, Enc;
880 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
881
882 // Return if the immediate is already all zeros, all ones, a bimm32 or a
883 // bimm64.
884 if (Imm == 0 || Imm == Mask ||
885 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
886 return false;
887
888 unsigned EltSize = Size;
889 uint64_t DemandedBits = Demanded.getZExtValue();
890
891 // Clear bits that are not demanded.
892 Imm &= DemandedBits;
893
894 while (true) {
895 // The goal here is to set the non-demanded bits in a way that minimizes
896 // the number of switching between 0 and 1. In order to achieve this goal,
897 // we set the non-demanded bits to the value of the preceding demanded bits.
898 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
899 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
900 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
901 // The final result is 0b11000011.
902 uint64_t NonDemandedBits = ~DemandedBits;
903 uint64_t InvertedImm = ~Imm & DemandedBits;
904 uint64_t RotatedImm =
905 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
906 NonDemandedBits;
907 uint64_t Sum = RotatedImm + NonDemandedBits;
908 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
909 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
910 NewImm = (Imm | Ones) & Mask;
911
912 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
913 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
914 // we halve the element size and continue the search.
915 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
916 break;
917
918 // We cannot shrink the element size any further if it is 2-bits.
919 if (EltSize == 2)
920 return false;
921
922 EltSize /= 2;
923 Mask >>= EltSize;
924 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
925
926 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
927 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
928 return false;
929
930 // Merge the upper and lower halves of Imm and DemandedBits.
931 Imm |= Hi;
932 DemandedBits |= DemandedBitsHi;
933 }
934
935 ++NumOptimizedImms;
936
937 // Replicate the element across the register width.
938 while (EltSize < Size) {
939 NewImm |= NewImm << EltSize;
940 EltSize *= 2;
941 }
942
943 (void)OldImm;
944 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
945 "demanded bits should never be altered");
946 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
947
948 // Create the new constant immediate node.
949 EVT VT = Op.getValueType();
950 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000951 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000952
953 // If the new constant immediate is all-zeros or all-ones, let the target
954 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000955 if (NewImm == 0 || NewImm == OrigMask) {
956 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
957 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000958 // Otherwise, create a machine node so that target independent DAG combine
959 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000960 } else {
961 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
962 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
963 New = SDValue(
964 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
965 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000966
967 return TLO.CombineTo(Op, New);
968}
969
970bool AArch64TargetLowering::targetShrinkDemandedConstant(
971 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
972 // Delay this optimization to as late as possible.
973 if (!TLO.LegalOps)
974 return false;
975
976 if (!EnableOptimizeLogicalImm)
977 return false;
978
979 EVT VT = Op.getValueType();
980 if (VT.isVector())
981 return false;
982
983 unsigned Size = VT.getSizeInBits();
984 assert((Size == 32 || Size == 64) &&
985 "i32 or i64 is expected after legalization.");
986
987 // Exit early if we demand all bits.
988 if (Demanded.countPopulation() == Size)
989 return false;
990
991 unsigned NewOpc;
992 switch (Op.getOpcode()) {
993 default:
994 return false;
995 case ISD::AND:
996 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
997 break;
998 case ISD::OR:
999 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1000 break;
1001 case ISD::XOR:
1002 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1003 break;
1004 }
1005 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1006 if (!C)
1007 return false;
1008 uint64_t Imm = C->getZExtValue();
1009 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1010}
1011
Tim Northover3b0846e2014-05-24 12:50:23 +00001012/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +00001013/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +00001014void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +00001015 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +00001016 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001017 switch (Op.getOpcode()) {
1018 default:
1019 break;
1020 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001021 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +00001022 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1023 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +00001024 Known.Zero &= Known2.Zero;
1025 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001026 break;
1027 }
1028 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001029 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001030 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1031 switch (IntID) {
1032 default: return;
1033 case Intrinsic::aarch64_ldaxr:
1034 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001035 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001037 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001038 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001039 return;
1040 }
1041 }
1042 break;
1043 }
1044 case ISD::INTRINSIC_WO_CHAIN:
1045 case ISD::INTRINSIC_VOID: {
1046 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1047 switch (IntNo) {
1048 default:
1049 break;
1050 case Intrinsic::aarch64_neon_umaxv:
1051 case Intrinsic::aarch64_neon_uminv: {
1052 // Figure out the datatype of the vector operand. The UMINV instruction
1053 // will zero extend the result, so we can mark as known zero all the
1054 // bits larger than the element datatype. 32-bit or larget doesn't need
1055 // this as those are legal types and will be handled by isel directly.
1056 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001057 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001058 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1059 assert(BitWidth >= 8 && "Unexpected width!");
1060 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001061 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001062 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1063 assert(BitWidth >= 16 && "Unexpected width!");
1064 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001065 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001066 }
1067 break;
1068 } break;
1069 }
1070 }
1071 }
1072}
1073
Mehdi Aminieaabc512015-07-09 15:12:23 +00001074MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1075 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001076 return MVT::i64;
1077}
1078
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00001079bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1080 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1081 bool *Fast) const {
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001082 if (Subtarget->requiresStrictAlign())
1083 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001084
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001085 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001086 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1087 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001088 // See comments in performSTORECombine() for more details about
1089 // these conditions.
1090
1091 // Code that uses clang vector extensions can mark that it
1092 // wants unaligned accesses to be treated as fast by
1093 // underspecifying alignment to be 1 or 2.
1094 Align <= 2 ||
1095
1096 // Disregard v2i64. Memcpy lowering produces those and splitting
1097 // them regresses performance on micro-benchmarks and olden/bh.
1098 VT == MVT::v2i64;
1099 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001100 return true;
1101}
1102
Amara Emerson13af1ed2019-07-24 22:17:31 +00001103// Same as above but handling LLTs instead.
1104bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1105 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1106 bool *Fast) const {
1107 if (Subtarget->requiresStrictAlign())
1108 return false;
1109
1110 if (Fast) {
1111 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1112 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1113 Ty.getSizeInBytes() != 16 ||
1114 // See comments in performSTORECombine() for more details about
1115 // these conditions.
1116
1117 // Code that uses clang vector extensions can mark that it
1118 // wants unaligned accesses to be treated as fast by
1119 // underspecifying alignment to be 1 or 2.
1120 Align <= 2 ||
1121
1122 // Disregard v2i64. Memcpy lowering produces those and splitting
1123 // them regresses performance on micro-benchmarks and olden/bh.
1124 Ty == LLT::vector(2, 64);
1125 }
1126 return true;
1127}
1128
Tim Northover3b0846e2014-05-24 12:50:23 +00001129FastISel *
1130AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1131 const TargetLibraryInfo *libInfo) const {
1132 return AArch64::createFastISel(funcInfo, libInfo);
1133}
1134
1135const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001136 switch ((AArch64ISD::NodeType)Opcode) {
1137 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001138 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1139 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001140 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001141 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1142 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1143 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1144 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1145 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1146 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1147 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1148 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1149 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1150 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001151 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001152 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1153 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1154 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1155 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1156 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1157 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1158 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001159 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1160 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1161 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001162 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001163 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1164 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1165 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1166 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1167 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1168 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1169 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1170 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1171 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1172 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1173 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1174 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1175 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1176 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1177 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1178 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1179 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1180 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1181 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1182 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1183 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1184 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1185 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1186 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1187 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1188 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1189 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1190 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1191 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1192 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1193 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1194 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1195 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1196 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1197 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1198 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1199 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1200 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1201 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1202 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1203 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1204 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1205 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1206 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1207 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1208 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1209 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1210 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001211 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1212 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1213 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1214 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1215 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1216 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001217 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1218 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1219 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1220 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1221 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1222 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1223 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001224 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001225 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1226 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001227 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001228 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1229 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1230 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1231 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1232 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1233 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1234 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1235 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1236 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1237 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1238 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1239 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1240 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1241 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1242 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1243 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1244 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1245 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1246 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1247 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1248 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1249 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1250 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1251 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1252 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1253 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1254 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1255 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1256 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001257 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1258 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001259 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001260 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1261 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1262 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Evgeniy Stepanovd752f5e2019-07-17 19:24:02 +00001263 case AArch64ISD::STG: return "AArch64ISD::STG";
1264 case AArch64ISD::STZG: return "AArch64ISD::STZG";
1265 case AArch64ISD::ST2G: return "AArch64ISD::ST2G";
1266 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G";
Tim Northover3b0846e2014-05-24 12:50:23 +00001267 }
Matthias Braund04893f2015-05-07 21:33:59 +00001268 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001269}
1270
1271MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001272AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001273 MachineBasicBlock *MBB) const {
1274 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1275 // phi node:
1276
1277 // OrigBB:
1278 // [... previous instrs leading to comparison ...]
1279 // b.ne TrueBB
1280 // b EndBB
1281 // TrueBB:
1282 // ; Fallthrough
1283 // EndBB:
1284 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1285
Tim Northover3b0846e2014-05-24 12:50:23 +00001286 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001287 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001288 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001289 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001290 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001291
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001292 unsigned DestReg = MI.getOperand(0).getReg();
1293 unsigned IfTrueReg = MI.getOperand(1).getReg();
1294 unsigned IfFalseReg = MI.getOperand(2).getReg();
1295 unsigned CondCode = MI.getOperand(3).getImm();
1296 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001297
1298 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1299 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1300 MF->insert(It, TrueBB);
1301 MF->insert(It, EndBB);
1302
1303 // Transfer rest of current basic-block to EndBB
1304 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1305 MBB->end());
1306 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1307
1308 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1309 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1310 MBB->addSuccessor(TrueBB);
1311 MBB->addSuccessor(EndBB);
1312
1313 // TrueBB falls through to the end.
1314 TrueBB->addSuccessor(EndBB);
1315
1316 if (!NZCVKilled) {
1317 TrueBB->addLiveIn(AArch64::NZCV);
1318 EndBB->addLiveIn(AArch64::NZCV);
1319 }
1320
1321 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1322 .addReg(IfTrueReg)
1323 .addMBB(TrueBB)
1324 .addReg(IfFalseReg)
1325 .addMBB(MBB);
1326
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001327 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001328 return EndBB;
1329}
1330
Eli Friedmanad1151c2018-11-09 23:33:30 +00001331MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1332 MachineInstr &MI, MachineBasicBlock *BB) const {
1333 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1334 BB->getParent()->getFunction().getPersonalityFn())) &&
1335 "SEH does not use catchret!");
1336 return BB;
1337}
1338
1339MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1340 MachineInstr &MI, MachineBasicBlock *BB) const {
1341 MI.eraseFromParent();
1342 return BB;
1343}
1344
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001345MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1346 MachineInstr &MI, MachineBasicBlock *BB) const {
1347 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001348 default:
1349#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001350 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001351#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001352 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001353
1354 case AArch64::F128CSEL:
1355 return EmitF128CSEL(MI, BB);
1356
1357 case TargetOpcode::STACKMAP:
1358 case TargetOpcode::PATCHPOINT:
1359 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001360
1361 case AArch64::CATCHRET:
1362 return EmitLoweredCatchRet(MI, BB);
1363 case AArch64::CATCHPAD:
1364 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001365 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001366}
1367
1368//===----------------------------------------------------------------------===//
1369// AArch64 Lowering private implementation.
1370//===----------------------------------------------------------------------===//
1371
1372//===----------------------------------------------------------------------===//
1373// Lowering Code
1374//===----------------------------------------------------------------------===//
1375
1376/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1377/// CC
1378static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1379 switch (CC) {
1380 default:
1381 llvm_unreachable("Unknown condition code!");
1382 case ISD::SETNE:
1383 return AArch64CC::NE;
1384 case ISD::SETEQ:
1385 return AArch64CC::EQ;
1386 case ISD::SETGT:
1387 return AArch64CC::GT;
1388 case ISD::SETGE:
1389 return AArch64CC::GE;
1390 case ISD::SETLT:
1391 return AArch64CC::LT;
1392 case ISD::SETLE:
1393 return AArch64CC::LE;
1394 case ISD::SETUGT:
1395 return AArch64CC::HI;
1396 case ISD::SETUGE:
1397 return AArch64CC::HS;
1398 case ISD::SETULT:
1399 return AArch64CC::LO;
1400 case ISD::SETULE:
1401 return AArch64CC::LS;
1402 }
1403}
1404
1405/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1406static void changeFPCCToAArch64CC(ISD::CondCode CC,
1407 AArch64CC::CondCode &CondCode,
1408 AArch64CC::CondCode &CondCode2) {
1409 CondCode2 = AArch64CC::AL;
1410 switch (CC) {
1411 default:
1412 llvm_unreachable("Unknown FP condition!");
1413 case ISD::SETEQ:
1414 case ISD::SETOEQ:
1415 CondCode = AArch64CC::EQ;
1416 break;
1417 case ISD::SETGT:
1418 case ISD::SETOGT:
1419 CondCode = AArch64CC::GT;
1420 break;
1421 case ISD::SETGE:
1422 case ISD::SETOGE:
1423 CondCode = AArch64CC::GE;
1424 break;
1425 case ISD::SETOLT:
1426 CondCode = AArch64CC::MI;
1427 break;
1428 case ISD::SETOLE:
1429 CondCode = AArch64CC::LS;
1430 break;
1431 case ISD::SETONE:
1432 CondCode = AArch64CC::MI;
1433 CondCode2 = AArch64CC::GT;
1434 break;
1435 case ISD::SETO:
1436 CondCode = AArch64CC::VC;
1437 break;
1438 case ISD::SETUO:
1439 CondCode = AArch64CC::VS;
1440 break;
1441 case ISD::SETUEQ:
1442 CondCode = AArch64CC::EQ;
1443 CondCode2 = AArch64CC::VS;
1444 break;
1445 case ISD::SETUGT:
1446 CondCode = AArch64CC::HI;
1447 break;
1448 case ISD::SETUGE:
1449 CondCode = AArch64CC::PL;
1450 break;
1451 case ISD::SETLT:
1452 case ISD::SETULT:
1453 CondCode = AArch64CC::LT;
1454 break;
1455 case ISD::SETLE:
1456 case ISD::SETULE:
1457 CondCode = AArch64CC::LE;
1458 break;
1459 case ISD::SETNE:
1460 case ISD::SETUNE:
1461 CondCode = AArch64CC::NE;
1462 break;
1463 }
1464}
1465
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001466/// Convert a DAG fp condition code to an AArch64 CC.
1467/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1468/// should be AND'ed instead of OR'ed.
1469static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1470 AArch64CC::CondCode &CondCode,
1471 AArch64CC::CondCode &CondCode2) {
1472 CondCode2 = AArch64CC::AL;
1473 switch (CC) {
1474 default:
1475 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1476 assert(CondCode2 == AArch64CC::AL);
1477 break;
1478 case ISD::SETONE:
1479 // (a one b)
1480 // == ((a olt b) || (a ogt b))
1481 // == ((a ord b) && (a une b))
1482 CondCode = AArch64CC::VC;
1483 CondCode2 = AArch64CC::NE;
1484 break;
1485 case ISD::SETUEQ:
1486 // (a ueq b)
1487 // == ((a uno b) || (a oeq b))
1488 // == ((a ule b) && (a uge b))
1489 CondCode = AArch64CC::PL;
1490 CondCode2 = AArch64CC::LE;
1491 break;
1492 }
1493}
1494
Tim Northover3b0846e2014-05-24 12:50:23 +00001495/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1496/// CC usable with the vector instructions. Fewer operations are available
1497/// without a real NZCV register, so we have to use less efficient combinations
1498/// to get the same effect.
1499static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1500 AArch64CC::CondCode &CondCode,
1501 AArch64CC::CondCode &CondCode2,
1502 bool &Invert) {
1503 Invert = false;
1504 switch (CC) {
1505 default:
1506 // Mostly the scalar mappings work fine.
1507 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1508 break;
1509 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001510 Invert = true;
1511 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001512 case ISD::SETO:
1513 CondCode = AArch64CC::MI;
1514 CondCode2 = AArch64CC::GE;
1515 break;
1516 case ISD::SETUEQ:
1517 case ISD::SETULT:
1518 case ISD::SETULE:
1519 case ISD::SETUGT:
1520 case ISD::SETUGE:
1521 // All of the compare-mask comparisons are ordered, but we can switch
1522 // between the two by a double inversion. E.g. ULE == !OGT.
1523 Invert = true;
1524 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1525 break;
1526 }
1527}
1528
1529static bool isLegalArithImmed(uint64_t C) {
1530 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001531 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001532 LLVM_DEBUG(dbgs() << "Is imm " << C
1533 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001534 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001535}
1536
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001537// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1538// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1539// can be set differently by this operation. It comes down to whether
1540// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1541// everything is fine. If not then the optimization is wrong. Thus general
1542// comparisons are only valid if op2 != 0.
1543//
1544// So, finally, the only LLVM-native comparisons that don't mention C and V
1545// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1546// the absence of information about op2.
1547static bool isCMN(SDValue Op, ISD::CondCode CC) {
1548 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1549 (CC == ISD::SETEQ || CC == ISD::SETNE);
1550}
1551
Tim Northover3b0846e2014-05-24 12:50:23 +00001552static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001553 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001554 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001555 const bool FullFP16 =
1556 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001557
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001558 if (VT.isFloatingPoint()) {
1559 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001560 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001561 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1562 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001563 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001564 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001565 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001566 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001567
1568 // The CMP instruction is just an alias for SUBS, and representing it as
1569 // SUBS means that it's possible to get CSE with subtract operations.
1570 // A later phase can perform the optimization of setting the destination
1571 // register to WZR/XZR if it ends up being unused.
1572 unsigned Opcode = AArch64ISD::SUBS;
1573
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001574 if (isCMN(RHS, CC)) {
1575 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001576 Opcode = AArch64ISD::ADDS;
1577 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001578 } else if (isCMN(LHS, CC)) {
1579 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1580 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1581 Opcode = AArch64ISD::ADDS;
1582 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001583 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001584 !isUnsignedIntSetCC(CC)) {
1585 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1586 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1587 // of the signed comparisons.
1588 Opcode = AArch64ISD::ANDS;
1589 RHS = LHS.getOperand(1);
1590 LHS = LHS.getOperand(0);
1591 }
1592
Matthias Braunaf7d7702015-07-16 20:02:37 +00001593 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001594 .getValue(1);
1595}
1596
Matthias Braunaf7d7702015-07-16 20:02:37 +00001597/// \defgroup AArch64CCMP CMP;CCMP matching
1598///
1599/// These functions deal with the formation of CMP;CCMP;... sequences.
1600/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1601/// a comparison. They set the NZCV flags to a predefined value if their
1602/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001603/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001604/// expressed as:
1605/// cmp A
1606/// ccmp B, inv(CB), CA
1607/// check for CB flags
1608///
Matthias Braund0412122018-12-06 01:40:23 +00001609/// This naturally lets us implement chains of AND operations with SETCC
1610/// operands. And we can even implement some other situations by transforming
1611/// them:
1612/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1613/// negating the flags used in a CCMP/FCCMP operations.
1614/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1615/// by negating the flags we test for afterwards. i.e.
1616/// NEG (CMP CCMP CCCMP ...) can be implemented.
1617/// - Note that we can only ever negate all previously processed results.
1618/// What we can not implement by flipping the flags to test is a negation
1619/// of two sub-trees (because the negation affects all sub-trees emitted so
1620/// far, so the 2nd sub-tree we emit would also affect the first).
1621/// With those tools we can implement some OR operations:
1622/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1623/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1624/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1625/// elimination rules from earlier to implement the whole thing as a
1626/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001627///
Matthias Braund0412122018-12-06 01:40:23 +00001628/// As complete example:
1629/// or (or (setCA (cmp A)) (setCB (cmp B)))
1630/// (and (setCC (cmp C)) (setCD (cmp D)))"
1631/// can be reassociated to:
1632/// or (and (setCC (cmp C)) setCD (cmp D))
1633// (or (setCA (cmp A)) (setCB (cmp B)))
1634/// can be transformed to:
1635/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1636/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1637/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001638/// cmp C
1639/// ccmp D, inv(CD), CC
1640/// ccmp A, CA, inv(CD)
1641/// ccmp B, CB, inv(CA)
1642/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001643///
1644/// A counterexample is "or (and A B) (and C D)" which translates to
1645/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1646/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001647/// @{
1648
Geoff Berrye41c2df2015-07-20 22:03:52 +00001649/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001650static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1651 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001652 AArch64CC::CondCode Predicate,
1653 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001654 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001655 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001656 const bool FullFP16 =
1657 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1658
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001659 if (LHS.getValueType().isFloatingPoint()) {
1660 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001661 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001662 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1663 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1664 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001665 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001666 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001667 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001668 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001669 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1670 Opcode = AArch64ISD::CCMN;
1671 RHS = RHS.getOperand(1);
1672 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001673 }
1674 if (Opcode == 0)
1675 Opcode = AArch64ISD::CCMP;
1676
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001677 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1678 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1679 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001680 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1681 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1682}
1683
Matthias Braun96d12512018-11-06 03:15:22 +00001684/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1685/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001686/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1687/// changing the conditions on the SETCC tests.
1688/// (this means we can call emitConjunctionRec() with
1689/// Negate==true on this sub-tree)
1690/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1691/// cannot do the negation naturally. We are required to
1692/// emit the subtree first in this case.
1693/// \param WillNegate Is true if are called when the result of this
1694/// subexpression must be negated. This happens when the
1695/// outer expression is an OR. We can use this fact to know
1696/// that we have a double negation (or (or ...) ...) that
1697/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001698static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001699 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001700 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001701 if (!Val.hasOneUse())
1702 return false;
1703 unsigned Opcode = Val->getOpcode();
1704 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001705 if (Val->getOperand(0).getValueType() == MVT::f128)
1706 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001707 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001708 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001709 return true;
1710 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001711 // Protect against exponential runtime and stack overflow.
1712 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001713 return false;
1714 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001715 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001716 SDValue O0 = Val->getOperand(0);
1717 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001718 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001719 bool MustBeFirstL;
1720 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001721 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001722 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001723 bool MustBeFirstR;
1724 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001725 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001726
Matthias Braund0412122018-12-06 01:40:23 +00001727 if (MustBeFirstL && MustBeFirstR)
1728 return false;
1729
1730 if (IsOR) {
1731 // For an OR expression we need to be able to naturally negate at least
1732 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001733 if (!CanNegateL && !CanNegateR)
1734 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001735 // If we the result of the OR will be negated and we can naturally negate
1736 // the leafs, then this sub-tree as a whole negates naturally.
1737 CanNegate = WillNegate && CanNegateL && CanNegateR;
1738 // If we cannot naturally negate the whole sub-tree, then this must be
1739 // emitted first.
1740 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001741 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001742 assert(Opcode == ISD::AND && "Must be OR or AND");
1743 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001744 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001745 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001746 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001747 return true;
1748 }
1749 return false;
1750}
1751
1752/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1753/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1754/// Tries to transform the given i1 producing node @p Val to a series compare
1755/// and conditional compare operations. @returns an NZCV flags producing node
1756/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1757/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001758/// \p Negate is true if we want this sub-tree being negated just by changing
1759/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001760static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001761 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001762 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001763 // We're at a tree leaf, produce a conditional comparison operation.
1764 unsigned Opcode = Val->getOpcode();
1765 if (Opcode == ISD::SETCC) {
1766 SDValue LHS = Val->getOperand(0);
1767 SDValue RHS = Val->getOperand(1);
1768 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1769 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001770 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001771 CC = getSetCCInverse(CC, isInteger);
1772 SDLoc DL(Val);
1773 // Determine OutCC and handle FP special case.
1774 if (isInteger) {
1775 OutCC = changeIntCCToAArch64CC(CC);
1776 } else {
1777 assert(LHS.getValueType().isFloatingPoint());
1778 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001779 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1780 // Some floating point conditions can't be tested with a single condition
1781 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001782 if (ExtraCC != AArch64CC::AL) {
1783 SDValue ExtraCmp;
1784 if (!CCOp.getNode())
1785 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001786 else
1787 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001788 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001789 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001790 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001791 }
1792 }
1793
1794 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001795 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001796 return emitComparison(LHS, RHS, CC, DL, DAG);
1797 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001798 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001799 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001800 }
Matthias Braund0412122018-12-06 01:40:23 +00001801 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001802
Matthias Braund0412122018-12-06 01:40:23 +00001803 bool IsOR = Opcode == ISD::OR;
1804
Matthias Braunaf7d7702015-07-16 20:02:37 +00001805 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001806 bool CanNegateL;
1807 bool MustBeFirstL;
1808 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1809 assert(ValidL && "Valid conjunction/disjunction tree");
1810 (void)ValidL;
1811
Matthias Braunaf7d7702015-07-16 20:02:37 +00001812 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001813 bool CanNegateR;
1814 bool MustBeFirstR;
1815 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1816 assert(ValidR && "Valid conjunction/disjunction tree");
1817 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001818
Matthias Braund0412122018-12-06 01:40:23 +00001819 // Swap sub-tree that must come first to the right side.
1820 if (MustBeFirstL) {
1821 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1822 std::swap(LHS, RHS);
1823 std::swap(CanNegateL, CanNegateR);
1824 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001825 }
1826
Matthias Braund0412122018-12-06 01:40:23 +00001827 bool NegateR;
1828 bool NegateAfterR;
1829 bool NegateL;
1830 bool NegateAfterAll;
1831 if (Opcode == ISD::OR) {
1832 // Swap the sub-tree that we can negate naturally to the left.
1833 if (!CanNegateL) {
1834 assert(CanNegateR && "at least one side must be negatable");
1835 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1836 assert(!Negate);
1837 std::swap(LHS, RHS);
1838 NegateR = false;
1839 NegateAfterR = true;
1840 } else {
1841 // Negate the left sub-tree if possible, otherwise negate the result.
1842 NegateR = CanNegateR;
1843 NegateAfterR = !CanNegateR;
1844 }
1845 NegateL = true;
1846 NegateAfterAll = !Negate;
1847 } else {
1848 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1849 assert(!Negate && "Valid conjunction/disjunction tree");
1850
1851 NegateL = false;
1852 NegateR = false;
1853 NegateAfterR = false;
1854 NegateAfterAll = false;
1855 }
1856
1857 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001858 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001859 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1860 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001861 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001862 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1863 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001864 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1865 return CmpL;
1866}
1867
Matthias Braun96d12512018-11-06 03:15:22 +00001868/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1869/// In some cases this is even possible with OR operations in the expression.
1870/// See \ref AArch64CCMP.
1871/// \see emitConjunctionRec().
1872static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1873 AArch64CC::CondCode &OutCC) {
1874 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001875 bool DummyMustBeFirst;
1876 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001877 return SDValue();
1878
Matthias Braun96d12512018-11-06 03:15:22 +00001879 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001880}
1881
Matthias Braunaf7d7702015-07-16 20:02:37 +00001882/// @}
1883
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001884/// Returns how profitable it is to fold a comparison's operand's shift and/or
1885/// extension operations.
1886static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1887 auto isSupportedExtend = [&](SDValue V) {
1888 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1889 return true;
1890
1891 if (V.getOpcode() == ISD::AND)
1892 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1893 uint64_t Mask = MaskCst->getZExtValue();
1894 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1895 }
1896
1897 return false;
1898 };
1899
1900 if (!Op.hasOneUse())
1901 return 0;
1902
1903 if (isSupportedExtend(Op))
1904 return 1;
1905
1906 unsigned Opc = Op.getOpcode();
1907 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1908 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1909 uint64_t Shift = ShiftCst->getZExtValue();
1910 if (isSupportedExtend(Op.getOperand(0)))
1911 return (Shift <= 4) ? 2 : 1;
1912 EVT VT = Op.getValueType();
1913 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1914 return 1;
1915 }
1916
1917 return 0;
1918}
1919
Tim Northover3b0846e2014-05-24 12:50:23 +00001920static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001921 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001922 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001923 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1924 EVT VT = RHS.getValueType();
1925 uint64_t C = RHSC->getZExtValue();
1926 if (!isLegalArithImmed(C)) {
1927 // Constant does not fit, try adjusting it by one?
1928 switch (CC) {
1929 default:
1930 break;
1931 case ISD::SETLT:
1932 case ISD::SETGE:
1933 if ((VT == MVT::i32 && C != 0x80000000 &&
1934 isLegalArithImmed((uint32_t)(C - 1))) ||
1935 (VT == MVT::i64 && C != 0x80000000ULL &&
1936 isLegalArithImmed(C - 1ULL))) {
1937 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1938 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001939 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001940 }
1941 break;
1942 case ISD::SETULT:
1943 case ISD::SETUGE:
1944 if ((VT == MVT::i32 && C != 0 &&
1945 isLegalArithImmed((uint32_t)(C - 1))) ||
1946 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1947 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1948 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001949 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001950 }
1951 break;
1952 case ISD::SETLE:
1953 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001954 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001955 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001956 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001957 isLegalArithImmed(C + 1ULL))) {
1958 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1959 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001960 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001961 }
1962 break;
1963 case ISD::SETULE:
1964 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001965 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001966 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001967 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001968 isLegalArithImmed(C + 1ULL))) {
1969 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1970 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001971 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001972 }
1973 break;
1974 }
1975 }
1976 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001977
1978 // Comparisons are canonicalized so that the RHS operand is simpler than the
1979 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1980 // can fold some shift+extend operations on the RHS operand, so swap the
1981 // operands if that can be done.
1982 //
1983 // For example:
1984 // lsl w13, w11, #1
1985 // cmp w13, w12
1986 // can be turned into:
1987 // cmp w12, w11, lsl #1
1988 if (!isa<ConstantSDNode>(RHS) ||
1989 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1990 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1991
1992 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1993 std::swap(LHS, RHS);
1994 CC = ISD::getSetCCSwappedOperands(CC);
1995 }
1996 }
1997
Matthias Braunaf7d7702015-07-16 20:02:37 +00001998 SDValue Cmp;
1999 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00002000 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002001 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2002
2003 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2004 // For the i8 operand, the largest immediate is 255, so this can be easily
2005 // encoded in the compare instruction. For the i16 operand, however, the
2006 // largest immediate cannot be encoded in the compare.
2007 // Therefore, use a sign extending load and cmn to avoid materializing the
2008 // -1 constant. For example,
2009 // movz w1, #65535
2010 // ldrh w0, [x0, #0]
2011 // cmp w0, w1
2012 // >
2013 // ldrsh w0, [x0, #0]
2014 // cmn w0, #1
2015 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2016 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002017 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00002018 // transformation is profitable.
2019 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2020 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2021 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2022 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2023 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2024 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2025 SDValue SExt =
2026 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2027 DAG.getValueType(MVT::i16));
2028 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2029 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002030 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002031 AArch64CC = changeIntCCToAArch64CC(CC);
2032 }
2033 }
2034
2035 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00002036 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002037 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2038 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00002039 }
2040 }
2041 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00002042
2043 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002044 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002045 AArch64CC = changeIntCCToAArch64CC(CC);
2046 }
2047 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00002048 return Cmp;
2049}
2050
2051static std::pair<SDValue, SDValue>
2052getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2053 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2054 "Unsupported value type");
2055 SDValue Value, Overflow;
2056 SDLoc DL(Op);
2057 SDValue LHS = Op.getOperand(0);
2058 SDValue RHS = Op.getOperand(1);
2059 unsigned Opc = 0;
2060 switch (Op.getOpcode()) {
2061 default:
2062 llvm_unreachable("Unknown overflow instruction!");
2063 case ISD::SADDO:
2064 Opc = AArch64ISD::ADDS;
2065 CC = AArch64CC::VS;
2066 break;
2067 case ISD::UADDO:
2068 Opc = AArch64ISD::ADDS;
2069 CC = AArch64CC::HS;
2070 break;
2071 case ISD::SSUBO:
2072 Opc = AArch64ISD::SUBS;
2073 CC = AArch64CC::VS;
2074 break;
2075 case ISD::USUBO:
2076 Opc = AArch64ISD::SUBS;
2077 CC = AArch64CC::LO;
2078 break;
2079 // Multiply needs a little bit extra work.
2080 case ISD::SMULO:
2081 case ISD::UMULO: {
2082 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002083 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002084 if (Op.getValueType() == MVT::i32) {
2085 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2086 // For a 32 bit multiply with overflow check we want the instruction
2087 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2088 // need to generate the following pattern:
2089 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2090 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2091 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2092 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2093 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002094 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002095 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2096 // operation. We need to clear out the upper 32 bits, because we used a
2097 // widening multiply that wrote all 64 bits. In the end this should be a
2098 // noop.
2099 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2100 if (IsSigned) {
2101 // The signed overflow check requires more than just a simple check for
2102 // any bit set in the upper 32 bits of the result. These bits could be
2103 // just the sign bits of a negative number. To perform the overflow
2104 // check we have to arithmetic shift right the 32nd bit of the result by
2105 // 31 bits. Then we compare the result to the upper 32 bits.
2106 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002107 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002108 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2109 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002110 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002111 // It is important that LowerBits is last, otherwise the arithmetic
2112 // shift will not be folded into the compare (SUBS).
2113 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2114 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2115 .getValue(1);
2116 } else {
2117 // The overflow check for unsigned multiply is easy. We only need to
2118 // check if any of the upper 32 bits are set. This can be done with a
2119 // CMP (shifted register). For that we need to generate the following
2120 // pattern:
2121 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2122 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002123 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002124 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2125 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002126 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2127 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002128 UpperBits).getValue(1);
2129 }
2130 break;
2131 }
2132 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2133 // For the 64 bit multiply
2134 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2135 if (IsSigned) {
2136 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2137 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002138 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002139 // It is important that LowerBits is last, otherwise the arithmetic
2140 // shift will not be folded into the compare (SUBS).
2141 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2142 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2143 .getValue(1);
2144 } else {
2145 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2146 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2147 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002148 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2149 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002150 UpperBits).getValue(1);
2151 }
2152 break;
2153 }
2154 } // switch (...)
2155
2156 if (Opc) {
2157 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2158
2159 // Emit the AArch64 operation with overflow check.
2160 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2161 Overflow = Value.getValue(1);
2162 }
2163 return std::make_pair(Value, Overflow);
2164}
2165
2166SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2167 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002168 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002169 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002170}
2171
Amara Emerson24ca39c2017-10-09 15:15:09 +00002172// Returns true if the given Op is the overflow flag result of an overflow
2173// intrinsic operation.
2174static bool isOverflowIntrOpRes(SDValue Op) {
2175 unsigned Opc = Op.getOpcode();
2176 return (Op.getResNo() == 1 &&
2177 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2178 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2179}
2180
Tim Northover3b0846e2014-05-24 12:50:23 +00002181static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2182 SDValue Sel = Op.getOperand(0);
2183 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002184 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002185
Amara Emerson24ca39c2017-10-09 15:15:09 +00002186 // If the operand is an overflow checking operation, invert the condition
2187 // code and kill the Not operation. I.e., transform:
2188 // (xor (overflow_op_bool, 1))
2189 // -->
2190 // (csel 1, 0, invert(cc), overflow_op_bool)
2191 // ... which later gets transformed to just a cset instruction with an
2192 // inverted condition code, rather than a cset + eor sequence.
2193 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2194 // Only lower legal XALUO ops.
2195 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2196 return SDValue();
2197
2198 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2199 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2200 AArch64CC::CondCode CC;
2201 SDValue Value, Overflow;
2202 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2203 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2204 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2205 CCVal, Overflow);
2206 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002207 // If neither operand is a SELECT_CC, give up.
2208 if (Sel.getOpcode() != ISD::SELECT_CC)
2209 std::swap(Sel, Other);
2210 if (Sel.getOpcode() != ISD::SELECT_CC)
2211 return Op;
2212
2213 // The folding we want to perform is:
2214 // (xor x, (select_cc a, b, cc, 0, -1) )
2215 // -->
2216 // (csel x, (xor x, -1), cc ...)
2217 //
2218 // The latter will get matched to a CSINV instruction.
2219
2220 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2221 SDValue LHS = Sel.getOperand(0);
2222 SDValue RHS = Sel.getOperand(1);
2223 SDValue TVal = Sel.getOperand(2);
2224 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002225
2226 // FIXME: This could be generalized to non-integer comparisons.
2227 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2228 return Op;
2229
2230 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2231 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2232
Eric Christopher572e03a2015-06-19 01:53:21 +00002233 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002234 if (!CFVal || !CTVal)
2235 return Op;
2236
2237 // We can commute the SELECT_CC by inverting the condition. This
2238 // might be needed to make this fit into a CSINV pattern.
2239 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2240 std::swap(TVal, FVal);
2241 std::swap(CTVal, CFVal);
2242 CC = ISD::getSetCCInverse(CC, true);
2243 }
2244
2245 // If the constants line up, perform the transform!
2246 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2247 SDValue CCVal;
2248 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2249
2250 FVal = Other;
2251 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002252 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002253
2254 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2255 CCVal, Cmp);
2256 }
2257
2258 return Op;
2259}
2260
2261static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2262 EVT VT = Op.getValueType();
2263
2264 // Let legalize expand this if it isn't a legal type yet.
2265 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2266 return SDValue();
2267
2268 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2269
2270 unsigned Opc;
2271 bool ExtraOp = false;
2272 switch (Op.getOpcode()) {
2273 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002274 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002275 case ISD::ADDC:
2276 Opc = AArch64ISD::ADDS;
2277 break;
2278 case ISD::SUBC:
2279 Opc = AArch64ISD::SUBS;
2280 break;
2281 case ISD::ADDE:
2282 Opc = AArch64ISD::ADCS;
2283 ExtraOp = true;
2284 break;
2285 case ISD::SUBE:
2286 Opc = AArch64ISD::SBCS;
2287 ExtraOp = true;
2288 break;
2289 }
2290
2291 if (!ExtraOp)
2292 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2293 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2294 Op.getOperand(2));
2295}
2296
2297static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2298 // Let legalize expand this if it isn't a legal type yet.
2299 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2300 return SDValue();
2301
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002302 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002303 AArch64CC::CondCode CC;
2304 // The actual operation that sets the overflow or carry flag.
2305 SDValue Value, Overflow;
2306 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2307
2308 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002309 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2310 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002311
2312 // We use an inverted condition, because the conditional select is inverted
2313 // too. This will allow it to be selected to a single instruction:
2314 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002315 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2316 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002317 CCVal, Overflow);
2318
2319 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002320 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002321}
2322
2323// Prefetch operands are:
2324// 1: Address to prefetch
2325// 2: bool isWrite
2326// 3: int locality (0 = no locality ... 3 = extreme locality)
2327// 4: bool isDataCache
2328static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2329 SDLoc DL(Op);
2330 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2331 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002332 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002333
2334 bool IsStream = !Locality;
2335 // When the locality number is set
2336 if (Locality) {
2337 // The front-end should have filtered out the out-of-range values
2338 assert(Locality <= 3 && "Prefetch locality out-of-range");
2339 // The locality degree is the opposite of the cache speed.
2340 // Put the number the other way around.
2341 // The encoding starts at 0 for level 1
2342 Locality = 3 - Locality;
2343 }
2344
2345 // built the mask value encoding the expected behavior.
2346 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002347 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002348 (Locality << 1) | // Cache level bits
2349 (unsigned)IsStream; // Stream bit
2350 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002351 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002352}
2353
2354SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2355 SelectionDAG &DAG) const {
2356 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2357
2358 RTLIB::Libcall LC;
2359 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2360
2361 return LowerF128Call(Op, DAG, LC);
2362}
2363
2364SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2365 SelectionDAG &DAG) const {
2366 if (Op.getOperand(0).getValueType() != MVT::f128) {
2367 // It's legal except when f128 is involved
2368 return Op;
2369 }
2370
2371 RTLIB::Libcall LC;
2372 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2373
2374 // FP_ROUND node has a second operand indicating whether it is known to be
2375 // precise. That doesn't take part in the LibCall so we can't directly use
2376 // LowerF128Call.
2377 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002378 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2379 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002380}
2381
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002382SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2383 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002384 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2385 // Any additional optimization in this function should be recorded
2386 // in the cost tables.
2387 EVT InVT = Op.getOperand(0).getValueType();
2388 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002389 unsigned NumElts = InVT.getVectorNumElements();
2390
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002391 // f16 conversions are promoted to f32 when full fp16 is not supported.
2392 if (InVT.getVectorElementType() == MVT::f16 &&
2393 !Subtarget->hasFullFP16()) {
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002394 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2395 SDLoc dl(Op);
2396 return DAG.getNode(
2397 Op.getOpcode(), dl, Op.getValueType(),
2398 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2399 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002400
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002401 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002402 SDLoc dl(Op);
2403 SDValue Cv =
2404 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2405 Op.getOperand(0));
2406 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002407 }
2408
2409 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002410 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002411 MVT ExtVT =
2412 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2413 VT.getVectorNumElements());
2414 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002415 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2416 }
2417
2418 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002419 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002420}
2421
2422SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2423 SelectionDAG &DAG) const {
2424 if (Op.getOperand(0).getValueType().isVector())
2425 return LowerVectorFP_TO_INT(Op, DAG);
2426
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002427 // f16 conversions are promoted to f32 when full fp16 is not supported.
2428 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2429 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002430 SDLoc dl(Op);
2431 return DAG.getNode(
2432 Op.getOpcode(), dl, Op.getValueType(),
2433 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2434 }
2435
Tim Northover3b0846e2014-05-24 12:50:23 +00002436 if (Op.getOperand(0).getValueType() != MVT::f128) {
2437 // It's legal except when f128 is involved
2438 return Op;
2439 }
2440
2441 RTLIB::Libcall LC;
2442 if (Op.getOpcode() == ISD::FP_TO_SINT)
2443 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2444 else
2445 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2446
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002447 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002448 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002449}
2450
2451static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2452 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2453 // Any additional optimization in this function should be recorded
2454 // in the cost tables.
2455 EVT VT = Op.getValueType();
2456 SDLoc dl(Op);
2457 SDValue In = Op.getOperand(0);
2458 EVT InVT = In.getValueType();
2459
Tim Northoveref0d7602014-06-15 09:27:06 +00002460 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2461 MVT CastVT =
2462 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2463 InVT.getVectorNumElements());
2464 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002465 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002466 }
2467
Tim Northoveref0d7602014-06-15 09:27:06 +00002468 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2469 unsigned CastOpc =
2470 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2471 EVT CastVT = VT.changeVectorElementTypeToInteger();
2472 In = DAG.getNode(CastOpc, dl, CastVT, In);
2473 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002474 }
2475
Tim Northoveref0d7602014-06-15 09:27:06 +00002476 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002477}
2478
2479SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2480 SelectionDAG &DAG) const {
2481 if (Op.getValueType().isVector())
2482 return LowerVectorINT_TO_FP(Op, DAG);
2483
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002484 // f16 conversions are promoted to f32 when full fp16 is not supported.
2485 if (Op.getValueType() == MVT::f16 &&
2486 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002487 SDLoc dl(Op);
2488 return DAG.getNode(
2489 ISD::FP_ROUND, dl, MVT::f16,
2490 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002491 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002492 }
2493
Tim Northover3b0846e2014-05-24 12:50:23 +00002494 // i128 conversions are libcalls.
2495 if (Op.getOperand(0).getValueType() == MVT::i128)
2496 return SDValue();
2497
2498 // Other conversions are legal, unless it's to the completely software-based
2499 // fp128.
2500 if (Op.getValueType() != MVT::f128)
2501 return Op;
2502
2503 RTLIB::Libcall LC;
2504 if (Op.getOpcode() == ISD::SINT_TO_FP)
2505 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2506 else
2507 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2508
2509 return LowerF128Call(Op, DAG, LC);
2510}
2511
2512SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2513 SelectionDAG &DAG) const {
2514 // For iOS, we want to call an alternative entry point: __sincos_stret,
2515 // which returns the values in two S / D registers.
2516 SDLoc dl(Op);
2517 SDValue Arg = Op.getOperand(0);
2518 EVT ArgVT = Arg.getValueType();
2519 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2520
2521 ArgListTy Args;
2522 ArgListEntry Entry;
2523
2524 Entry.Node = Arg;
2525 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002526 Entry.IsSExt = false;
2527 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002528 Args.push_back(Entry);
2529
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002530 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2531 : RTLIB::SINCOS_STRET_F32;
2532 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002533 SDValue Callee =
2534 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002535
Serge Gueltone38003f2017-05-09 19:31:13 +00002536 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002537 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002538 CLI.setDebugLoc(dl)
2539 .setChain(DAG.getEntryNode())
2540 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002541
2542 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2543 return CallResult.first;
2544}
2545
Tim Northoverf8bfe212014-07-18 13:07:05 +00002546static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2547 if (Op.getValueType() != MVT::f16)
2548 return SDValue();
2549
2550 assert(Op.getOperand(0).getValueType() == MVT::i16);
2551 SDLoc DL(Op);
2552
2553 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2554 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2555 return SDValue(
2556 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002557 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002558 0);
2559}
2560
Chad Rosierd9d0f862014-10-08 02:31:24 +00002561static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2562 if (OrigVT.getSizeInBits() >= 64)
2563 return OrigVT;
2564
2565 assert(OrigVT.isSimple() && "Expecting a simple value type");
2566
2567 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2568 switch (OrigSimpleTy) {
2569 default: llvm_unreachable("Unexpected Vector Type");
2570 case MVT::v2i8:
2571 case MVT::v2i16:
2572 return MVT::v2i32;
2573 case MVT::v4i8:
2574 return MVT::v4i16;
2575 }
2576}
2577
2578static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2579 const EVT &OrigTy,
2580 const EVT &ExtTy,
2581 unsigned ExtOpcode) {
2582 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2583 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2584 // 64-bits we need to insert a new extension so that it will be 64-bits.
2585 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2586 if (OrigTy.getSizeInBits() >= 64)
2587 return N;
2588
2589 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2590 EVT NewVT = getExtensionTo64Bits(OrigTy);
2591
2592 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2593}
2594
2595static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2596 bool isSigned) {
2597 EVT VT = N->getValueType(0);
2598
2599 if (N->getOpcode() != ISD::BUILD_VECTOR)
2600 return false;
2601
Pete Cooper3af9a252015-06-26 18:17:36 +00002602 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002604 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002605 unsigned HalfSize = EltSize / 2;
2606 if (isSigned) {
2607 if (!isIntN(HalfSize, C->getSExtValue()))
2608 return false;
2609 } else {
2610 if (!isUIntN(HalfSize, C->getZExtValue()))
2611 return false;
2612 }
2613 continue;
2614 }
2615 return false;
2616 }
2617
2618 return true;
2619}
2620
2621static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2622 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2623 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2624 N->getOperand(0)->getValueType(0),
2625 N->getValueType(0),
2626 N->getOpcode());
2627
2628 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2629 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002630 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002631 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002632 unsigned NumElts = VT.getVectorNumElements();
2633 MVT TruncVT = MVT::getIntegerVT(EltSize);
2634 SmallVector<SDValue, 8> Ops;
2635 for (unsigned i = 0; i != NumElts; ++i) {
2636 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2637 const APInt &CInt = C->getAPIntValue();
2638 // Element types smaller than 32 bits are not legal, so use i32 elements.
2639 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002640 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002641 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002642 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002643}
2644
2645static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002646 return N->getOpcode() == ISD::SIGN_EXTEND ||
2647 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002648}
2649
2650static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002651 return N->getOpcode() == ISD::ZERO_EXTEND ||
2652 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002653}
2654
2655static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2656 unsigned Opcode = N->getOpcode();
2657 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2658 SDNode *N0 = N->getOperand(0).getNode();
2659 SDNode *N1 = N->getOperand(1).getNode();
2660 return N0->hasOneUse() && N1->hasOneUse() &&
2661 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2662 }
2663 return false;
2664}
2665
2666static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2667 unsigned Opcode = N->getOpcode();
2668 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2669 SDNode *N0 = N->getOperand(0).getNode();
2670 SDNode *N1 = N->getOperand(1).getNode();
2671 return N0->hasOneUse() && N1->hasOneUse() &&
2672 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2673 }
2674 return false;
2675}
2676
Tim Northover70666e72018-06-20 12:09:01 +00002677SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2678 SelectionDAG &DAG) const {
2679 // The rounding mode is in bits 23:22 of the FPSCR.
2680 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2681 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2682 // so that the shift + and get folded into a bitfield extract.
2683 SDLoc dl(Op);
2684
2685 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2686 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2687 MVT::i64));
2688 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2689 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2690 DAG.getConstant(1U << 22, dl, MVT::i32));
2691 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2692 DAG.getConstant(22, dl, MVT::i32));
2693 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2694 DAG.getConstant(3, dl, MVT::i32));
2695}
2696
Chad Rosierd9d0f862014-10-08 02:31:24 +00002697static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2698 // Multiplications are only custom-lowered for 128-bit vectors so that
2699 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2700 EVT VT = Op.getValueType();
2701 assert(VT.is128BitVector() && VT.isInteger() &&
2702 "unexpected type for custom-lowering ISD::MUL");
2703 SDNode *N0 = Op.getOperand(0).getNode();
2704 SDNode *N1 = Op.getOperand(1).getNode();
2705 unsigned NewOpc = 0;
2706 bool isMLA = false;
2707 bool isN0SExt = isSignExtended(N0, DAG);
2708 bool isN1SExt = isSignExtended(N1, DAG);
2709 if (isN0SExt && isN1SExt)
2710 NewOpc = AArch64ISD::SMULL;
2711 else {
2712 bool isN0ZExt = isZeroExtended(N0, DAG);
2713 bool isN1ZExt = isZeroExtended(N1, DAG);
2714 if (isN0ZExt && isN1ZExt)
2715 NewOpc = AArch64ISD::UMULL;
2716 else if (isN1SExt || isN1ZExt) {
2717 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2718 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2719 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2720 NewOpc = AArch64ISD::SMULL;
2721 isMLA = true;
2722 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2723 NewOpc = AArch64ISD::UMULL;
2724 isMLA = true;
2725 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2726 std::swap(N0, N1);
2727 NewOpc = AArch64ISD::UMULL;
2728 isMLA = true;
2729 }
2730 }
2731
2732 if (!NewOpc) {
2733 if (VT == MVT::v2i64)
2734 // Fall through to expand this. It is not legal.
2735 return SDValue();
2736 else
2737 // Other vector multiplications are legal.
2738 return Op;
2739 }
2740 }
2741
2742 // Legalize to a S/UMULL instruction
2743 SDLoc DL(Op);
2744 SDValue Op0;
2745 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2746 if (!isMLA) {
2747 Op0 = skipExtensionForVectorMULL(N0, DAG);
2748 assert(Op0.getValueType().is64BitVector() &&
2749 Op1.getValueType().is64BitVector() &&
2750 "unexpected types for extended operands to VMULL");
2751 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2752 }
2753 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2754 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2755 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2756 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2757 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2758 EVT Op1VT = Op1.getValueType();
2759 return DAG.getNode(N0->getOpcode(), DL, VT,
2760 DAG.getNode(NewOpc, DL, VT,
2761 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2762 DAG.getNode(NewOpc, DL, VT,
2763 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2764}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002765
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002766SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2767 SelectionDAG &DAG) const {
2768 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2769 SDLoc dl(Op);
2770 switch (IntNo) {
2771 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002772 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002773 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2774 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2775 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002776 case Intrinsic::aarch64_neon_abs: {
2777 EVT Ty = Op.getValueType();
2778 if (Ty == MVT::i64) {
2779 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2780 Op.getOperand(1));
2781 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2782 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2783 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2784 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2785 } else {
2786 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2787 }
2788 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002789 case Intrinsic::aarch64_neon_smax:
2790 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2791 Op.getOperand(1), Op.getOperand(2));
2792 case Intrinsic::aarch64_neon_umax:
2793 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2794 Op.getOperand(1), Op.getOperand(2));
2795 case Intrinsic::aarch64_neon_smin:
2796 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2797 Op.getOperand(1), Op.getOperand(2));
2798 case Intrinsic::aarch64_neon_umin:
2799 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2800 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002801
2802 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002803 const auto &MF = DAG.getMachineFunction();
2804 const auto *RegInfo = Subtarget->getRegisterInfo();
2805 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002806 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2807 Op.getSimpleValueType());
2808 }
2809
2810 case Intrinsic::eh_recoverfp: {
2811 // FIXME: This needs to be implemented to correctly handle highly aligned
2812 // stack objects. For now we simply return the incoming FP. Refer D53541
2813 // for more details.
2814 SDValue FnOp = Op.getOperand(1);
2815 SDValue IncomingFPOp = Op.getOperand(2);
2816 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2817 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2818 if (!Fn)
2819 report_fatal_error(
2820 "llvm.eh.recoverfp must take a function as the first argument");
2821 return IncomingFPOp;
2822 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002823 }
2824}
2825
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002826// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2827static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2828 EVT VT, EVT MemVT,
2829 SelectionDAG &DAG) {
2830 assert(VT.isVector() && "VT should be a vector type");
2831 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2832
2833 SDValue Value = ST->getValue();
2834
2835 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2836 // the word lane which represent the v4i8 subvector. It optimizes the store
2837 // to:
2838 //
2839 // xtn v0.8b, v0.8h
2840 // str s0, [x0]
2841
2842 SDValue Undef = DAG.getUNDEF(MVT::i16);
2843 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2844 {Undef, Undef, Undef, Undef});
2845
2846 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2847 Value, UndefVec);
2848 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2849
2850 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2851 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2852 Trunc, DAG.getConstant(0, DL, MVT::i64));
2853
2854 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2855 ST->getBasePtr(), ST->getMemOperand());
2856}
2857
2858// Custom lowering for any store, vector or scalar and/or default or with
2859// a truncate operations. Currently only custom lower truncate operation
2860// from vector v4i16 to v4i8.
2861SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2862 SelectionDAG &DAG) const {
2863 SDLoc Dl(Op);
2864 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2865 assert (StoreNode && "Can only custom lower store nodes");
2866
2867 SDValue Value = StoreNode->getValue();
2868
2869 EVT VT = Value.getValueType();
2870 EVT MemVT = StoreNode->getMemoryVT();
2871
2872 assert (VT.isVector() && "Can only custom lower vector store types");
2873
2874 unsigned AS = StoreNode->getAddressSpace();
2875 unsigned Align = StoreNode->getAlignment();
2876 if (Align < MemVT.getStoreSize() &&
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00002877 !allowsMisalignedMemoryAccesses(
2878 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002879 return scalarizeVectorStore(StoreNode, DAG);
2880 }
2881
2882 if (StoreNode->isTruncatingStore()) {
2883 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2884 }
2885
2886 return SDValue();
2887}
2888
Tim Northover3b0846e2014-05-24 12:50:23 +00002889SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2890 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002891 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2892 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002893
Tim Northover3b0846e2014-05-24 12:50:23 +00002894 switch (Op.getOpcode()) {
2895 default:
2896 llvm_unreachable("unimplemented operand");
2897 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002898 case ISD::BITCAST:
2899 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002900 case ISD::GlobalAddress:
2901 return LowerGlobalAddress(Op, DAG);
2902 case ISD::GlobalTLSAddress:
2903 return LowerGlobalTLSAddress(Op, DAG);
2904 case ISD::SETCC:
2905 return LowerSETCC(Op, DAG);
2906 case ISD::BR_CC:
2907 return LowerBR_CC(Op, DAG);
2908 case ISD::SELECT:
2909 return LowerSELECT(Op, DAG);
2910 case ISD::SELECT_CC:
2911 return LowerSELECT_CC(Op, DAG);
2912 case ISD::JumpTable:
2913 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002914 case ISD::BR_JT:
2915 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002916 case ISD::ConstantPool:
2917 return LowerConstantPool(Op, DAG);
2918 case ISD::BlockAddress:
2919 return LowerBlockAddress(Op, DAG);
2920 case ISD::VASTART:
2921 return LowerVASTART(Op, DAG);
2922 case ISD::VACOPY:
2923 return LowerVACOPY(Op, DAG);
2924 case ISD::VAARG:
2925 return LowerVAARG(Op, DAG);
2926 case ISD::ADDC:
2927 case ISD::ADDE:
2928 case ISD::SUBC:
2929 case ISD::SUBE:
2930 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2931 case ISD::SADDO:
2932 case ISD::UADDO:
2933 case ISD::SSUBO:
2934 case ISD::USUBO:
2935 case ISD::SMULO:
2936 case ISD::UMULO:
2937 return LowerXALUO(Op, DAG);
2938 case ISD::FADD:
2939 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2940 case ISD::FSUB:
2941 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2942 case ISD::FMUL:
2943 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2944 case ISD::FDIV:
2945 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2946 case ISD::FP_ROUND:
2947 return LowerFP_ROUND(Op, DAG);
2948 case ISD::FP_EXTEND:
2949 return LowerFP_EXTEND(Op, DAG);
2950 case ISD::FRAMEADDR:
2951 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002952 case ISD::SPONENTRY:
2953 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002954 case ISD::RETURNADDR:
2955 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002956 case ISD::ADDROFRETURNADDR:
2957 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002958 case ISD::INSERT_VECTOR_ELT:
2959 return LowerINSERT_VECTOR_ELT(Op, DAG);
2960 case ISD::EXTRACT_VECTOR_ELT:
2961 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2962 case ISD::BUILD_VECTOR:
2963 return LowerBUILD_VECTOR(Op, DAG);
2964 case ISD::VECTOR_SHUFFLE:
2965 return LowerVECTOR_SHUFFLE(Op, DAG);
2966 case ISD::EXTRACT_SUBVECTOR:
2967 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2968 case ISD::SRA:
2969 case ISD::SRL:
2970 case ISD::SHL:
2971 return LowerVectorSRA_SRL_SHL(Op, DAG);
2972 case ISD::SHL_PARTS:
2973 return LowerShiftLeftParts(Op, DAG);
2974 case ISD::SRL_PARTS:
2975 case ISD::SRA_PARTS:
2976 return LowerShiftRightParts(Op, DAG);
2977 case ISD::CTPOP:
2978 return LowerCTPOP(Op, DAG);
2979 case ISD::FCOPYSIGN:
2980 return LowerFCOPYSIGN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002981 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002982 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002983 case ISD::XOR:
2984 return LowerXOR(Op, DAG);
2985 case ISD::PREFETCH:
2986 return LowerPREFETCH(Op, DAG);
2987 case ISD::SINT_TO_FP:
2988 case ISD::UINT_TO_FP:
2989 return LowerINT_TO_FP(Op, DAG);
2990 case ISD::FP_TO_SINT:
2991 case ISD::FP_TO_UINT:
2992 return LowerFP_TO_INT(Op, DAG);
2993 case ISD::FSINCOS:
2994 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002995 case ISD::FLT_ROUNDS_:
2996 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002997 case ISD::MUL:
2998 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002999 case ISD::INTRINSIC_WO_CHAIN:
3000 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00003001 case ISD::STORE:
3002 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00003003 case ISD::VECREDUCE_ADD:
3004 case ISD::VECREDUCE_SMAX:
3005 case ISD::VECREDUCE_SMIN:
3006 case ISD::VECREDUCE_UMAX:
3007 case ISD::VECREDUCE_UMIN:
3008 case ISD::VECREDUCE_FMAX:
3009 case ISD::VECREDUCE_FMIN:
3010 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00003011 case ISD::ATOMIC_LOAD_SUB:
3012 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00003013 case ISD::ATOMIC_LOAD_AND:
3014 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00003015 case ISD::DYNAMIC_STACKALLOC:
3016 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003017 }
3018}
3019
Tim Northover3b0846e2014-05-24 12:50:23 +00003020//===----------------------------------------------------------------------===//
3021// Calling Convention Implementation
3022//===----------------------------------------------------------------------===//
3023
Robin Morisset039781e2014-08-29 21:53:01 +00003024/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00003025CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3026 bool IsVarArg) const {
3027 switch (CC) {
3028 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00003029 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00003030 case CallingConv::WebKit_JS:
3031 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00003032 case CallingConv::GHC:
3033 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00003034 case CallingConv::C:
3035 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00003036 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00003037 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00003038 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00003039 if (Subtarget->isTargetWindows() && IsVarArg)
3040 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00003041 if (!Subtarget->isTargetDarwin())
3042 return CC_AArch64_AAPCS;
3043 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00003044 case CallingConv::Win64:
3045 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00003046 case CallingConv::AArch64_VectorCall:
3047 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00003048 }
3049}
3050
Tim Northover406024a2016-08-10 21:44:01 +00003051CCAssignFn *
3052AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3053 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3054 : RetCC_AArch64_AAPCS;
3055}
3056
Tim Northover3b0846e2014-05-24 12:50:23 +00003057SDValue AArch64TargetLowering::LowerFormalArguments(
3058 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003059 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3060 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003061 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003062 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003063 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003064
3065 // Assign locations to all of the incoming arguments.
3066 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003067 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3068 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003069
3070 // At this point, Ins[].VT may already be promoted to i32. To correctly
3071 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3072 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3073 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3074 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3075 // LocVT.
3076 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003077 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003078 unsigned CurArgIdx = 0;
3079 for (unsigned i = 0; i != NumArgs; ++i) {
3080 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003081 if (Ins[i].isOrigArg()) {
3082 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3083 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003084
Andrew Trick05938a52015-02-16 18:10:47 +00003085 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003086 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3087 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003088 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3089 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3090 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3091 ValVT = MVT::i8;
3092 else if (ActualMVT == MVT::i16)
3093 ValVT = MVT::i16;
3094 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003095 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3096 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003097 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003098 assert(!Res && "Call operand has unhandled type");
3099 (void)Res;
3100 }
3101 assert(ArgLocs.size() == Ins.size());
3102 SmallVector<SDValue, 16> ArgValues;
3103 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3104 CCValAssign &VA = ArgLocs[i];
3105
3106 if (Ins[i].Flags.isByVal()) {
3107 // Byval is used for HFAs in the PCS, but the system should work in a
3108 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003109 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003110 int Size = Ins[i].Flags.getByValSize();
3111 unsigned NumRegs = (Size + 7) / 8;
3112
3113 // FIXME: This works on big-endian for composite byvals, which are the common
3114 // case. It should also work for fundamental types too.
3115 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003116 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003117 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003118 InVals.push_back(FrameIdxN);
3119
3120 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003121 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003122
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003123 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003124 // Arguments stored in registers.
3125 EVT RegVT = VA.getLocVT();
3126
3127 SDValue ArgValue;
3128 const TargetRegisterClass *RC;
3129
3130 if (RegVT == MVT::i32)
3131 RC = &AArch64::GPR32RegClass;
3132 else if (RegVT == MVT::i64)
3133 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003134 else if (RegVT == MVT::f16)
3135 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003136 else if (RegVT == MVT::f32)
3137 RC = &AArch64::FPR32RegClass;
3138 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3139 RC = &AArch64::FPR64RegClass;
3140 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3141 RC = &AArch64::FPR128RegClass;
3142 else
3143 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3144
3145 // Transform the arguments in physical registers into virtual ones.
3146 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3147 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3148
3149 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3150 // to 64 bits. Insert an assert[sz]ext to capture this, then
3151 // truncate to the right size.
3152 switch (VA.getLocInfo()) {
3153 default:
3154 llvm_unreachable("Unknown loc info!");
3155 case CCValAssign::Full:
3156 break;
3157 case CCValAssign::BCvt:
3158 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3159 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003160 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003161 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003162 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003163 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3164 // nodes after our lowering.
3165 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003166 break;
3167 }
3168
3169 InVals.push_back(ArgValue);
3170
3171 } else { // VA.isRegLoc()
3172 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3173 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003174 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003175
3176 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003177 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3178 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003179 BEAlign = 8 - ArgSize;
3180
Matthias Braun941a7052016-07-28 18:40:00 +00003181 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003182
3183 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003184 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003185 SDValue ArgValue;
3186
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003187 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003188 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003189 MVT MemVT = VA.getValVT();
3190
Tim Northover47e003c2014-05-26 17:21:53 +00003191 switch (VA.getLocInfo()) {
3192 default:
3193 break;
Tim Northover6890add2014-06-03 13:54:53 +00003194 case CCValAssign::BCvt:
3195 MemVT = VA.getLocVT();
3196 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003197 case CCValAssign::SExt:
3198 ExtType = ISD::SEXTLOAD;
3199 break;
3200 case CCValAssign::ZExt:
3201 ExtType = ISD::ZEXTLOAD;
3202 break;
3203 case CCValAssign::AExt:
3204 ExtType = ISD::EXTLOAD;
3205 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003206 }
3207
Alex Lorenze40c8a22015-08-11 23:09:45 +00003208 ArgValue = DAG.getExtLoad(
3209 ExtType, DL, VA.getLocVT(), Chain, FIN,
3210 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003211 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003212
Tim Northover3b0846e2014-05-24 12:50:23 +00003213 InVals.push_back(ArgValue);
3214 }
3215 }
3216
3217 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003218 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003219 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003220 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003221 // The AAPCS variadic function ABI is identical to the non-variadic
3222 // one. As a result there may be more arguments in registers and we should
3223 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003224 // Win64 variadic functions also pass arguments in registers, but all float
3225 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003226 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3227 }
3228
Tim Northover3b0846e2014-05-24 12:50:23 +00003229 // This will point to the next argument passed via stack.
3230 unsigned StackOffset = CCInfo.getNextStackOffset();
3231 // We currently pass all varargs at 8-byte alignment.
3232 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003233 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003234
3235 if (MFI.hasMustTailInVarArgFunc()) {
3236 SmallVector<MVT, 2> RegParmTypes;
3237 RegParmTypes.push_back(MVT::i64);
3238 RegParmTypes.push_back(MVT::f128);
3239 // Compute the set of forwarded registers. The rest are scratch.
3240 SmallVectorImpl<ForwardedRegister> &Forwards =
3241 FuncInfo->getForwardedMustTailRegParms();
3242 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3243 CC_AArch64_AAPCS);
Reid Klecknerb7a78c72019-05-24 01:27:20 +00003244
3245 // Conservatively forward X8, since it might be used for aggregate return.
3246 if (!CCInfo.isAllocated(AArch64::X8)) {
3247 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3248 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3249 }
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003250 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003251 }
3252
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003253 // On Windows, InReg pointers must be returned, so record the pointer in a
3254 // virtual register at the start of the function so it can be returned in the
3255 // epilogue.
3256 if (IsWin64) {
3257 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3258 if (Ins[I].Flags.isInReg()) {
3259 assert(!FuncInfo->getSRetReturnReg());
3260
3261 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3262 unsigned Reg =
3263 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3264 FuncInfo->setSRetReturnReg(Reg);
3265
3266 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3267 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3268 break;
3269 }
3270 }
3271 }
3272
Tim Northover3b0846e2014-05-24 12:50:23 +00003273 unsigned StackArgSize = CCInfo.getNextStackOffset();
3274 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3275 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3276 // This is a non-standard ABI so by fiat I say we're allowed to make full
3277 // use of the stack area to be popped, which must be aligned to 16 bytes in
3278 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003279 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003280
3281 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3282 // a multiple of 16.
3283 FuncInfo->setArgumentStackToRestore(StackArgSize);
3284
3285 // This realignment carries over to the available bytes below. Our own
3286 // callers will guarantee the space is free by giving an aligned value to
3287 // CALLSEQ_START.
3288 }
3289 // Even if we're not expected to free up the space, it's useful to know how
3290 // much is there while considering tail calls (because we can reuse it).
3291 FuncInfo->setBytesInStackArgArea(StackArgSize);
3292
Tri Vo6c47c622018-09-22 22:17:50 +00003293 if (Subtarget->hasCustomCallingConv())
3294 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3295
Tim Northover3b0846e2014-05-24 12:50:23 +00003296 return Chain;
3297}
3298
3299void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003300 SelectionDAG &DAG,
3301 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003302 SDValue &Chain) const {
3303 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003304 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003305 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003306 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003307 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003308
3309 SmallVector<SDValue, 8> MemOps;
3310
3311 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3312 AArch64::X3, AArch64::X4, AArch64::X5,
3313 AArch64::X6, AArch64::X7 };
3314 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003315 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003316
3317 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3318 int GPRIdx = 0;
3319 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003320 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003321 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003322 if (GPRSaveSize & 15)
3323 // The extra size here, if triggered, will always be 8.
3324 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3325 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003326 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003327
Mehdi Amini44ede332015-07-09 02:09:04 +00003328 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003329
3330 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3331 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3332 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003333 SDValue Store = DAG.getStore(
3334 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003335 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003336 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3337 GPRIdx,
3338 (i - FirstVariadicGPR) * 8)
3339 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003340 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003341 FIN =
3342 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003343 }
3344 }
3345 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3346 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3347
Martin Storsjo2f24e932017-07-17 20:05:19 +00003348 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003349 static const MCPhysReg FPRArgRegs[] = {
3350 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3351 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3352 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003353 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003354
3355 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3356 int FPRIdx = 0;
3357 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003358 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003359
Mehdi Amini44ede332015-07-09 02:09:04 +00003360 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003361
3362 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3363 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3364 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3365
Alex Lorenze40c8a22015-08-11 23:09:45 +00003366 SDValue Store = DAG.getStore(
3367 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003368 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003369 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003370 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3371 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003372 }
3373 }
3374 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3375 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3376 }
3377
3378 if (!MemOps.empty()) {
3379 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3380 }
3381}
3382
3383/// LowerCallResult - Lower the result values of a call into the
3384/// appropriate copies out of appropriate physical registers.
3385SDValue AArch64TargetLowering::LowerCallResult(
3386 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003387 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3388 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003389 SDValue ThisVal) const {
3390 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3391 ? RetCC_AArch64_WebKit_JS
3392 : RetCC_AArch64_AAPCS;
3393 // Assign locations to each value returned by this call.
3394 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003395 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3396 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003397 CCInfo.AnalyzeCallResult(Ins, RetCC);
3398
3399 // Copy all of the result registers out of their specified physreg.
3400 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3401 CCValAssign VA = RVLocs[i];
3402
3403 // Pass 'this' value directly from the argument to return value, to avoid
3404 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003405 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003406 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3407 "unexpected return calling convention register assignment");
3408 InVals.push_back(ThisVal);
3409 continue;
3410 }
3411
3412 SDValue Val =
3413 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3414 Chain = Val.getValue(1);
3415 InFlag = Val.getValue(2);
3416
3417 switch (VA.getLocInfo()) {
3418 default:
3419 llvm_unreachable("Unknown loc info!");
3420 case CCValAssign::Full:
3421 break;
3422 case CCValAssign::BCvt:
3423 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3424 break;
3425 }
3426
3427 InVals.push_back(Val);
3428 }
3429
3430 return Chain;
3431}
3432
Matthias Braun1af14142016-09-13 19:27:38 +00003433/// Return true if the calling convention is one that we can guarantee TCO for.
3434static bool canGuaranteeTCO(CallingConv::ID CC) {
3435 return CC == CallingConv::Fast;
3436}
3437
3438/// Return true if we might ever do TCO for calls with this calling convention.
3439static bool mayTailCallThisCC(CallingConv::ID CC) {
3440 switch (CC) {
3441 case CallingConv::C:
3442 case CallingConv::PreserveMost:
3443 case CallingConv::Swift:
3444 return true;
3445 default:
3446 return canGuaranteeTCO(CC);
3447 }
3448}
3449
Tim Northover3b0846e2014-05-24 12:50:23 +00003450bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3451 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003452 const SmallVectorImpl<ISD::OutputArg> &Outs,
3453 const SmallVectorImpl<SDValue> &OutVals,
3454 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003455 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003456 return false;
3457
Matthias Braun8d414362016-03-30 22:46:04 +00003458 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003459 const Function &CallerF = MF.getFunction();
3460 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003461 bool CCMatch = CallerCC == CalleeCC;
3462
3463 // Byval parameters hand the function a pointer directly into the stack area
3464 // we want to reuse during a tail call. Working around this *is* possible (see
3465 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003466 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3467 e = CallerF.arg_end();
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003468 i != e; ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003469 if (i->hasByValAttr())
3470 return false;
3471
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003472 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3473 // In this case, it is necessary to save/restore X0 in the callee. Tail
3474 // call opt interferes with this. So we disable tail call opt when the
3475 // caller has an argument with "inreg" attribute.
3476
3477 // FIXME: Check whether the callee also has an "inreg" argument.
3478 if (i->hasInRegAttr())
3479 return false;
3480 }
3481
Matthias Braun1af14142016-09-13 19:27:38 +00003482 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3483 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003484
Oliver Stannard12993dd2014-08-18 12:42:15 +00003485 // Externally-defined functions with weak linkage should not be
3486 // tail-called on AArch64 when the OS does not support dynamic
3487 // pre-emption of symbols, as the AAELF spec requires normal calls
3488 // to undefined weak functions to be replaced with a NOP or jump to the
3489 // next instruction. The behaviour of branch instructions in this
3490 // situation (as used for tail calls) is implementation-defined, so we
3491 // cannot rely on the linker replacing the tail call with a return.
3492 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3493 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003494 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003495 if (GV->hasExternalWeakLinkage() &&
3496 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003497 return false;
3498 }
3499
Tim Northover3b0846e2014-05-24 12:50:23 +00003500 // Now we search for cases where we can use a tail call without changing the
3501 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3502 // concept.
3503
3504 // I want anyone implementing a new calling convention to think long and hard
3505 // about this assert.
3506 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3507 "Unexpected variadic calling convention");
3508
Matthias Braun8d414362016-03-30 22:46:04 +00003509 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003510 if (isVarArg && !Outs.empty()) {
3511 // At least two cases here: if caller is fastcc then we can't have any
3512 // memory arguments (we'd be expected to clean up the stack afterwards). If
3513 // caller is C then we could potentially use its argument area.
3514
3515 // FIXME: for now we take the most conservative of these in both cases:
3516 // disallow all variadic memory operands.
3517 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003518 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003519
3520 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003521 for (const CCValAssign &ArgLoc : ArgLocs)
3522 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003523 return false;
3524 }
3525
Matthias Braun8d414362016-03-30 22:46:04 +00003526 // Check that the call results are passed in the same way.
3527 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3528 CCAssignFnForCall(CalleeCC, isVarArg),
3529 CCAssignFnForCall(CallerCC, isVarArg)))
3530 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003531 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003532 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3533 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003534 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003535 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003536 if (Subtarget->hasCustomCallingConv()) {
3537 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3538 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3539 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003540 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003541 return false;
3542 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003543
3544 // Nothing more to check if the callee is taking no arguments
3545 if (Outs.empty())
3546 return true;
3547
3548 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003549 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003550
3551 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3552
3553 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3554
Matthias Braun74a0bd32016-04-13 21:43:16 +00003555 // If the stack arguments for this call do not fit into our own save area then
3556 // the call cannot be made tail.
3557 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3558 return false;
3559
Matthias Braun46b0f032016-04-14 01:10:42 +00003560 const MachineRegisterInfo &MRI = MF.getRegInfo();
3561 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3562 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003563
3564 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003565}
3566
3567SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3568 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003569 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003570 int ClobberedFI) const {
3571 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003572 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3573 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003574
3575 // Include the original chain at the beginning of the list. When this is
3576 // used by target LowerCall hooks, this helps legalize find the
3577 // CALLSEQ_BEGIN node.
3578 ArgChains.push_back(Chain);
3579
3580 // Add a chain value for each stack argument corresponding
3581 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3582 UE = DAG.getEntryNode().getNode()->use_end();
3583 U != UE; ++U)
3584 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3585 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3586 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003587 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003588 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003589 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003590
3591 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3592 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3593 ArgChains.push_back(SDValue(L, 1));
3594 }
3595
3596 // Build a tokenfactor for all the chains.
3597 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3598}
3599
3600bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3601 bool TailCallOpt) const {
3602 return CallCC == CallingConv::Fast && TailCallOpt;
3603}
3604
Tim Northover3b0846e2014-05-24 12:50:23 +00003605/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3606/// and add input and output parameter nodes.
3607SDValue
3608AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3609 SmallVectorImpl<SDValue> &InVals) const {
3610 SelectionDAG &DAG = CLI.DAG;
3611 SDLoc &DL = CLI.DL;
3612 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3613 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3614 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3615 SDValue Chain = CLI.Chain;
3616 SDValue Callee = CLI.Callee;
3617 bool &IsTailCall = CLI.IsTailCall;
3618 CallingConv::ID CallConv = CLI.CallConv;
3619 bool IsVarArg = CLI.IsVarArg;
3620
3621 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003622 bool IsThisReturn = false;
3623
3624 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3625 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3626 bool IsSibCall = false;
3627
3628 if (IsTailCall) {
3629 // Check if it's really possible to do a tail call.
3630 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003631 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003632 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003633 report_fatal_error("failed to perform tail call elimination on a call "
3634 "site marked musttail");
3635
3636 // A sibling call is one where we're under the usual C ABI and not planning
3637 // to change that but can still do a tail call:
3638 if (!TailCallOpt && IsTailCall)
3639 IsSibCall = true;
3640
3641 if (IsTailCall)
3642 ++NumTailCalls;
3643 }
3644
3645 // Analyze operands of the call, assigning locations to each operand.
3646 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003647 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3648 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003649
3650 if (IsVarArg) {
3651 // Handle fixed and variable vector arguments differently.
3652 // Variable vector arguments always go into memory.
3653 unsigned NumArgs = Outs.size();
3654
3655 for (unsigned i = 0; i != NumArgs; ++i) {
3656 MVT ArgVT = Outs[i].VT;
3657 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3658 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3659 /*IsVarArg=*/ !Outs[i].IsFixed);
3660 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3661 assert(!Res && "Call operand has unhandled type");
3662 (void)Res;
3663 }
3664 } else {
3665 // At this point, Outs[].VT may already be promoted to i32. To correctly
3666 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3667 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3668 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3669 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3670 // LocVT.
3671 unsigned NumArgs = Outs.size();
3672 for (unsigned i = 0; i != NumArgs; ++i) {
3673 MVT ValVT = Outs[i].VT;
3674 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003675 EVT ActualVT = getValueType(DAG.getDataLayout(),
3676 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003677 /*AllowUnknown*/ true);
3678 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3679 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3680 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003681 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003682 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003683 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003684 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003685
3686 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003687 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003688 assert(!Res && "Call operand has unhandled type");
3689 (void)Res;
3690 }
3691 }
3692
3693 // Get a count of how many bytes are to be pushed on the stack.
3694 unsigned NumBytes = CCInfo.getNextStackOffset();
3695
3696 if (IsSibCall) {
3697 // Since we're not changing the ABI to make this a tail call, the memory
3698 // operands are already available in the caller's incoming argument space.
3699 NumBytes = 0;
3700 }
3701
3702 // FPDiff is the byte offset of the call's argument area from the callee's.
3703 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3704 // by this amount for a tail call. In a sibling call it must be 0 because the
3705 // caller will deallocate the entire stack and the callee still expects its
3706 // arguments to begin at SP+0. Completely unused for non-tail calls.
3707 int FPDiff = 0;
3708
3709 if (IsTailCall && !IsSibCall) {
3710 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3711
3712 // Since callee will pop argument stack as a tail call, we must keep the
3713 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003714 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003715
3716 // FPDiff will be negative if this tail call requires more space than we
3717 // would automatically have in our incoming argument space. Positive if we
3718 // can actually shrink the stack.
3719 FPDiff = NumReusableBytes - NumBytes;
3720
3721 // The stack pointer must be 16-byte aligned at all times it's used for a
3722 // memory operation, which in practice means at *all* times and in
3723 // particular across call boundaries. Therefore our own arguments started at
3724 // a 16-byte aligned SP and the delta applied for the tail call should
3725 // satisfy the same constraint.
3726 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3727 }
3728
3729 // Adjust the stack pointer for the new arguments...
3730 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003731 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003732 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003733
Mehdi Amini44ede332015-07-09 02:09:04 +00003734 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3735 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003736
3737 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3738 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003739 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003740
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003741 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3742 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3743 for (const auto &F : Forwards) {
3744 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3745 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3746 }
3747 }
3748
Tim Northover3b0846e2014-05-24 12:50:23 +00003749 // Walk the register/memloc assignments, inserting copies/loads.
3750 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3751 ++i, ++realArgIdx) {
3752 CCValAssign &VA = ArgLocs[i];
3753 SDValue Arg = OutVals[realArgIdx];
3754 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3755
3756 // Promote the value if needed.
3757 switch (VA.getLocInfo()) {
3758 default:
3759 llvm_unreachable("Unknown loc info!");
3760 case CCValAssign::Full:
3761 break;
3762 case CCValAssign::SExt:
3763 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3764 break;
3765 case CCValAssign::ZExt:
3766 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3767 break;
3768 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003769 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3770 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3771 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3772 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3773 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003774 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3775 break;
3776 case CCValAssign::BCvt:
3777 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3778 break;
3779 case CCValAssign::FPExt:
3780 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3781 break;
3782 }
3783
3784 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003785 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3786 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003787 assert(VA.getLocVT() == MVT::i64 &&
3788 "unexpected calling convention register assignment");
3789 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3790 "unexpected use of 'returned'");
3791 IsThisReturn = true;
3792 }
3793 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3794 } else {
3795 assert(VA.isMemLoc());
3796
3797 SDValue DstAddr;
3798 MachinePointerInfo DstInfo;
3799
3800 // FIXME: This works on big-endian for composite byvals, which are the
3801 // common case. It should also work for fundamental types too.
3802 uint32_t BEAlign = 0;
3803 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003804 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003805 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003806 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3807 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003808 if (OpSize < 8)
3809 BEAlign = 8 - OpSize;
3810 }
3811 unsigned LocMemOffset = VA.getLocMemOffset();
3812 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003813 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003814 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003815
3816 if (IsTailCall) {
3817 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003818 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003819
Mehdi Amini44ede332015-07-09 02:09:04 +00003820 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003821 DstInfo =
3822 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003823
3824 // Make sure any stack arguments overlapping with where we're storing
3825 // are loaded before this eventual operation. Otherwise they'll be
3826 // clobbered.
3827 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3828 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003829 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003830
Mehdi Amini44ede332015-07-09 02:09:04 +00003831 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003832 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3833 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003834 }
3835
3836 if (Outs[i].Flags.isByVal()) {
3837 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003838 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003839 SDValue Cpy = DAG.getMemcpy(
3840 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003841 /*isVol = */ false, /*AlwaysInline = */ false,
3842 /*isTailCall = */ false,
3843 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003844
3845 MemOpChains.push_back(Cpy);
3846 } else {
3847 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3848 // promoted to a legal register type i32, we should truncate Arg back to
3849 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003850 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3851 VA.getValVT() == MVT::i16)
3852 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003853
Justin Lebar9c375812016-07-15 18:27:10 +00003854 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003855 MemOpChains.push_back(Store);
3856 }
3857 }
3858 }
3859
3860 if (!MemOpChains.empty())
3861 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3862
3863 // Build a sequence of copy-to-reg nodes chained together with token chain
3864 // and flag operands which copy the outgoing args into the appropriate regs.
3865 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003866 for (auto &RegToPass : RegsToPass) {
3867 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3868 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003869 InFlag = Chain.getValue(1);
3870 }
3871
3872 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3873 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3874 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003875 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3876 auto GV = G->getGlobal();
3877 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3878 AArch64II::MO_GOT) {
3879 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3880 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003881 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3882 assert(Subtarget->isTargetWindows() &&
3883 "Windows is the only supported COFF target");
3884 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003885 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003886 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003887 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3888 }
3889 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3890 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3891 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003892 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003893 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3894 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003895 } else {
3896 const char *Sym = S->getSymbol();
3897 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003898 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003899 }
3900
3901 // We don't usually want to end the call-sequence here because we would tidy
3902 // the frame up *after* the call, however in the ABI-changing tail-call case
3903 // we've carefully laid out the parameters so that when sp is reset they'll be
3904 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003905 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003906 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3907 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003908 InFlag = Chain.getValue(1);
3909 }
3910
3911 std::vector<SDValue> Ops;
3912 Ops.push_back(Chain);
3913 Ops.push_back(Callee);
3914
3915 if (IsTailCall) {
3916 // Each tail call may have to adjust the stack by a different amount, so
3917 // this information must travel along with the operation for eventual
3918 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003919 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003920 }
3921
3922 // Add argument registers to the end of the list so that they are known live
3923 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003924 for (auto &RegToPass : RegsToPass)
3925 Ops.push_back(DAG.getRegister(RegToPass.first,
3926 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003927
3928 // Add a register mask operand representing the call-preserved registers.
3929 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003930 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003931 if (IsThisReturn) {
3932 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003933 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003934 if (!Mask) {
3935 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003936 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003937 }
3938 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003939 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003940
Tri Vo6c47c622018-09-22 22:17:50 +00003941 if (Subtarget->hasCustomCallingConv())
3942 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3943
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003944 if (TRI->isAnyArgRegReserved(MF))
3945 TRI->emitReservedArgRegCallError(MF);
3946
Tim Northover3b0846e2014-05-24 12:50:23 +00003947 assert(Mask && "Missing call preserved mask for calling convention");
3948 Ops.push_back(DAG.getRegisterMask(Mask));
3949
3950 if (InFlag.getNode())
3951 Ops.push_back(InFlag);
3952
3953 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3954
3955 // If we're doing a tall call, use a TC_RETURN here rather than an
3956 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003957 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003958 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003959 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003960 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003961
3962 // Returns a chain and a flag for retval copy to use.
3963 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3964 InFlag = Chain.getValue(1);
3965
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003966 uint64_t CalleePopBytes =
3967 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003968
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003969 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3970 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3971 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003972 if (!Ins.empty())
3973 InFlag = Chain.getValue(1);
3974
3975 // Handle result values, copying them out of physregs into vregs that we
3976 // return.
3977 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3978 InVals, IsThisReturn,
3979 IsThisReturn ? OutVals[0] : SDValue());
3980}
3981
3982bool AArch64TargetLowering::CanLowerReturn(
3983 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3984 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3985 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3986 ? RetCC_AArch64_WebKit_JS
3987 : RetCC_AArch64_AAPCS;
3988 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003989 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003990 return CCInfo.CheckReturn(Outs, RetCC);
3991}
3992
3993SDValue
3994AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3995 bool isVarArg,
3996 const SmallVectorImpl<ISD::OutputArg> &Outs,
3997 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003998 const SDLoc &DL, SelectionDAG &DAG) const {
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003999 auto &MF = DAG.getMachineFunction();
4000 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4001
Tim Northover3b0846e2014-05-24 12:50:23 +00004002 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4003 ? RetCC_AArch64_WebKit_JS
4004 : RetCC_AArch64_AAPCS;
4005 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00004006 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4007 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00004008 CCInfo.AnalyzeReturn(Outs, RetCC);
4009
4010 // Copy the result values into the output registers.
4011 SDValue Flag;
4012 SmallVector<SDValue, 4> RetOps(1, Chain);
4013 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4014 ++i, ++realRVLocIdx) {
4015 CCValAssign &VA = RVLocs[i];
4016 assert(VA.isRegLoc() && "Can only return in registers!");
4017 SDValue Arg = OutVals[realRVLocIdx];
4018
4019 switch (VA.getLocInfo()) {
4020 default:
4021 llvm_unreachable("Unknown loc info!");
4022 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00004023 if (Outs[i].ArgVT == MVT::i1) {
4024 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4025 // value. This is strictly redundant on Darwin (which uses "zeroext
4026 // i1"), but will be optimised out before ISel.
4027 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4028 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4029 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004030 break;
4031 case CCValAssign::BCvt:
4032 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4033 break;
4034 }
4035
4036 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
4037 Flag = Chain.getValue(1);
4038 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4039 }
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00004040
4041 // Windows AArch64 ABIs require that for returning structs by value we copy
4042 // the sret argument into X0 for the return.
4043 // We saved the argument into a virtual register in the entry block,
4044 // so now we copy the value out and into X0.
4045 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4046 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4047 getPointerTy(MF.getDataLayout()));
4048
4049 unsigned RetValReg = AArch64::X0;
4050 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4051 Flag = Chain.getValue(1);
4052
4053 RetOps.push_back(
4054 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4055 }
4056
Manman Rencbe4f942015-12-16 21:04:19 +00004057 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4058 const MCPhysReg *I =
4059 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4060 if (I) {
4061 for (; *I; ++I) {
4062 if (AArch64::GPR64RegClass.contains(*I))
4063 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4064 else if (AArch64::FPR64RegClass.contains(*I))
4065 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4066 else
4067 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4068 }
4069 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004070
4071 RetOps[0] = Chain; // Update chain.
4072
4073 // Add the flag if we have it.
4074 if (Flag.getNode())
4075 RetOps.push_back(Flag);
4076
4077 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4078}
4079
4080//===----------------------------------------------------------------------===//
4081// Other Lowering Code
4082//===----------------------------------------------------------------------===//
4083
Joel Jonesa7c4a522017-04-21 17:31:03 +00004084SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4085 SelectionDAG &DAG,
4086 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004087 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4088 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004089}
4090
4091SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4092 SelectionDAG &DAG,
4093 unsigned Flag) const {
4094 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4095}
4096
4097SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4098 SelectionDAG &DAG,
4099 unsigned Flag) const {
4100 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4101 N->getOffset(), Flag);
4102}
4103
4104SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4105 SelectionDAG &DAG,
4106 unsigned Flag) const {
4107 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4108}
4109
4110// (loadGOT sym)
4111template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004112SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4113 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004114 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004115 SDLoc DL(N);
4116 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004117 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004118 // FIXME: Once remat is capable of dealing with instructions with register
4119 // operands, expand this into two nodes instead of using a wrapper node.
4120 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4121}
4122
4123// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4124template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004125SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4126 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004127 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004128 SDLoc DL(N);
4129 EVT Ty = getPointerTy(DAG.getDataLayout());
4130 const unsigned char MO_NC = AArch64II::MO_NC;
4131 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004132 AArch64ISD::WrapperLarge, DL, Ty,
4133 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4134 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4135 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4136 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004137}
4138
4139// (addlow (adrp %hi(sym)) %lo(sym))
4140template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004141SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4142 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004143 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004144 SDLoc DL(N);
4145 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004146 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004147 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004148 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004149 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4150 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4151}
4152
David Green9dd1d452018-08-22 11:31:39 +00004153// (adr sym)
4154template <class NodeTy>
4155SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4156 unsigned Flags) const {
4157 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4158 SDLoc DL(N);
4159 EVT Ty = getPointerTy(DAG.getDataLayout());
4160 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4161 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4162}
4163
Tim Northover3b0846e2014-05-24 12:50:23 +00004164SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4165 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004166 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004167 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004168 unsigned char OpFlags =
4169 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004170
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004171 if (OpFlags != AArch64II::MO_NO_FLAG)
4172 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4173 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004174
David Green9dd1d452018-08-22 11:31:39 +00004175 // This also catches the large code model case for Darwin, and tiny code
4176 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004177 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004178 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004179 }
4180
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004181 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004182 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004183 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004184 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004185 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004186 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004187 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004188 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004189 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4190 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004191 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004192 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4193 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4194 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004195}
4196
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004197/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004198/// and calls to compute the variable's address (for Darwin, currently) and
4199/// return an SDValue containing the final node.
4200
4201/// Darwin only has one TLS scheme which must be capable of dealing with the
4202/// fully general situation, in the worst case. This means:
4203/// + "extern __thread" declaration.
4204/// + Defined in a possibly unknown dynamic library.
4205///
4206/// The general system is that each __thread variable has a [3 x i64] descriptor
4207/// which contains information used by the runtime to calculate the address. The
4208/// only part of this the compiler needs to know about is the first xword, which
4209/// contains a function pointer that must be called with the address of the
4210/// entire descriptor in "x0".
4211///
4212/// Since this descriptor may be in a different unit, in general even the
4213/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4214/// is:
4215/// adrp x0, _var@TLVPPAGE
4216/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4217/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4218/// ; the function pointer
4219/// blr x1 ; Uses descriptor address in x0
4220/// ; Address of _var is now in x0.
4221///
4222/// If the address of _var's descriptor *is* known to the linker, then it can
4223/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4224/// a slight efficiency gain.
4225SDValue
4226AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4227 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004228 assert(Subtarget->isTargetDarwin() &&
4229 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004230
4231 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004232 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004233 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4234
4235 SDValue TLVPAddr =
4236 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4237 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4238
4239 // The first entry in the descriptor is a function pointer that we must call
4240 // to obtain the address of the variable.
4241 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004242 SDValue FuncTLVGet = DAG.getLoad(
4243 MVT::i64, DL, Chain, DescAddr,
4244 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4245 /* Alignment = */ 8,
4246 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4247 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004248 Chain = FuncTLVGet.getValue(1);
4249
Matthias Braun941a7052016-07-28 18:40:00 +00004250 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4251 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004252
4253 // TLS calls preserve all registers except those that absolutely must be
4254 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4255 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004256 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4257 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4258 if (Subtarget->hasCustomCallingConv())
4259 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004260
4261 // Finally, we can make the call. This is just a degenerate version of a
4262 // normal AArch64 call node: x0 takes the address of the descriptor, and
4263 // returns the address of the variable in this thread.
4264 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4265 Chain =
4266 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4267 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4268 DAG.getRegisterMask(Mask), Chain.getValue(1));
4269 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4270}
4271
4272/// When accessing thread-local variables under either the general-dynamic or
4273/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4274/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004275/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004276///
Kristof Beylsaea84612015-03-04 09:12:08 +00004277/// The sequence is:
4278/// adrp x0, :tlsdesc:var
4279/// ldr x1, [x0, #:tlsdesc_lo12:var]
4280/// add x0, x0, #:tlsdesc_lo12:var
4281/// .tlsdesccall var
4282/// blr x1
4283/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004284///
Kristof Beylsaea84612015-03-04 09:12:08 +00004285/// The above sequence must be produced unscheduled, to enable the linker to
4286/// optimize/relax this sequence.
4287/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4288/// above sequence, and expanded really late in the compilation flow, to ensure
4289/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004290SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4291 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004292 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004293 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004294
Kristof Beylsaea84612015-03-04 09:12:08 +00004295 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004296 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004297
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004298 Chain =
4299 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004300 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004301
4302 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4303}
4304
4305SDValue
4306AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4307 SelectionDAG &DAG) const {
4308 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004309 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4310 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004311 // Different choices can be made for the maximum size of the TLS area for a
4312 // module. For the small address model, the default TLS size is 16MiB and the
4313 // maximum TLS size is 4GiB.
4314 // FIXME: add -mtls-size command line option and make it control the 16MiB
4315 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004316 // FIXME: add tiny codemodel support. We currently generate the same code as
4317 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004318 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4319
4320 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004321
Kristof Beylsaea84612015-03-04 09:12:08 +00004322 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4323 if (Model == TLSModel::LocalDynamic)
4324 Model = TLSModel::GeneralDynamic;
4325 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004326
4327 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004328 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004329 SDLoc DL(Op);
4330 const GlobalValue *GV = GA->getGlobal();
4331
4332 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4333
4334 if (Model == TLSModel::LocalExec) {
4335 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004336 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004337 SDValue LoVar = DAG.getTargetGlobalAddress(
4338 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004339 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004340
Kristof Beylsaea84612015-03-04 09:12:08 +00004341 SDValue TPWithOff_lo =
4342 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004343 HiVar,
4344 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004345 0);
4346 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004347 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4348 LoVar,
4349 DAG.getTargetConstant(0, DL, MVT::i32)),
4350 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004351 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004352 } else if (Model == TLSModel::InitialExec) {
4353 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4354 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4355 } else if (Model == TLSModel::LocalDynamic) {
4356 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4357 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4358 // the beginning of the module's TLS region, followed by a DTPREL offset
4359 // calculation.
4360
4361 // These accesses will need deduplicating if there's more than one.
4362 AArch64FunctionInfo *MFI =
4363 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4364 MFI->incNumLocalDynamicTLSAccesses();
4365
Tim Northover3b0846e2014-05-24 12:50:23 +00004366 // The call needs a relocation too for linker relaxation. It doesn't make
4367 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4368 // the address.
4369 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4370 AArch64II::MO_TLS);
4371
4372 // Now we can calculate the offset from TPIDR_EL0 to this module's
4373 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004374 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004375
4376 // Now use :dtprel_whatever: operations to calculate this variable's offset
4377 // in its thread-storage area.
4378 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004379 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004380 SDValue LoVar = DAG.getTargetGlobalAddress(
4381 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004382 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4383
Kristof Beylsaea84612015-03-04 09:12:08 +00004384 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004385 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004386 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004387 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4388 DAG.getTargetConstant(0, DL, MVT::i32)),
4389 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004390 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004391 // The call needs a relocation too for linker relaxation. It doesn't make
4392 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4393 // the address.
4394 SDValue SymAddr =
4395 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4396
4397 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004398 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004399 } else
4400 llvm_unreachable("Unsupported ELF TLS access model");
4401
4402 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4403}
4404
Martin Storsjocc240962018-03-10 19:05:21 +00004405SDValue
4406AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4407 SelectionDAG &DAG) const {
4408 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4409
4410 SDValue Chain = DAG.getEntryNode();
4411 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4412 SDLoc DL(Op);
4413
4414 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4415
4416 // Load the ThreadLocalStoragePointer from the TEB
4417 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4418 SDValue TLSArray =
4419 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4420 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4421 Chain = TLSArray.getValue(1);
4422
4423 // Load the TLS index from the C runtime;
4424 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4425 // This also does the same as LOADgot, but using a generic i32 load,
4426 // while LOADgot only loads i64.
4427 SDValue TLSIndexHi =
4428 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4429 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4430 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4431 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4432 SDValue TLSIndex =
4433 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4434 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4435 Chain = TLSIndex.getValue(1);
4436
4437 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4438 // offset into the TLSArray.
4439 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4440 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4441 DAG.getConstant(3, DL, PtrVT));
4442 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4443 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4444 MachinePointerInfo());
4445 Chain = TLS.getValue(1);
4446
4447 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4448 const GlobalValue *GV = GA->getGlobal();
4449 SDValue TGAHi = DAG.getTargetGlobalAddress(
4450 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4451 SDValue TGALo = DAG.getTargetGlobalAddress(
4452 GV, DL, PtrVT, 0,
4453 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4454
4455 // Add the offset from the start of the .tls section (section base).
4456 SDValue Addr =
4457 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4458 DAG.getTargetConstant(0, DL, MVT::i32)),
4459 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004460 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004461 return Addr;
4462}
4463
Tim Northover3b0846e2014-05-24 12:50:23 +00004464SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4465 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004466 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004467 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004468 return LowerToTLSEmulatedModel(GA, DAG);
4469
Tim Northover3b0846e2014-05-24 12:50:23 +00004470 if (Subtarget->isTargetDarwin())
4471 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004472 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004473 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004474 if (Subtarget->isTargetWindows())
4475 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004476
4477 llvm_unreachable("Unexpected platform trying to use TLS");
4478}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004479
Tim Northover3b0846e2014-05-24 12:50:23 +00004480SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4481 SDValue Chain = Op.getOperand(0);
4482 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4483 SDValue LHS = Op.getOperand(2);
4484 SDValue RHS = Op.getOperand(3);
4485 SDValue Dest = Op.getOperand(4);
4486 SDLoc dl(Op);
4487
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004488 MachineFunction &MF = DAG.getMachineFunction();
4489 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4490 // will not be produced, as they are conditional branch instructions that do
4491 // not set flags.
4492 bool ProduceNonFlagSettingCondBr =
4493 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4494
Tim Northover3b0846e2014-05-24 12:50:23 +00004495 // Handle f128 first, since lowering it will result in comparing the return
4496 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4497 // is expecting to deal with.
4498 if (LHS.getValueType() == MVT::f128) {
4499 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4500
4501 // If softenSetCCOperands returned a scalar, we need to compare the result
4502 // against zero to select between true and false values.
4503 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004504 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004505 CC = ISD::SETNE;
4506 }
4507 }
4508
4509 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4510 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004511 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4512 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004513 // Only lower legal XALUO ops.
4514 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4515 return SDValue();
4516
4517 // The actual operation with overflow check.
4518 AArch64CC::CondCode OFCC;
4519 SDValue Value, Overflow;
4520 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4521
4522 if (CC == ISD::SETNE)
4523 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004524 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004525
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004526 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4527 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004528 }
4529
4530 if (LHS.getValueType().isInteger()) {
4531 assert((LHS.getValueType() == RHS.getValueType()) &&
4532 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4533
4534 // If the RHS of the comparison is zero, we can potentially fold this
4535 // to a specialized branch.
4536 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004537 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004538 if (CC == ISD::SETEQ) {
4539 // See if we can use a TBZ to fold in an AND as well.
4540 // TBZ has a smaller branch displacement than CBZ. If the offset is
4541 // out of bounds, a late MI-layer pass rewrites branches.
4542 // 403.gcc is an example that hits this case.
4543 if (LHS.getOpcode() == ISD::AND &&
4544 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4545 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4546 SDValue Test = LHS.getOperand(0);
4547 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004548 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004549 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4550 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004551 }
4552
4553 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4554 } else if (CC == ISD::SETNE) {
4555 // See if we can use a TBZ to fold in an AND as well.
4556 // TBZ has a smaller branch displacement than CBZ. If the offset is
4557 // out of bounds, a late MI-layer pass rewrites branches.
4558 // 403.gcc is an example that hits this case.
4559 if (LHS.getOpcode() == ISD::AND &&
4560 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4561 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4562 SDValue Test = LHS.getOperand(0);
4563 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004564 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004565 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4566 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004567 }
4568
4569 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004570 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4571 // Don't combine AND since emitComparison converts the AND to an ANDS
4572 // (a.k.a. TST) and the test in the test bit and branch instruction
4573 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004574 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004575 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004576 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004577 }
4578 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004579 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004580 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004581 // Don't combine AND since emitComparison converts the AND to an ANDS
4582 // (a.k.a. TST) and the test in the test bit and branch instruction
4583 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004584 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004585 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004586 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004587 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004588
4589 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004590 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004591 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4592 Cmp);
4593 }
4594
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004595 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4596 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004597
4598 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4599 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004600 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004601 AArch64CC::CondCode CC1, CC2;
4602 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004603 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004604 SDValue BR1 =
4605 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4606 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004607 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004608 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4609 Cmp);
4610 }
4611
4612 return BR1;
4613}
4614
4615SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4616 SelectionDAG &DAG) const {
4617 EVT VT = Op.getValueType();
4618 SDLoc DL(Op);
4619
4620 SDValue In1 = Op.getOperand(0);
4621 SDValue In2 = Op.getOperand(1);
4622 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004623
4624 if (SrcVT.bitsLT(VT))
4625 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4626 else if (SrcVT.bitsGT(VT))
4627 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004628
4629 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004630 uint64_t EltMask;
4631 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004632
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004633 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004634 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004635 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004636 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004637 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004638 DAG.getUNDEF(VecVT), In2);
4639 } else {
4640 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4641 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4642 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004643 };
4644
4645 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4646 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4647 EltMask = 0x80000000ULL;
4648 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004649 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004650 VecVT = MVT::v2i64;
4651
Eric Christopher572e03a2015-06-19 01:53:21 +00004652 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004653 // immediate moves cannot materialize that in a single instruction for
4654 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004655 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004656
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004657 setVecVal(AArch64::dsub);
4658 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4659 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4660 EltMask = 0x8000ULL;
4661 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004662 } else {
4663 llvm_unreachable("Invalid type for copysign!");
4664 }
4665
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004666 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004667
4668 // If we couldn't materialize the mask above, then the mask vector will be
4669 // the zero vector, and we need to negate it here.
4670 if (VT == MVT::f64 || VT == MVT::v2f64) {
4671 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4672 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4673 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4674 }
4675
4676 SDValue Sel =
4677 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4678
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004679 if (VT == MVT::f16)
4680 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004681 if (VT == MVT::f32)
4682 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4683 else if (VT == MVT::f64)
4684 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4685 else
4686 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4687}
4688
4689SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004690 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004691 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004692 return SDValue();
4693
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004694 if (!Subtarget->hasNEON())
4695 return SDValue();
4696
Tim Northover3b0846e2014-05-24 12:50:23 +00004697 // While there is no integer popcount instruction, it can
4698 // be more efficiently lowered to the following sequence that uses
4699 // AdvSIMD registers/instructions as long as the copies to/from
4700 // the AdvSIMD registers are cheap.
4701 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4702 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4703 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4704 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4705 SDValue Val = Op.getOperand(0);
4706 SDLoc DL(Op);
4707 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004708
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004709 if (VT == MVT::i32 || VT == MVT::i64) {
4710 if (VT == MVT::i32)
4711 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4712 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004713
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004714 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4715 SDValue UaddLV = DAG.getNode(
4716 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4717 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004718
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004719 if (VT == MVT::i64)
4720 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4721 return UaddLV;
4722 }
4723
4724 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4725 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4726 "Unexpected type for custom ctpop lowering");
4727
4728 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4729 Val = DAG.getBitcast(VT8Bit, Val);
4730 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4731
4732 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4733 unsigned EltSize = 8;
4734 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4735 while (EltSize != VT.getScalarSizeInBits()) {
4736 EltSize *= 2;
4737 NumElts /= 2;
4738 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4739 Val = DAG.getNode(
4740 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4741 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4742 }
4743
4744 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004745}
4746
4747SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4748
4749 if (Op.getValueType().isVector())
4750 return LowerVSETCC(Op, DAG);
4751
4752 SDValue LHS = Op.getOperand(0);
4753 SDValue RHS = Op.getOperand(1);
4754 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4755 SDLoc dl(Op);
4756
4757 // We chose ZeroOrOneBooleanContents, so use zero and one.
4758 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004759 SDValue TVal = DAG.getConstant(1, dl, VT);
4760 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004761
4762 // Handle f128 first, since one possible outcome is a normal integer
4763 // comparison which gets picked up by the next if statement.
4764 if (LHS.getValueType() == MVT::f128) {
4765 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4766
4767 // If softenSetCCOperands returned a scalar, use it.
4768 if (!RHS.getNode()) {
4769 assert(LHS.getValueType() == Op.getValueType() &&
4770 "Unexpected setcc expansion!");
4771 return LHS;
4772 }
4773 }
4774
4775 if (LHS.getValueType().isInteger()) {
4776 SDValue CCVal;
4777 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004778 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004779
4780 // Note that we inverted the condition above, so we reverse the order of
4781 // the true and false operands here. This will allow the setcc to be
4782 // matched to a single CSINC instruction.
4783 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4784 }
4785
4786 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004787 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4788 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004789
4790 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4791 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004792 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004793
4794 AArch64CC::CondCode CC1, CC2;
4795 changeFPCCToAArch64CC(CC, CC1, CC2);
4796 if (CC2 == AArch64CC::AL) {
4797 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004798 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004799
4800 // Note that we inverted the condition above, so we reverse the order of
4801 // the true and false operands here. This will allow the setcc to be
4802 // matched to a single CSINC instruction.
4803 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4804 } else {
4805 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4806 // totally clean. Some of them require two CSELs to implement. As is in
4807 // this case, we emit the first CSEL and then emit a second using the output
4808 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4809
4810 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004811 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004812 SDValue CS1 =
4813 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4814
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004815 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004816 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4817 }
4818}
4819
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004820SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4821 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004822 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004823 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004824 // Handle f128 first, because it will result in a comparison of some RTLIB
4825 // call result against zero.
4826 if (LHS.getValueType() == MVT::f128) {
4827 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4828
4829 // If softenSetCCOperands returned a scalar, we need to compare the result
4830 // against zero to select between true and false values.
4831 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004832 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004833 CC = ISD::SETNE;
4834 }
4835 }
4836
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004837 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004838 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004839 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4840 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4841 }
4842
4843 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004844 if (LHS.getValueType().isInteger()) {
4845 assert((LHS.getValueType() == RHS.getValueType()) &&
4846 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4847
4848 unsigned Opcode = AArch64ISD::CSEL;
4849
4850 // If both the TVal and the FVal are constants, see if we can swap them in
4851 // order to for a CSINV or CSINC out of them.
4852 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4853 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4854
4855 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4856 std::swap(TVal, FVal);
4857 std::swap(CTVal, CFVal);
4858 CC = ISD::getSetCCInverse(CC, true);
4859 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4860 std::swap(TVal, FVal);
4861 std::swap(CTVal, CFVal);
4862 CC = ISD::getSetCCInverse(CC, true);
4863 } else if (TVal.getOpcode() == ISD::XOR) {
4864 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4865 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004866 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004867 std::swap(TVal, FVal);
4868 std::swap(CTVal, CFVal);
4869 CC = ISD::getSetCCInverse(CC, true);
4870 }
4871 } else if (TVal.getOpcode() == ISD::SUB) {
4872 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4873 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004874 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004875 std::swap(TVal, FVal);
4876 std::swap(CTVal, CFVal);
4877 CC = ISD::getSetCCInverse(CC, true);
4878 }
4879 } else if (CTVal && CFVal) {
4880 const int64_t TrueVal = CTVal->getSExtValue();
4881 const int64_t FalseVal = CFVal->getSExtValue();
4882 bool Swap = false;
4883
4884 // If both TVal and FVal are constants, see if FVal is the
4885 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4886 // instead of a CSEL in that case.
4887 if (TrueVal == ~FalseVal) {
4888 Opcode = AArch64ISD::CSINV;
4889 } else if (TrueVal == -FalseVal) {
4890 Opcode = AArch64ISD::CSNEG;
4891 } else if (TVal.getValueType() == MVT::i32) {
4892 // If our operands are only 32-bit wide, make sure we use 32-bit
4893 // arithmetic for the check whether we can use CSINC. This ensures that
4894 // the addition in the check will wrap around properly in case there is
4895 // an overflow (which would not be the case if we do the check with
4896 // 64-bit arithmetic).
4897 const uint32_t TrueVal32 = CTVal->getZExtValue();
4898 const uint32_t FalseVal32 = CFVal->getZExtValue();
4899
4900 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4901 Opcode = AArch64ISD::CSINC;
4902
4903 if (TrueVal32 > FalseVal32) {
4904 Swap = true;
4905 }
4906 }
4907 // 64-bit check whether we can use CSINC.
4908 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4909 Opcode = AArch64ISD::CSINC;
4910
4911 if (TrueVal > FalseVal) {
4912 Swap = true;
4913 }
4914 }
4915
4916 // Swap TVal and FVal if necessary.
4917 if (Swap) {
4918 std::swap(TVal, FVal);
4919 std::swap(CTVal, CFVal);
4920 CC = ISD::getSetCCInverse(CC, true);
4921 }
4922
4923 if (Opcode != AArch64ISD::CSEL) {
4924 // Drop FVal since we can get its value by simply inverting/negating
4925 // TVal.
4926 FVal = TVal;
4927 }
4928 }
4929
Chad Rosier58f505b2016-08-26 18:05:50 +00004930 // Avoid materializing a constant when possible by reusing a known value in
4931 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004932 // is one, zero or negative one in the case of a CSEL. We can always
4933 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4934 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004935 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4936 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4937 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4938 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4939 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4940 // "a != C ? x : a" to avoid materializing C.
4941 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4942 TVal = LHS;
4943 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4944 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004945 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4946 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4947 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4948 // avoid materializing C.
4949 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4950 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4951 Opcode = AArch64ISD::CSINV;
4952 TVal = LHS;
4953 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4954 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004955 }
4956
Tim Northover3b0846e2014-05-24 12:50:23 +00004957 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004958 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004959 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004960 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4961 }
4962
4963 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004964 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4965 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004966 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004967 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004968 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004969
4970 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4971 // clean. Some of them require two CSELs to implement.
4972 AArch64CC::CondCode CC1, CC2;
4973 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004974
4975 if (DAG.getTarget().Options.UnsafeFPMath) {
4976 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4977 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4978 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4979 if (RHSVal && RHSVal->isZero()) {
4980 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4981 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4982
4983 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004984 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004985 TVal = LHS;
4986 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004987 CFVal && CFVal->isZero() &&
4988 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004989 FVal = LHS;
4990 }
4991 }
4992
4993 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004994 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004995 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4996
4997 // If we need a second CSEL, emit it, using the output of the first as the
4998 // RHS. We're effectively OR'ing the two CC's together.
4999 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005000 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00005001 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5002 }
5003
5004 // Otherwise, return the output of the first CSEL.
5005 return CS1;
5006}
5007
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005008SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5009 SelectionDAG &DAG) const {
5010 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5011 SDValue LHS = Op.getOperand(0);
5012 SDValue RHS = Op.getOperand(1);
5013 SDValue TVal = Op.getOperand(2);
5014 SDValue FVal = Op.getOperand(3);
5015 SDLoc DL(Op);
5016 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5017}
5018
5019SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5020 SelectionDAG &DAG) const {
5021 SDValue CCVal = Op->getOperand(0);
5022 SDValue TVal = Op->getOperand(1);
5023 SDValue FVal = Op->getOperand(2);
5024 SDLoc DL(Op);
5025
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005026 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5027 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00005028 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005029 // Only lower legal XALUO ops.
5030 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5031 return SDValue();
5032
5033 AArch64CC::CondCode OFCC;
5034 SDValue Value, Overflow;
5035 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005036 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005037
5038 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5039 CCVal, Overflow);
5040 }
5041
5042 // Lower it the same way as we would lower a SELECT_CC node.
5043 ISD::CondCode CC;
5044 SDValue LHS, RHS;
5045 if (CCVal.getOpcode() == ISD::SETCC) {
5046 LHS = CCVal.getOperand(0);
5047 RHS = CCVal.getOperand(1);
5048 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5049 } else {
5050 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005051 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005052 CC = ISD::SETNE;
5053 }
5054 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5055}
5056
Tim Northover3b0846e2014-05-24 12:50:23 +00005057SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5058 SelectionDAG &DAG) const {
5059 // Jump table entries as PC relative offsets. No additional tweaking
5060 // is necessary here. Just get the address of the jump table.
5061 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005062
5063 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5064 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005065 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005066 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5067 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005068 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005069 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005070}
5071
Tim Northover1c353412018-10-24 20:19:09 +00005072SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5073 SelectionDAG &DAG) const {
5074 // Jump table entries as PC relative offsets. No additional tweaking
5075 // is necessary here. Just get the address of the jump table.
5076 SDLoc DL(Op);
5077 SDValue JT = Op.getOperand(1);
5078 SDValue Entry = Op.getOperand(2);
5079 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5080
5081 SDNode *Dest =
5082 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5083 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5084 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5085 SDValue(Dest, 0));
5086}
5087
Tim Northover3b0846e2014-05-24 12:50:23 +00005088SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5089 SelectionDAG &DAG) const {
5090 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005091
5092 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5093 // Use the GOT for the large code model on iOS.
5094 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005095 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005096 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005097 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005098 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5099 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005100 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005101 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005102 }
5103}
5104
5105SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5106 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005107 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005108 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5109 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005110 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005111 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5112 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005113 }
David Green9dd1d452018-08-22 11:31:39 +00005114 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005115}
5116
5117SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5118 SelectionDAG &DAG) const {
5119 AArch64FunctionInfo *FuncInfo =
5120 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5121
5122 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005123 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5124 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005125 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5126 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005127 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005128}
5129
Martin Storsjo68266fa2017-07-13 17:03:12 +00005130SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5131 SelectionDAG &DAG) const {
5132 AArch64FunctionInfo *FuncInfo =
5133 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5134
5135 SDLoc DL(Op);
5136 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5137 ? FuncInfo->getVarArgsGPRIndex()
5138 : FuncInfo->getVarArgsStackIndex(),
5139 getPointerTy(DAG.getDataLayout()));
5140 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5141 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5142 MachinePointerInfo(SV));
5143}
5144
Tim Northover3b0846e2014-05-24 12:50:23 +00005145SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5146 SelectionDAG &DAG) const {
5147 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5148 // Standard, section B.3.
5149 MachineFunction &MF = DAG.getMachineFunction();
5150 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005151 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005152 SDLoc DL(Op);
5153
5154 SDValue Chain = Op.getOperand(0);
5155 SDValue VAList = Op.getOperand(1);
5156 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5157 SmallVector<SDValue, 4> MemOps;
5158
5159 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005160 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005161 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005162 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005163
5164 // void *__gr_top at offset 8
5165 int GPRSize = FuncInfo->getVarArgsGPRSize();
5166 if (GPRSize > 0) {
5167 SDValue GRTop, GRTopAddr;
5168
Mehdi Amini44ede332015-07-09 02:09:04 +00005169 GRTopAddr =
5170 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005171
Mehdi Amini44ede332015-07-09 02:09:04 +00005172 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5173 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5174 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005175
5176 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005177 MachinePointerInfo(SV, 8),
5178 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005179 }
5180
5181 // void *__vr_top at offset 16
5182 int FPRSize = FuncInfo->getVarArgsFPRSize();
5183 if (FPRSize > 0) {
5184 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005185 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5186 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005187
Mehdi Amini44ede332015-07-09 02:09:04 +00005188 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5189 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5190 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005191
5192 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005193 MachinePointerInfo(SV, 16),
5194 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005195 }
5196
5197 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005198 SDValue GROffsAddr =
5199 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005200 MemOps.push_back(DAG.getStore(
5201 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5202 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005203
5204 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005205 SDValue VROffsAddr =
5206 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005207 MemOps.push_back(DAG.getStore(
5208 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5209 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005210
5211 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5212}
5213
5214SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5215 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005216 MachineFunction &MF = DAG.getMachineFunction();
5217
Matthias Braunf1caa282017-12-15 22:22:58 +00005218 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005219 return LowerWin64_VASTART(Op, DAG);
5220 else if (Subtarget->isTargetDarwin())
5221 return LowerDarwin_VASTART(Op, DAG);
5222 else
5223 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005224}
5225
5226SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5227 SelectionDAG &DAG) const {
5228 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5229 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005230 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005231 unsigned VaListSize =
5232 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005233 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5234 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5235
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005236 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5237 Op.getOperand(2),
5238 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005239 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005240 MachinePointerInfo(SrcSV));
5241}
5242
5243SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5244 assert(Subtarget->isTargetDarwin() &&
5245 "automatic va_arg instruction only works on Darwin");
5246
5247 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5248 EVT VT = Op.getValueType();
5249 SDLoc DL(Op);
5250 SDValue Chain = Op.getOperand(0);
5251 SDValue Addr = Op.getOperand(1);
5252 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005253 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005254
Justin Lebar9c375812016-07-15 18:27:10 +00005255 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005256 Chain = VAList.getValue(1);
5257
5258 if (Align > 8) {
5259 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005260 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5261 DAG.getConstant(Align - 1, DL, PtrVT));
5262 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5263 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005264 }
5265
5266 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005267 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005268
5269 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5270 // up to 64 bits. At the very least, we have to increase the striding of the
5271 // vaargs list to match this, and for FP values we need to introduce
5272 // FP_ROUND nodes as well.
5273 if (VT.isInteger() && !VT.isVector())
5274 ArgSize = 8;
5275 bool NeedFPTrunc = false;
5276 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5277 ArgSize = 8;
5278 NeedFPTrunc = true;
5279 }
5280
5281 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005282 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5283 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005284 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005285 SDValue APStore =
5286 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005287
5288 // Load the actual argument out of the pointer VAList
5289 if (NeedFPTrunc) {
5290 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005291 SDValue WideFP =
5292 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005293 // Round the value down to an f32.
5294 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005295 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005296 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5297 // Merge the rounded value with the chain output of the load.
5298 return DAG.getMergeValues(Ops, DL);
5299 }
5300
Justin Lebar9c375812016-07-15 18:27:10 +00005301 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005302}
5303
5304SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5305 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005306 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5307 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005308
5309 EVT VT = Op.getValueType();
5310 SDLoc DL(Op);
5311 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5312 SDValue FrameAddr =
5313 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5314 while (Depth--)
5315 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005316 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005317 return FrameAddr;
5318}
5319
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005320SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5321 SelectionDAG &DAG) const {
5322 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5323
5324 EVT VT = getPointerTy(DAG.getDataLayout());
5325 SDLoc DL(Op);
5326 int FI = MFI.CreateFixedObject(4, 0, false);
5327 return DAG.getFrameIndex(FI, VT);
5328}
5329
Petr Hosekfcbec022019-02-13 17:28:47 +00005330#define GET_REGISTER_MATCHER
5331#include "AArch64GenAsmMatcher.inc"
5332
Tim Northover3b0846e2014-05-24 12:50:23 +00005333// FIXME? Maybe this could be a TableGen attribute on some registers and
5334// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005335unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5336 SelectionDAG &DAG) const {
Petr Hosekfcbec022019-02-13 17:28:47 +00005337 unsigned Reg = MatchRegisterName(RegName);
5338 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5339 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5340 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5341 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5342 Reg = 0;
5343 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005344 if (Reg)
5345 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005346 report_fatal_error(Twine("Invalid register name \""
5347 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005348}
5349
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005350SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5351 SelectionDAG &DAG) const {
5352 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5353
5354 EVT VT = Op.getValueType();
5355 SDLoc DL(Op);
5356
5357 SDValue FrameAddr =
5358 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5359 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5360
5361 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5362}
5363
Tim Northover3b0846e2014-05-24 12:50:23 +00005364SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5365 SelectionDAG &DAG) const {
5366 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005367 MachineFrameInfo &MFI = MF.getFrameInfo();
5368 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005369
5370 EVT VT = Op.getValueType();
5371 SDLoc DL(Op);
5372 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5373 if (Depth) {
5374 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005375 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005376 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5377 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005378 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005379 }
5380
5381 // Return LR, which contains the return address. Mark it an implicit live-in.
5382 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5383 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5384}
5385
5386/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5387/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5388SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5389 SelectionDAG &DAG) const {
5390 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5391 EVT VT = Op.getValueType();
5392 unsigned VTBits = VT.getSizeInBits();
5393 SDLoc dl(Op);
5394 SDValue ShOpLo = Op.getOperand(0);
5395 SDValue ShOpHi = Op.getOperand(1);
5396 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005397 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5398
5399 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5400
5401 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005402 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005403 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5404
5405 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5406 // is "undef". We wanted 0, so CSEL it directly.
5407 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5408 ISD::SETEQ, dl, DAG);
5409 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5410 HiBitsForLo =
5411 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5412 HiBitsForLo, CCVal, Cmp);
5413
Tim Northover3b0846e2014-05-24 12:50:23 +00005414 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005415 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005416
Tim Northoverf3be9d52015-12-02 00:33:54 +00005417 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5418 SDValue LoForNormalShift =
5419 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005420
Tim Northoverf3be9d52015-12-02 00:33:54 +00005421 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5422 dl, DAG);
5423 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5424 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5425 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5426 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005427
5428 // AArch64 shifts larger than the register width are wrapped rather than
5429 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005430 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5431 SDValue HiForBigShift =
5432 Opc == ISD::SRA
5433 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5434 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5435 : DAG.getConstant(0, dl, VT);
5436 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5437 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005438
5439 SDValue Ops[2] = { Lo, Hi };
5440 return DAG.getMergeValues(Ops, dl);
5441}
5442
5443/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5444/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5445SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005446 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005447 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5448 EVT VT = Op.getValueType();
5449 unsigned VTBits = VT.getSizeInBits();
5450 SDLoc dl(Op);
5451 SDValue ShOpLo = Op.getOperand(0);
5452 SDValue ShOpHi = Op.getOperand(1);
5453 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005454
5455 assert(Op.getOpcode() == ISD::SHL_PARTS);
5456 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005457 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005458 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5459
5460 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5461 // is "undef". We wanted 0, so CSEL it directly.
5462 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5463 ISD::SETEQ, dl, DAG);
5464 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5465 LoBitsForHi =
5466 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5467 LoBitsForHi, CCVal, Cmp);
5468
Tim Northover3b0846e2014-05-24 12:50:23 +00005469 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005470 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005471 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5472 SDValue HiForNormalShift =
5473 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005474
Tim Northoverf3be9d52015-12-02 00:33:54 +00005475 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005476
Tim Northoverf3be9d52015-12-02 00:33:54 +00005477 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5478 dl, DAG);
5479 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5480 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5481 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005482
5483 // AArch64 shifts of larger than register sizes are wrapped rather than
5484 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005485 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5486 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5487 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5488 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005489
5490 SDValue Ops[2] = { Lo, Hi };
5491 return DAG.getMergeValues(Ops, dl);
5492}
5493
5494bool AArch64TargetLowering::isOffsetFoldingLegal(
5495 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005496 // Offsets are folded in the DAG combine rather than here so that we can
5497 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005498 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005499}
5500
Adhemerval Zanella664c1ef2019-03-18 18:40:07 +00005501bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5502 bool OptForSize) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005503 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005504 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5505 // 16-bit case when target has full fp16 support.
5506 // FIXME: We should be able to handle f128 as well with a clever lowering.
5507 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005508 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005509 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005510 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005511 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005512 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005513 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5514 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5515 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005516
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005517 // If we can not materialize in immediate field for fmov, check if the
5518 // value can be encoded as the immediate operand of a logical instruction.
5519 // The immediate value will be created with either MOVZ, MOVN, or ORR.
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +00005520 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5521 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5522 // however the mov+fmov sequence is always better because of the reduced
5523 // cache pressure. The timings are still the same if you consider
5524 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5525 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5526 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5527 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5528 Insn);
5529 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5530 IsLegal = Insn.size() <= Limit;
5531 }
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005532
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005533 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5534 << " imm value: "; Imm.dump(););
5535 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005536}
5537
5538//===----------------------------------------------------------------------===//
5539// AArch64 Optimization Hooks
5540//===----------------------------------------------------------------------===//
5541
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005542static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5543 SDValue Operand, SelectionDAG &DAG,
5544 int &ExtraSteps) {
5545 EVT VT = Operand.getValueType();
5546 if (ST->hasNEON() &&
5547 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5548 VT == MVT::f32 || VT == MVT::v1f32 ||
5549 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5550 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5551 // For the reciprocal estimates, convergence is quadratic, so the number
5552 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5553 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5554 // the result for float (23 mantissa bits) is 2 and for double (52
5555 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005556 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005557
5558 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5559 }
5560
5561 return SDValue();
5562}
5563
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005564SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5565 SelectionDAG &DAG, int Enabled,
5566 int &ExtraSteps,
5567 bool &UseOneConst,
5568 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005569 if (Enabled == ReciprocalEstimate::Enabled ||
5570 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5571 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5572 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005573 SDLoc DL(Operand);
5574 EVT VT = Operand.getValueType();
5575
5576 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005577 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005578
5579 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5580 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5581 for (int i = ExtraSteps; i > 0; --i) {
5582 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005583 Flags);
5584 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5585 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005586 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005587 if (!Reciprocal) {
5588 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5589 VT);
5590 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5591 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5592
Amara Emersond28f0cd42017-05-01 15:17:51 +00005593 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005594 // Correct the result if the operand is 0.0.
5595 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5596 VT, Eq, Operand, Estimate);
5597 }
5598
5599 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005600 return Estimate;
5601 }
5602
5603 return SDValue();
5604}
5605
5606SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5607 SelectionDAG &DAG, int Enabled,
5608 int &ExtraSteps) const {
5609 if (Enabled == ReciprocalEstimate::Enabled)
5610 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005611 DAG, ExtraSteps)) {
5612 SDLoc DL(Operand);
5613 EVT VT = Operand.getValueType();
5614
5615 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005616 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005617
5618 // Newton reciprocal iteration: E * (2 - X * E)
5619 // AArch64 reciprocal iteration instruction: (2 - M * N)
5620 for (int i = ExtraSteps; i > 0; --i) {
5621 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005622 Estimate, Flags);
5623 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005624 }
5625
5626 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005627 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005628 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005629
5630 return SDValue();
5631}
5632
Tim Northover3b0846e2014-05-24 12:50:23 +00005633//===----------------------------------------------------------------------===//
5634// AArch64 Inline Assembly Support
5635//===----------------------------------------------------------------------===//
5636
5637// Table of Constraints
5638// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005639// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005640//
5641// r - A general register
5642// w - An FP/SIMD register of some size in the range v0-v31
5643// x - An FP/SIMD register of some size in the range v0-v15
5644// I - Constant that can be used with an ADD instruction
5645// J - Constant that can be used with a SUB instruction
5646// K - Constant that can be used with a 32-bit logical instruction
5647// L - Constant that can be used with a 64-bit logical instruction
5648// M - Constant that can be used as a 32-bit MOV immediate
5649// N - Constant that can be used as a 64-bit MOV immediate
5650// Q - A memory reference with base register and no offset
5651// S - A symbolic address
5652// Y - Floating point constant zero
5653// Z - Integer constant zero
5654//
5655// Note that general register operands will be output using their 64-bit x
5656// register name, whatever the size of the variable, unless the asm operand
5657// is prefixed by the %w modifier. Floating-point and SIMD register operands
5658// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5659// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005660const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5661 // At this point, we have to lower this constraint to something else, so we
5662 // lower it to an "r" or "w". However, by doing this we will force the result
5663 // to be in register, while the X constraint is much more permissive.
5664 //
5665 // Although we are correct (we are free to emit anything, without
5666 // constraints), we might break use cases that would expect us to be more
5667 // efficient and emit something else.
5668 if (!Subtarget->hasFPARMv8())
5669 return "r";
5670
5671 if (ConstraintVT.isFloatingPoint())
5672 return "w";
5673
5674 if (ConstraintVT.isVector() &&
5675 (ConstraintVT.getSizeInBits() == 64 ||
5676 ConstraintVT.getSizeInBits() == 128))
5677 return "w";
5678
5679 return "r";
5680}
Tim Northover3b0846e2014-05-24 12:50:23 +00005681
5682/// getConstraintType - Given a constraint letter, return the type of
5683/// constraint it is for this target.
5684AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005685AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005686 if (Constraint.size() == 1) {
5687 switch (Constraint[0]) {
5688 default:
5689 break;
5690 case 'z':
5691 return C_Other;
5692 case 'x':
5693 case 'w':
5694 return C_RegisterClass;
5695 // An address with a single base register. Due to the way we
5696 // currently handle addresses it is the same as 'r'.
5697 case 'Q':
5698 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005699 case 'S': // A symbolic address
5700 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005701 }
5702 }
5703 return TargetLowering::getConstraintType(Constraint);
5704}
5705
5706/// Examine constraint type and operand type and determine a weight value.
5707/// This object must already have been set up with the operand type
5708/// and the current alternative constraint selected.
5709TargetLowering::ConstraintWeight
5710AArch64TargetLowering::getSingleConstraintMatchWeight(
5711 AsmOperandInfo &info, const char *constraint) const {
5712 ConstraintWeight weight = CW_Invalid;
5713 Value *CallOperandVal = info.CallOperandVal;
5714 // If we don't have a value, we can't do a match,
5715 // but allow it at the lowest weight.
5716 if (!CallOperandVal)
5717 return CW_Default;
5718 Type *type = CallOperandVal->getType();
5719 // Look at the constraint type.
5720 switch (*constraint) {
5721 default:
5722 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5723 break;
5724 case 'x':
5725 case 'w':
5726 if (type->isFloatingPointTy() || type->isVectorTy())
5727 weight = CW_Register;
5728 break;
5729 case 'z':
5730 weight = CW_Constant;
5731 break;
5732 }
5733 return weight;
5734}
5735
5736std::pair<unsigned, const TargetRegisterClass *>
5737AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005738 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005739 if (Constraint.size() == 1) {
5740 switch (Constraint[0]) {
5741 case 'r':
5742 if (VT.getSizeInBits() == 64)
5743 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5744 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5745 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005746 if (!Subtarget->hasFPARMv8())
5747 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005748 if (VT.getSizeInBits() == 16)
5749 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005750 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005751 return std::make_pair(0U, &AArch64::FPR32RegClass);
5752 if (VT.getSizeInBits() == 64)
5753 return std::make_pair(0U, &AArch64::FPR64RegClass);
5754 if (VT.getSizeInBits() == 128)
5755 return std::make_pair(0U, &AArch64::FPR128RegClass);
5756 break;
5757 // The instructions that this constraint is designed for can
5758 // only take 128-bit registers so just use that regclass.
5759 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005760 if (!Subtarget->hasFPARMv8())
5761 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005762 if (VT.getSizeInBits() == 128)
5763 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5764 break;
5765 }
5766 }
5767 if (StringRef("{cc}").equals_lower(Constraint))
5768 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5769
5770 // Use the default implementation in TargetLowering to convert the register
5771 // constraint into a member of a register class.
5772 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005773 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005774
5775 // Not found as a standard register?
5776 if (!Res.second) {
5777 unsigned Size = Constraint.size();
5778 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5779 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005780 int RegNo;
5781 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5782 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005783 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005784 // By default we'll emit v0-v31 for this unless there's a modifier where
5785 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005786 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5787 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5788 Res.second = &AArch64::FPR64RegClass;
5789 } else {
5790 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5791 Res.second = &AArch64::FPR128RegClass;
5792 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005793 }
5794 }
5795 }
5796
Eli Friedman071203b2018-08-24 19:12:13 +00005797 if (Res.second && !Subtarget->hasFPARMv8() &&
5798 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5799 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5800 return std::make_pair(0U, nullptr);
5801
Tim Northover3b0846e2014-05-24 12:50:23 +00005802 return Res;
5803}
5804
5805/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5806/// vector. If it is invalid, don't add anything to Ops.
5807void AArch64TargetLowering::LowerAsmOperandForConstraint(
5808 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5809 SelectionDAG &DAG) const {
5810 SDValue Result;
5811
5812 // Currently only support length 1 constraints.
5813 if (Constraint.length() != 1)
5814 return;
5815
5816 char ConstraintLetter = Constraint[0];
5817 switch (ConstraintLetter) {
5818 default:
5819 break;
5820
5821 // This set of constraints deal with valid constants for various instructions.
5822 // Validate and return a target constant for them if we can.
5823 case 'z': {
5824 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005825 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005826 return;
5827
5828 if (Op.getValueType() == MVT::i64)
5829 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5830 else
5831 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5832 break;
5833 }
Peter Smithc8117582018-05-16 09:33:25 +00005834 case 'S': {
5835 // An absolute symbolic address or label reference.
5836 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5837 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5838 GA->getValueType(0));
5839 } else if (const BlockAddressSDNode *BA =
5840 dyn_cast<BlockAddressSDNode>(Op)) {
5841 Result =
5842 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5843 } else if (const ExternalSymbolSDNode *ES =
5844 dyn_cast<ExternalSymbolSDNode>(Op)) {
5845 Result =
5846 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5847 } else
5848 return;
5849 break;
5850 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005851
5852 case 'I':
5853 case 'J':
5854 case 'K':
5855 case 'L':
5856 case 'M':
5857 case 'N':
5858 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5859 if (!C)
5860 return;
5861
5862 // Grab the value and do some validation.
5863 uint64_t CVal = C->getZExtValue();
5864 switch (ConstraintLetter) {
5865 // The I constraint applies only to simple ADD or SUB immediate operands:
5866 // i.e. 0 to 4095 with optional shift by 12
5867 // The J constraint applies only to ADD or SUB immediates that would be
5868 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5869 // instruction [or vice versa], in other words -1 to -4095 with optional
5870 // left shift by 12.
5871 case 'I':
5872 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5873 break;
5874 return;
5875 case 'J': {
5876 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005877 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5878 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005879 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005880 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005881 return;
5882 }
5883 // The K and L constraints apply *only* to logical immediates, including
5884 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5885 // been removed and MOV should be used). So these constraints have to
5886 // distinguish between bit patterns that are valid 32-bit or 64-bit
5887 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5888 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5889 // versa.
5890 case 'K':
5891 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5892 break;
5893 return;
5894 case 'L':
5895 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5896 break;
5897 return;
5898 // The M and N constraints are a superset of K and L respectively, for use
5899 // with the MOV (immediate) alias. As well as the logical immediates they
5900 // also match 32 or 64-bit immediates that can be loaded either using a
5901 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5902 // (M) or 64-bit 0x1234000000000000 (N) etc.
5903 // As a note some of this code is liberally stolen from the asm parser.
5904 case 'M': {
5905 if (!isUInt<32>(CVal))
5906 return;
5907 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5908 break;
5909 if ((CVal & 0xFFFF) == CVal)
5910 break;
5911 if ((CVal & 0xFFFF0000ULL) == CVal)
5912 break;
5913 uint64_t NCVal = ~(uint32_t)CVal;
5914 if ((NCVal & 0xFFFFULL) == NCVal)
5915 break;
5916 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5917 break;
5918 return;
5919 }
5920 case 'N': {
5921 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5922 break;
5923 if ((CVal & 0xFFFFULL) == CVal)
5924 break;
5925 if ((CVal & 0xFFFF0000ULL) == CVal)
5926 break;
5927 if ((CVal & 0xFFFF00000000ULL) == CVal)
5928 break;
5929 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5930 break;
5931 uint64_t NCVal = ~CVal;
5932 if ((NCVal & 0xFFFFULL) == NCVal)
5933 break;
5934 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5935 break;
5936 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5937 break;
5938 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5939 break;
5940 return;
5941 }
5942 default:
5943 return;
5944 }
5945
5946 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005947 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005948 break;
5949 }
5950
5951 if (Result.getNode()) {
5952 Ops.push_back(Result);
5953 return;
5954 }
5955
5956 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5957}
5958
5959//===----------------------------------------------------------------------===//
5960// AArch64 Advanced SIMD Support
5961//===----------------------------------------------------------------------===//
5962
5963/// WidenVector - Given a value in the V64 register class, produce the
5964/// equivalent value in the V128 register class.
5965static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5966 EVT VT = V64Reg.getValueType();
5967 unsigned NarrowSize = VT.getVectorNumElements();
5968 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5969 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5970 SDLoc DL(V64Reg);
5971
5972 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005973 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005974}
5975
5976/// getExtFactor - Determine the adjustment factor for the position when
5977/// generating an "extract from vector registers" instruction.
5978static unsigned getExtFactor(SDValue &V) {
5979 EVT EltType = V.getValueType().getVectorElementType();
5980 return EltType.getSizeInBits() / 8;
5981}
5982
5983/// NarrowVector - Given a value in the V128 register class, produce the
5984/// equivalent value in the V64 register class.
5985static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5986 EVT VT = V128Reg.getValueType();
5987 unsigned WideSize = VT.getVectorNumElements();
5988 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5989 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5990 SDLoc DL(V128Reg);
5991
5992 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5993}
5994
5995// Gather data to see if the operation can be modelled as a
5996// shuffle in combination with VEXTs.
5997SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5998 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005999 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006000 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006001 SDLoc dl(Op);
6002 EVT VT = Op.getValueType();
6003 unsigned NumElts = VT.getVectorNumElements();
6004
Tim Northover7324e842014-07-24 15:39:55 +00006005 struct ShuffleSourceInfo {
6006 SDValue Vec;
6007 unsigned MinElt;
6008 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006009
Tim Northover7324e842014-07-24 15:39:55 +00006010 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6011 // be compatible with the shuffle we intend to construct. As a result
6012 // ShuffleVec will be some sliding window into the original Vec.
6013 SDValue ShuffleVec;
6014
6015 // Code should guarantee that element i in Vec starts at element "WindowBase
6016 // + i * WindowScale in ShuffleVec".
6017 int WindowBase;
6018 int WindowScale;
6019
Tim Northover7324e842014-07-24 15:39:55 +00006020 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00006021 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6022 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6023
6024 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00006025 };
6026
6027 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6028 // node.
6029 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00006030 for (unsigned i = 0; i < NumElts; ++i) {
6031 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006032 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006033 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00006034 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6035 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006036 LLVM_DEBUG(
6037 dbgs() << "Reshuffle failed: "
6038 "a shuffle can only come from building a vector from "
6039 "various elements of other vectors, provided their "
6040 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006041 return SDValue();
6042 }
6043
Tim Northover7324e842014-07-24 15:39:55 +00006044 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00006045 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00006046 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00006047 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00006048 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00006049
Tim Northover7324e842014-07-24 15:39:55 +00006050 // Update the minimum and maximum lane number seen.
6051 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6052 Source->MinElt = std::min(Source->MinElt, EltNo);
6053 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00006054 }
6055
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006056 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006057 LLVM_DEBUG(
6058 dbgs() << "Reshuffle failed: currently only do something sane when at "
6059 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006060 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006061 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006062
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006063 // Find out the smallest element size among result and two sources, and use
6064 // it as element size to build the shuffle_vector.
6065 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00006066 for (auto &Source : Sources) {
6067 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006068 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6069 SmallestEltTy = SrcEltTy;
6070 }
6071 }
6072 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006073 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006074 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6075 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00006076
Tim Northover7324e842014-07-24 15:39:55 +00006077 // If the source vector is too wide or too narrow, we may nevertheless be able
6078 // to construct a compatible shuffle either by concatenating it with UNDEF or
6079 // extracting a suitable range of elements.
6080 for (auto &Src : Sources) {
6081 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006082
Tim Northover7324e842014-07-24 15:39:55 +00006083 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00006084 continue;
Tim Northover7324e842014-07-24 15:39:55 +00006085
6086 // This stage of the search produces a source with the same element type as
6087 // the original, but with a total width matching the BUILD_VECTOR output.
6088 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00006089 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6090 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00006091
6092 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6093 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006094 // We can pad out the smaller vector for free, so if it's part of a
6095 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00006096 Src.ShuffleVec =
6097 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6098 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00006099 continue;
6100 }
6101
Tim Northover7324e842014-07-24 15:39:55 +00006102 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006103
James Molloyf497d552014-10-17 17:06:31 +00006104 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006105 LLVM_DEBUG(
6106 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006107 return SDValue();
6108 }
6109
James Molloyf497d552014-10-17 17:06:31 +00006110 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006111 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00006112 Src.ShuffleVec =
6113 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006114 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00006115 Src.WindowBase = -NumSrcElts;
6116 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006117 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006118 Src.ShuffleVec =
6119 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006120 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006121 } else {
6122 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006123 SDValue VEXTSrc1 =
6124 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006125 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006126 SDValue VEXTSrc2 =
6127 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006128 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006129 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6130
6131 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006132 VEXTSrc2,
6133 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006134 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006135 }
6136 }
6137
Tim Northover7324e842014-07-24 15:39:55 +00006138 // Another possible incompatibility occurs from the vector element types. We
6139 // can fix this by bitcasting the source vectors to the same type we intend
6140 // for the shuffle.
6141 for (auto &Src : Sources) {
6142 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6143 if (SrcEltTy == SmallestEltTy)
6144 continue;
6145 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6146 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6147 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6148 Src.WindowBase *= Src.WindowScale;
6149 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006150
Tim Northover7324e842014-07-24 15:39:55 +00006151 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006152 LLVM_DEBUG(for (auto Src
6153 : Sources)
6154 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006155
6156 // The stars all align, our next step is to produce the mask for the shuffle.
6157 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006158 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006159 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006160 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006161 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006162 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006163
David Majnemer0d955d02016-08-11 22:21:41 +00006164 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006165 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6166
6167 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6168 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6169 // segment.
6170 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006171 int BitsDefined =
6172 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006173 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6174
6175 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6176 // starting at the appropriate offset.
6177 int *LaneMask = &Mask[i * ResMultiplier];
6178
6179 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6180 ExtractBase += NumElts * (Src - Sources.begin());
6181 for (int j = 0; j < LanesDefined; ++j)
6182 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006183 }
6184
6185 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006186 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006187 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006188 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006189 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006190
Tim Northover7324e842014-07-24 15:39:55 +00006191 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6192 for (unsigned i = 0; i < Sources.size(); ++i)
6193 ShuffleOps[i] = Sources[i].ShuffleVec;
6194
6195 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006196 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006197 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6198
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006199 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6200 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006201
6202 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006203}
6204
6205// check if an EXT instruction can handle the shuffle mask when the
6206// vector sources of the shuffle are the same.
6207static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6208 unsigned NumElts = VT.getVectorNumElements();
6209
6210 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6211 if (M[0] < 0)
6212 return false;
6213
6214 Imm = M[0];
6215
6216 // If this is a VEXT shuffle, the immediate value is the index of the first
6217 // element. The other shuffle indices must be the successive elements after
6218 // the first one.
6219 unsigned ExpectedElt = Imm;
6220 for (unsigned i = 1; i < NumElts; ++i) {
6221 // Increment the expected index. If it wraps around, just follow it
6222 // back to index zero and keep going.
6223 ++ExpectedElt;
6224 if (ExpectedElt == NumElts)
6225 ExpectedElt = 0;
6226
6227 if (M[i] < 0)
6228 continue; // ignore UNDEF indices
6229 if (ExpectedElt != static_cast<unsigned>(M[i]))
6230 return false;
6231 }
6232
6233 return true;
6234}
6235
6236// check if an EXT instruction can handle the shuffle mask when the
6237// vector sources of the shuffle are different.
6238static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6239 unsigned &Imm) {
6240 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006241 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006242
6243 // Benefit form APInt to handle overflow when calculating expected element.
6244 unsigned NumElts = VT.getVectorNumElements();
6245 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6246 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6247 // The following shuffle indices must be the successive elements after the
6248 // first real element.
6249 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6250 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6251 if (FirstWrongElt != M.end())
6252 return false;
6253
6254 // The index of an EXT is the first element if it is not UNDEF.
6255 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006256 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006257 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6258 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6259 // ExpectedElt is the last mask index plus 1.
6260 Imm = ExpectedElt.getZExtValue();
6261
6262 // There are two difference cases requiring to reverse input vectors.
6263 // For example, for vector <4 x i32> we have the following cases,
6264 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6265 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6266 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6267 // to reverse two input vectors.
6268 if (Imm < NumElts)
6269 ReverseEXT = true;
6270 else
6271 Imm -= NumElts;
6272
6273 return true;
6274}
6275
6276/// isREVMask - Check if a vector shuffle corresponds to a REV
6277/// instruction with the specified blocksize. (The order of the elements
6278/// within each block of the vector is reversed.)
6279static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6280 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6281 "Only possible block sizes for REV are: 16, 32, 64");
6282
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006283 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006284 if (EltSz == 64)
6285 return false;
6286
6287 unsigned NumElts = VT.getVectorNumElements();
6288 unsigned BlockElts = M[0] + 1;
6289 // If the first shuffle index is UNDEF, be optimistic.
6290 if (M[0] < 0)
6291 BlockElts = BlockSize / EltSz;
6292
6293 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6294 return false;
6295
6296 for (unsigned i = 0; i < NumElts; ++i) {
6297 if (M[i] < 0)
6298 continue; // ignore UNDEF indices
6299 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6300 return false;
6301 }
6302
6303 return true;
6304}
6305
6306static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6307 unsigned NumElts = VT.getVectorNumElements();
6308 WhichResult = (M[0] == 0 ? 0 : 1);
6309 unsigned Idx = WhichResult * NumElts / 2;
6310 for (unsigned i = 0; i != NumElts; i += 2) {
6311 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6312 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6313 return false;
6314 Idx += 1;
6315 }
6316
6317 return true;
6318}
6319
6320static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6321 unsigned NumElts = VT.getVectorNumElements();
6322 WhichResult = (M[0] == 0 ? 0 : 1);
6323 for (unsigned i = 0; i != NumElts; ++i) {
6324 if (M[i] < 0)
6325 continue; // ignore UNDEF indices
6326 if ((unsigned)M[i] != 2 * i + WhichResult)
6327 return false;
6328 }
6329
6330 return true;
6331}
6332
6333static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6334 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006335 if (NumElts % 2 != 0)
6336 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006337 WhichResult = (M[0] == 0 ? 0 : 1);
6338 for (unsigned i = 0; i < NumElts; i += 2) {
6339 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6340 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6341 return false;
6342 }
6343 return true;
6344}
6345
6346/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6347/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6348/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6349static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6350 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006351 if (NumElts % 2 != 0)
6352 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006353 WhichResult = (M[0] == 0 ? 0 : 1);
6354 unsigned Idx = WhichResult * NumElts / 2;
6355 for (unsigned i = 0; i != NumElts; i += 2) {
6356 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6357 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6358 return false;
6359 Idx += 1;
6360 }
6361
6362 return true;
6363}
6364
6365/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6366/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6367/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6368static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6369 unsigned Half = VT.getVectorNumElements() / 2;
6370 WhichResult = (M[0] == 0 ? 0 : 1);
6371 for (unsigned j = 0; j != 2; ++j) {
6372 unsigned Idx = WhichResult;
6373 for (unsigned i = 0; i != Half; ++i) {
6374 int MIdx = M[i + j * Half];
6375 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6376 return false;
6377 Idx += 2;
6378 }
6379 }
6380
6381 return true;
6382}
6383
6384/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6385/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6386/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6387static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6388 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006389 if (NumElts % 2 != 0)
6390 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006391 WhichResult = (M[0] == 0 ? 0 : 1);
6392 for (unsigned i = 0; i < NumElts; i += 2) {
6393 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6394 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6395 return false;
6396 }
6397 return true;
6398}
6399
6400static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6401 bool &DstIsLeft, int &Anomaly) {
6402 if (M.size() != static_cast<size_t>(NumInputElements))
6403 return false;
6404
6405 int NumLHSMatch = 0, NumRHSMatch = 0;
6406 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6407
6408 for (int i = 0; i < NumInputElements; ++i) {
6409 if (M[i] == -1) {
6410 ++NumLHSMatch;
6411 ++NumRHSMatch;
6412 continue;
6413 }
6414
6415 if (M[i] == i)
6416 ++NumLHSMatch;
6417 else
6418 LastLHSMismatch = i;
6419
6420 if (M[i] == i + NumInputElements)
6421 ++NumRHSMatch;
6422 else
6423 LastRHSMismatch = i;
6424 }
6425
6426 if (NumLHSMatch == NumInputElements - 1) {
6427 DstIsLeft = true;
6428 Anomaly = LastLHSMismatch;
6429 return true;
6430 } else if (NumRHSMatch == NumInputElements - 1) {
6431 DstIsLeft = false;
6432 Anomaly = LastRHSMismatch;
6433 return true;
6434 }
6435
6436 return false;
6437}
6438
6439static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6440 if (VT.getSizeInBits() != 128)
6441 return false;
6442
6443 unsigned NumElts = VT.getVectorNumElements();
6444
6445 for (int I = 0, E = NumElts / 2; I != E; I++) {
6446 if (Mask[I] != I)
6447 return false;
6448 }
6449
6450 int Offset = NumElts / 2;
6451 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6452 if (Mask[I] != I + SplitLHS * Offset)
6453 return false;
6454 }
6455
6456 return true;
6457}
6458
6459static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6460 SDLoc DL(Op);
6461 EVT VT = Op.getValueType();
6462 SDValue V0 = Op.getOperand(0);
6463 SDValue V1 = Op.getOperand(1);
6464 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6465
6466 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6467 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6468 return SDValue();
6469
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006470 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006471
6472 if (!isConcatMask(Mask, VT, SplitV0))
6473 return SDValue();
6474
6475 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6476 VT.getVectorNumElements() / 2);
6477 if (SplitV0) {
6478 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006479 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006480 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006481 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006482 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006483 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006484 }
6485 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6486}
6487
6488/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6489/// the specified operations to build the shuffle.
6490static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6491 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006492 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006493 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6494 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6495 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6496
6497 enum {
6498 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6499 OP_VREV,
6500 OP_VDUP0,
6501 OP_VDUP1,
6502 OP_VDUP2,
6503 OP_VDUP3,
6504 OP_VEXT1,
6505 OP_VEXT2,
6506 OP_VEXT3,
6507 OP_VUZPL, // VUZP, left result
6508 OP_VUZPR, // VUZP, right result
6509 OP_VZIPL, // VZIP, left result
6510 OP_VZIPR, // VZIP, right result
6511 OP_VTRNL, // VTRN, left result
6512 OP_VTRNR // VTRN, right result
6513 };
6514
6515 if (OpNum == OP_COPY) {
6516 if (LHSID == (1 * 9 + 2) * 9 + 3)
6517 return LHS;
6518 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6519 return RHS;
6520 }
6521
6522 SDValue OpLHS, OpRHS;
6523 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6524 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6525 EVT VT = OpLHS.getValueType();
6526
6527 switch (OpNum) {
6528 default:
6529 llvm_unreachable("Unknown shuffle opcode!");
6530 case OP_VREV:
6531 // VREV divides the vector in half and swaps within the half.
6532 if (VT.getVectorElementType() == MVT::i32 ||
6533 VT.getVectorElementType() == MVT::f32)
6534 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6535 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006536 if (VT.getVectorElementType() == MVT::i16 ||
6537 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006538 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6539 // vrev <4 x i8> -> REV16
6540 assert(VT.getVectorElementType() == MVT::i8);
6541 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6542 case OP_VDUP0:
6543 case OP_VDUP1:
6544 case OP_VDUP2:
6545 case OP_VDUP3: {
6546 EVT EltTy = VT.getVectorElementType();
6547 unsigned Opcode;
6548 if (EltTy == MVT::i8)
6549 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006550 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006551 Opcode = AArch64ISD::DUPLANE16;
6552 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6553 Opcode = AArch64ISD::DUPLANE32;
6554 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6555 Opcode = AArch64ISD::DUPLANE64;
6556 else
6557 llvm_unreachable("Invalid vector element type?");
6558
6559 if (VT.getSizeInBits() == 64)
6560 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006561 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006562 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6563 }
6564 case OP_VEXT1:
6565 case OP_VEXT2:
6566 case OP_VEXT3: {
6567 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6568 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006569 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006570 }
6571 case OP_VUZPL:
6572 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6573 OpRHS);
6574 case OP_VUZPR:
6575 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6576 OpRHS);
6577 case OP_VZIPL:
6578 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6579 OpRHS);
6580 case OP_VZIPR:
6581 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6582 OpRHS);
6583 case OP_VTRNL:
6584 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6585 OpRHS);
6586 case OP_VTRNR:
6587 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6588 OpRHS);
6589 }
6590}
6591
6592static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6593 SelectionDAG &DAG) {
6594 // Check to see if we can use the TBL instruction.
6595 SDValue V1 = Op.getOperand(0);
6596 SDValue V2 = Op.getOperand(1);
6597 SDLoc DL(Op);
6598
6599 EVT EltVT = Op.getValueType().getVectorElementType();
6600 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6601
6602 SmallVector<SDValue, 8> TBLMask;
6603 for (int Val : ShuffleMask) {
6604 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6605 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006606 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006607 }
6608 }
6609
6610 MVT IndexVT = MVT::v8i8;
6611 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006612 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006613 IndexVT = MVT::v16i8;
6614 IndexLen = 16;
6615 }
6616
6617 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6618 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6619
6620 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006621 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006622 if (IndexLen == 8)
6623 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6624 Shuffle = DAG.getNode(
6625 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006626 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006627 DAG.getBuildVector(IndexVT, DL,
6628 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006629 } else {
6630 if (IndexLen == 8) {
6631 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6632 Shuffle = DAG.getNode(
6633 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006634 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006635 DAG.getBuildVector(IndexVT, DL,
6636 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006637 } else {
6638 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6639 // cannot currently represent the register constraints on the input
6640 // table registers.
6641 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006642 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6643 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006644 Shuffle = DAG.getNode(
6645 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006646 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6647 V2Cst, DAG.getBuildVector(IndexVT, DL,
6648 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006649 }
6650 }
6651 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6652}
6653
6654static unsigned getDUPLANEOp(EVT EltType) {
6655 if (EltType == MVT::i8)
6656 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006657 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006658 return AArch64ISD::DUPLANE16;
6659 if (EltType == MVT::i32 || EltType == MVT::f32)
6660 return AArch64ISD::DUPLANE32;
6661 if (EltType == MVT::i64 || EltType == MVT::f64)
6662 return AArch64ISD::DUPLANE64;
6663
6664 llvm_unreachable("Invalid vector element type?");
6665}
6666
6667SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6668 SelectionDAG &DAG) const {
6669 SDLoc dl(Op);
6670 EVT VT = Op.getValueType();
6671
6672 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6673
6674 // Convert shuffles that are directly supported on NEON to target-specific
6675 // DAG nodes, instead of keeping them as shuffles and matching them again
6676 // during code selection. This is more efficient and avoids the possibility
6677 // of inconsistencies between legalization and selection.
6678 ArrayRef<int> ShuffleMask = SVN->getMask();
6679
6680 SDValue V1 = Op.getOperand(0);
6681 SDValue V2 = Op.getOperand(1);
6682
Craig Topperbc56e3b2016-06-30 04:38:51 +00006683 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006684 int Lane = SVN->getSplatIndex();
6685 // If this is undef splat, generate it via "just" vdup, if possible.
6686 if (Lane == -1)
6687 Lane = 0;
6688
6689 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6690 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6691 V1.getOperand(0));
6692 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6693 // constant. If so, we can just reference the lane's definition directly.
6694 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6695 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6696 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6697
6698 // Otherwise, duplicate from the lane of the input vector.
6699 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6700
6701 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6702 // to make a vector of the same size as this SHUFFLE. We can ignore the
6703 // extract entirely, and canonicalise the concat using WidenVector.
6704 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6705 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6706 V1 = V1.getOperand(0);
6707 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6708 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6709 Lane -= Idx * VT.getVectorNumElements() / 2;
6710 V1 = WidenVector(V1.getOperand(Idx), DAG);
6711 } else if (VT.getSizeInBits() == 64)
6712 V1 = WidenVector(V1, DAG);
6713
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006714 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006715 }
6716
6717 if (isREVMask(ShuffleMask, VT, 64))
6718 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6719 if (isREVMask(ShuffleMask, VT, 32))
6720 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6721 if (isREVMask(ShuffleMask, VT, 16))
6722 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6723
6724 bool ReverseEXT = false;
6725 unsigned Imm;
6726 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6727 if (ReverseEXT)
6728 std::swap(V1, V2);
6729 Imm *= getExtFactor(V1);
6730 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006731 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006732 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006733 Imm *= getExtFactor(V1);
6734 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006735 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006736 }
6737
6738 unsigned WhichResult;
6739 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6740 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6741 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6742 }
6743 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6744 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6745 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6746 }
6747 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6748 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6749 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6750 }
6751
6752 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6753 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6754 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6755 }
6756 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6757 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6758 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6759 }
6760 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6761 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6762 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6763 }
6764
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006765 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006766 return Concat;
6767
6768 bool DstIsLeft;
6769 int Anomaly;
6770 int NumInputElements = V1.getValueType().getVectorNumElements();
6771 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6772 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006773 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006774
6775 SDValue SrcVec = V1;
6776 int SrcLane = ShuffleMask[Anomaly];
6777 if (SrcLane >= NumInputElements) {
6778 SrcVec = V2;
6779 SrcLane -= VT.getVectorNumElements();
6780 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006781 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006782
6783 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006784
6785 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006786 ScalarVT = MVT::i32;
6787
6788 return DAG.getNode(
6789 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6790 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6791 DstLaneV);
6792 }
6793
6794 // If the shuffle is not directly supported and it has 4 elements, use
6795 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6796 unsigned NumElts = VT.getVectorNumElements();
6797 if (NumElts == 4) {
6798 unsigned PFIndexes[4];
6799 for (unsigned i = 0; i != 4; ++i) {
6800 if (ShuffleMask[i] < 0)
6801 PFIndexes[i] = 8;
6802 else
6803 PFIndexes[i] = ShuffleMask[i];
6804 }
6805
6806 // Compute the index in the perfect shuffle table.
6807 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6808 PFIndexes[2] * 9 + PFIndexes[3];
6809 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6810 unsigned Cost = (PFEntry >> 30);
6811
6812 if (Cost <= 4)
6813 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6814 }
6815
6816 return GenerateTBL(Op, ShuffleMask, DAG);
6817}
6818
6819static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6820 APInt &UndefBits) {
6821 EVT VT = BVN->getValueType(0);
6822 APInt SplatBits, SplatUndef;
6823 unsigned SplatBitSize;
6824 bool HasAnyUndefs;
6825 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6826 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6827
6828 for (unsigned i = 0; i < NumSplats; ++i) {
6829 CnstBits <<= SplatBitSize;
6830 UndefBits <<= SplatBitSize;
6831 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6832 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6833 }
6834
6835 return true;
6836 }
6837
6838 return false;
6839}
6840
Evandro Menezes72f39832018-02-20 20:31:45 +00006841// Try 64-bit splatted SIMD immediate.
6842static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6843 const APInt &Bits) {
6844 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6845 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6846 EVT VT = Op.getValueType();
6847 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6848
6849 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6850 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6851
6852 SDLoc dl(Op);
6853 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6854 DAG.getConstant(Value, dl, MVT::i32));
6855 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6856 }
6857 }
6858
6859 return SDValue();
6860}
6861
6862// Try 32-bit splatted SIMD immediate.
6863static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6864 const APInt &Bits,
6865 const SDValue *LHS = nullptr) {
6866 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6867 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6868 EVT VT = Op.getValueType();
6869 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6870 bool isAdvSIMDModImm = false;
6871 uint64_t Shift;
6872
6873 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6874 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6875 Shift = 0;
6876 }
6877 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6878 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6879 Shift = 8;
6880 }
6881 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6882 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6883 Shift = 16;
6884 }
6885 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6886 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6887 Shift = 24;
6888 }
6889
6890 if (isAdvSIMDModImm) {
6891 SDLoc dl(Op);
6892 SDValue Mov;
6893
6894 if (LHS)
6895 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6896 DAG.getConstant(Value, dl, MVT::i32),
6897 DAG.getConstant(Shift, dl, MVT::i32));
6898 else
6899 Mov = DAG.getNode(NewOp, dl, MovTy,
6900 DAG.getConstant(Value, dl, MVT::i32),
6901 DAG.getConstant(Shift, dl, MVT::i32));
6902
6903 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6904 }
6905 }
6906
6907 return SDValue();
6908}
6909
6910// Try 16-bit splatted SIMD immediate.
6911static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6912 const APInt &Bits,
6913 const SDValue *LHS = nullptr) {
6914 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6915 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6916 EVT VT = Op.getValueType();
6917 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6918 bool isAdvSIMDModImm = false;
6919 uint64_t Shift;
6920
6921 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6922 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6923 Shift = 0;
6924 }
6925 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6926 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6927 Shift = 8;
6928 }
6929
6930 if (isAdvSIMDModImm) {
6931 SDLoc dl(Op);
6932 SDValue Mov;
6933
6934 if (LHS)
6935 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006936 DAG.getConstant(Value, dl, MVT::i32),
6937 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006938 else
6939 Mov = DAG.getNode(NewOp, dl, MovTy,
6940 DAG.getConstant(Value, dl, MVT::i32),
6941 DAG.getConstant(Shift, dl, MVT::i32));
6942
6943 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6944 }
6945 }
6946
6947 return SDValue();
6948}
6949
6950// Try 32-bit splatted SIMD immediate with shifted ones.
6951static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6952 SelectionDAG &DAG, const APInt &Bits) {
6953 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6954 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6955 EVT VT = Op.getValueType();
6956 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6957 bool isAdvSIMDModImm = false;
6958 uint64_t Shift;
6959
6960 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6961 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6962 Shift = 264;
6963 }
6964 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6965 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6966 Shift = 272;
6967 }
6968
6969 if (isAdvSIMDModImm) {
6970 SDLoc dl(Op);
6971 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6972 DAG.getConstant(Value, dl, MVT::i32),
6973 DAG.getConstant(Shift, dl, MVT::i32));
6974 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6975 }
6976 }
6977
6978 return SDValue();
6979}
6980
6981// Try 8-bit splatted SIMD immediate.
6982static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6983 const APInt &Bits) {
6984 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6985 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6986 EVT VT = Op.getValueType();
6987 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6988
6989 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6990 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6991
6992 SDLoc dl(Op);
6993 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6994 DAG.getConstant(Value, dl, MVT::i32));
6995 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6996 }
6997 }
6998
6999 return SDValue();
7000}
7001
7002// Try FP splatted SIMD immediate.
7003static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7004 const APInt &Bits) {
7005 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7006 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7007 EVT VT = Op.getValueType();
7008 bool isWide = (VT.getSizeInBits() == 128);
7009 MVT MovTy;
7010 bool isAdvSIMDModImm = false;
7011
7012 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7013 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7014 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7015 }
7016 else if (isWide &&
7017 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7018 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7019 MovTy = MVT::v2f64;
7020 }
7021
7022 if (isAdvSIMDModImm) {
7023 SDLoc dl(Op);
7024 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7025 DAG.getConstant(Value, dl, MVT::i32));
7026 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7027 }
7028 }
7029
7030 return SDValue();
7031}
7032
Tim Northover3b0846e2014-05-24 12:50:23 +00007033// Specialized code to quickly find if PotentialBVec is a BuildVector that
7034// consists of only the same constant int value, returned in reference arg
7035// ConstVal
7036static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7037 uint64_t &ConstVal) {
7038 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7039 if (!Bvec)
7040 return false;
7041 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7042 if (!FirstElt)
7043 return false;
7044 EVT VT = Bvec->getValueType(0);
7045 unsigned NumElts = VT.getVectorNumElements();
7046 for (unsigned i = 1; i < NumElts; ++i)
7047 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7048 return false;
7049 ConstVal = FirstElt->getZExtValue();
7050 return true;
7051}
7052
7053static unsigned getIntrinsicID(const SDNode *N) {
7054 unsigned Opcode = N->getOpcode();
7055 switch (Opcode) {
7056 default:
7057 return Intrinsic::not_intrinsic;
7058 case ISD::INTRINSIC_WO_CHAIN: {
7059 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7060 if (IID < Intrinsic::num_intrinsics)
7061 return IID;
7062 return Intrinsic::not_intrinsic;
7063 }
7064 }
7065}
7066
7067// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7068// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7069// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7070// Also, logical shift right -> sri, with the same structure.
7071static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7072 EVT VT = N->getValueType(0);
7073
7074 if (!VT.isVector())
7075 return SDValue();
7076
7077 SDLoc DL(N);
7078
7079 // Is the first op an AND?
7080 const SDValue And = N->getOperand(0);
7081 if (And.getOpcode() != ISD::AND)
7082 return SDValue();
7083
7084 // Is the second op an shl or lshr?
7085 SDValue Shift = N->getOperand(1);
7086 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7087 // or AArch64ISD::VLSHR vector, #shift
7088 unsigned ShiftOpc = Shift.getOpcode();
7089 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7090 return SDValue();
7091 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7092
7093 // Is the shift amount constant?
7094 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7095 if (!C2node)
7096 return SDValue();
7097
7098 // Is the and mask vector all constant?
7099 uint64_t C1;
7100 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7101 return SDValue();
7102
7103 // Is C1 == ~C2, taking into account how much one can shift elements of a
7104 // particular size?
7105 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007106 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007107 if (C2 > ElemSizeInBits)
7108 return SDValue();
7109 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7110 if ((C1 & ElemMask) != (~C2 & ElemMask))
7111 return SDValue();
7112
7113 SDValue X = And.getOperand(0);
7114 SDValue Y = Shift.getOperand(0);
7115
7116 unsigned Intrin =
7117 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7118 SDValue ResultSLI =
7119 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007120 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7121 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007122
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007123 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7124 LLVM_DEBUG(N->dump(&DAG));
7125 LLVM_DEBUG(dbgs() << "into: \n");
7126 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007127
7128 ++NumShiftInserts;
7129 return ResultSLI;
7130}
7131
7132SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7133 SelectionDAG &DAG) const {
7134 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7135 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007136 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007137 return Res;
7138 }
7139
Tim Northover3b0846e2014-05-24 12:50:23 +00007140 EVT VT = Op.getValueType();
7141
Evandro Menezescd855f72018-03-05 17:02:47 +00007142 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007143 BuildVectorSDNode *BVN =
7144 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007145 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007146 // OR commutes, so try swapping the operands.
7147 LHS = Op.getOperand(1);
7148 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007149 }
7150 if (!BVN)
7151 return Op;
7152
Evandro Menezes72f39832018-02-20 20:31:45 +00007153 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007154 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007155 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7156 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007157
Evandro Menezes72f39832018-02-20 20:31:45 +00007158 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7159 DefBits, &LHS)) ||
7160 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7161 DefBits, &LHS)))
7162 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007163
7164 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7165 UndefBits, &LHS)) ||
7166 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7167 UndefBits, &LHS)))
7168 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007169 }
7170
Evandro Menezes72f39832018-02-20 20:31:45 +00007171 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007172 return Op;
7173}
7174
Kevin Qin4473c192014-07-07 02:45:40 +00007175// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7176// be truncated to fit element width.
7177static SDValue NormalizeBuildVector(SDValue Op,
7178 SelectionDAG &DAG) {
7179 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007180 SDLoc dl(Op);
7181 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007182 EVT EltTy= VT.getVectorElementType();
7183
7184 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7185 return Op;
7186
7187 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007188 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007189 // For integer vectors, type legalization would have promoted the
7190 // operands already. Otherwise, if Op is a floating-point splat
7191 // (with operands cast to integers), then the only possibilities
7192 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007193 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007194 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007195 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007196 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007197 } else if (Lane.getNode()->isUndef()) {
7198 Lane = DAG.getUNDEF(MVT::i32);
7199 } else {
7200 assert(Lane.getValueType() == MVT::i32 &&
7201 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007202 }
7203 Ops.push_back(Lane);
7204 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007205 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007206}
7207
Evandro Menezescd855f72018-03-05 17:02:47 +00007208static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007209 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007210
Evandro Menezes72f39832018-02-20 20:31:45 +00007211 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007212 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007213 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007214 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007215 SDValue NewOp;
7216 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7217 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7218 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7219 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7220 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7221 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7222 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007223
Evandro Menezes72f39832018-02-20 20:31:45 +00007224 DefBits = ~DefBits;
7225 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7226 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7227 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7228 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007229
Evandro Menezes72f39832018-02-20 20:31:45 +00007230 DefBits = UndefBits;
7231 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7232 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7233 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7234 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7235 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7236 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7237 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007238
Evandro Menezes72f39832018-02-20 20:31:45 +00007239 DefBits = ~UndefBits;
7240 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7241 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7242 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7243 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007244 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007245
Evandro Menezescd855f72018-03-05 17:02:47 +00007246 return SDValue();
7247}
7248
7249SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7250 SelectionDAG &DAG) const {
7251 EVT VT = Op.getValueType();
7252
7253 // Try to build a simple constant vector.
7254 Op = NormalizeBuildVector(Op, DAG);
7255 if (VT.isInteger()) {
7256 // Certain vector constants, used to express things like logical NOT and
7257 // arithmetic NEG, are passed through unmodified. This allows special
7258 // patterns for these operations to match, which will lower these constants
7259 // to whatever is proven necessary.
7260 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7261 if (BVN->isConstant())
7262 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7263 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7264 APInt Val(BitSize,
7265 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7266 if (Val.isNullValue() || Val.isAllOnesValue())
7267 return Op;
7268 }
7269 }
7270
7271 if (SDValue V = ConstantBuildVector(Op, DAG))
7272 return V;
7273
Tim Northover3b0846e2014-05-24 12:50:23 +00007274 // Scan through the operands to find some interesting properties we can
7275 // exploit:
7276 // 1) If only one value is used, we can use a DUP, or
7277 // 2) if only the low element is not undef, we can just insert that, or
7278 // 3) if only one constant value is used (w/ some non-constant lanes),
7279 // we can splat the constant value into the whole vector then fill
7280 // in the non-constant lanes.
7281 // 4) FIXME: If different constant values are used, but we can intelligently
7282 // select the values we'll be overwriting for the non-constant
7283 // lanes such that we can directly materialize the vector
7284 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007285 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007286 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007287 unsigned NumElts = VT.getVectorNumElements();
7288 bool isOnlyLowElement = true;
7289 bool usesOnlyOneValue = true;
7290 bool usesOnlyOneConstantValue = true;
7291 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007292 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007293 unsigned NumConstantLanes = 0;
7294 SDValue Value;
7295 SDValue ConstantValue;
7296 for (unsigned i = 0; i < NumElts; ++i) {
7297 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007298 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7299 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007300 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007301 continue;
7302 if (i > 0)
7303 isOnlyLowElement = false;
7304 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7305 isConstant = false;
7306
7307 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7308 ++NumConstantLanes;
7309 if (!ConstantValue.getNode())
7310 ConstantValue = V;
7311 else if (ConstantValue != V)
7312 usesOnlyOneConstantValue = false;
7313 }
7314
7315 if (!Value.getNode())
7316 Value = V;
7317 else if (V != Value)
7318 usesOnlyOneValue = false;
7319 }
7320
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007321 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007322 LLVM_DEBUG(
7323 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007324 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007325 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007326
John Brawnd6e0ebe2018-11-22 11:45:23 +00007327 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7328 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7329 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7330 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007331 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7332 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007333 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007334 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007335
Sebastian Popc33af712018-03-01 15:47:39 +00007336 if (AllLanesExtractElt) {
7337 SDNode *Vector = nullptr;
7338 bool Even = false;
7339 bool Odd = false;
7340 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7341 // the Odd pattern <1,3,5,...>.
7342 for (unsigned i = 0; i < NumElts; ++i) {
7343 SDValue V = Op.getOperand(i);
7344 const SDNode *N = V.getNode();
7345 if (!isa<ConstantSDNode>(N->getOperand(1)))
7346 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007347 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007348
7349 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007350 if (!Vector) {
7351 Vector = N0.getNode();
7352 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7353 // BUILD_VECTOR.
7354 if (VT.getVectorElementType() !=
7355 N0.getValueType().getVectorElementType())
7356 break;
7357 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007358 Odd = false;
7359 Even = false;
7360 break;
7361 }
7362
7363 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7364 // indices <1,3,5,...>.
7365 uint64_t Val = N->getConstantOperandVal(1);
7366 if (Val == 2 * i) {
7367 Even = true;
7368 continue;
7369 }
7370 if (Val - 1 == 2 * i) {
7371 Odd = true;
7372 continue;
7373 }
7374
7375 // Something does not match: abort.
7376 Odd = false;
7377 Even = false;
7378 break;
7379 }
7380 if (Even || Odd) {
7381 SDValue LHS =
7382 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7383 DAG.getConstant(0, dl, MVT::i64));
7384 SDValue RHS =
7385 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7386 DAG.getConstant(NumElts, dl, MVT::i64));
7387
7388 if (Even && !Odd)
7389 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7390 RHS);
7391 if (Odd && !Even)
7392 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7393 RHS);
7394 }
7395 }
7396
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007397 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007398 // i32 and try again.
7399 if (usesOnlyOneValue) {
7400 if (!isConstant) {
7401 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007402 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007403 LLVM_DEBUG(
7404 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007405 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007406 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007407
7408 // This is actually a DUPLANExx operation, which keeps everything vectory.
7409
Tim Northover3b0846e2014-05-24 12:50:23 +00007410 SDValue Lane = Value.getOperand(1);
7411 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007412 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007413 LLVM_DEBUG(
7414 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7415 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007416 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007417 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007418
7419 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7420 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7421 }
7422
7423 if (VT.getVectorElementType().isFloatingPoint()) {
7424 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007425 EVT EltTy = VT.getVectorElementType();
7426 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7427 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007428 LLVM_DEBUG(
7429 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7430 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007431 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007432 for (unsigned i = 0; i < NumElts; ++i)
7433 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7434 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007435 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007436 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7437 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007438 Val = LowerBUILD_VECTOR(Val, DAG);
7439 if (Val.getNode())
7440 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7441 }
7442 }
7443
7444 // If there was only one constant value used and for more than one lane,
7445 // start by splatting that value, then replace the non-constant lanes. This
7446 // is better than the default, which will perform a separate initialization
7447 // for each lane.
7448 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007449 // Firstly, try to materialize the splat constant.
7450 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7451 Val = ConstantBuildVector(Vec, DAG);
7452 if (!Val) {
7453 // Otherwise, materialize the constant and splat it.
7454 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7455 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7456 }
7457
Tim Northover3b0846e2014-05-24 12:50:23 +00007458 // Now insert the non-constant lanes.
7459 for (unsigned i = 0; i < NumElts; ++i) {
7460 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007461 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007462 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007463 // Note that type legalization likely mucked about with the VT of the
7464 // source operand, so we may have to convert it here before inserting.
7465 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007466 }
7467 return Val;
7468 }
7469
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007470 // This will generate a load from the constant pool.
7471 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007472 LLVM_DEBUG(
7473 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7474 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007475 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007476 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007477
7478 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7479 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007480 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007481 return shuffle;
7482 }
7483
7484 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7485 // know the default expansion would otherwise fall back on something even
7486 // worse. For a vector with one or two non-undef values, that's
7487 // scalar_to_vector for the elements followed by a shuffle (provided the
7488 // shuffle is valid for the target) and materialization element by element
7489 // on the stack followed by a load for everything else.
7490 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007491 LLVM_DEBUG(
7492 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7493 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007494
Tim Northover3b0846e2014-05-24 12:50:23 +00007495 SDValue Vec = DAG.getUNDEF(VT);
7496 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007497 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007498
7499 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007500 // a) Avoid a RMW dependency on the full vector register, and
7501 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007502 // value is already in an S or D register, and we're forced to emit an
7503 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007504 //
7505 // We also allow types like i8 and i16 which are illegal scalar but legal
7506 // vector element types. After type-legalization the inserted value is
7507 // extended (i32) and it is safe to cast them to the vector type by ignoring
7508 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7509 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007510 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007511 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007512 ++i;
7513 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007514 LLVM_DEBUG(if (i < NumElts) dbgs()
7515 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007516 for (; i < NumElts; ++i) {
7517 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007518 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007519 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007520 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007521 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7522 }
7523 return Vec;
7524 }
7525
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007526 LLVM_DEBUG(
7527 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7528 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007529 return SDValue();
7530}
7531
7532SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7533 SelectionDAG &DAG) const {
7534 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7535
Tim Northovere4b8e132014-07-15 10:00:26 +00007536 // Check for non-constant or out of range lane.
7537 EVT VT = Op.getOperand(0).getValueType();
7538 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7539 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007540 return SDValue();
7541
Tim Northover3b0846e2014-05-24 12:50:23 +00007542
7543 // Insertion/extraction are legal for V128 types.
7544 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007545 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7546 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007547 return Op;
7548
7549 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007550 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007551 return SDValue();
7552
7553 // For V64 types, we perform insertion by expanding the value
7554 // to a V128 type and perform the insertion on that.
7555 SDLoc DL(Op);
7556 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7557 EVT WideTy = WideVec.getValueType();
7558
7559 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7560 Op.getOperand(1), Op.getOperand(2));
7561 // Re-narrow the resultant vector.
7562 return NarrowVector(Node, DAG);
7563}
7564
7565SDValue
7566AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7567 SelectionDAG &DAG) const {
7568 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7569
Tim Northovere4b8e132014-07-15 10:00:26 +00007570 // Check for non-constant or out of range lane.
7571 EVT VT = Op.getOperand(0).getValueType();
7572 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7573 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007574 return SDValue();
7575
Tim Northover3b0846e2014-05-24 12:50:23 +00007576
7577 // Insertion/extraction are legal for V128 types.
7578 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007579 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7580 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007581 return Op;
7582
7583 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007584 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007585 return SDValue();
7586
7587 // For V64 types, we perform extraction by expanding the value
7588 // to a V128 type and perform the extraction on that.
7589 SDLoc DL(Op);
7590 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7591 EVT WideTy = WideVec.getValueType();
7592
7593 EVT ExtrTy = WideTy.getVectorElementType();
7594 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7595 ExtrTy = MVT::i32;
7596
7597 // For extractions, we just return the result directly.
7598 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7599 Op.getOperand(1));
7600}
7601
7602SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7603 SelectionDAG &DAG) const {
7604 EVT VT = Op.getOperand(0).getValueType();
7605 SDLoc dl(Op);
7606 // Just in case...
7607 if (!VT.isVector())
7608 return SDValue();
7609
7610 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7611 if (!Cst)
7612 return SDValue();
7613 unsigned Val = Cst->getZExtValue();
7614
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007615 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007616
7617 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7618 if (Val == 0)
7619 return Op;
7620
Tim Northover3b0846e2014-05-24 12:50:23 +00007621 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7622 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007623 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007624 return Op;
7625
7626 return SDValue();
7627}
7628
Zvi Rackover1b736822017-07-26 08:06:58 +00007629bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007630 if (VT.getVectorNumElements() == 4 &&
7631 (VT.is128BitVector() || VT.is64BitVector())) {
7632 unsigned PFIndexes[4];
7633 for (unsigned i = 0; i != 4; ++i) {
7634 if (M[i] < 0)
7635 PFIndexes[i] = 8;
7636 else
7637 PFIndexes[i] = M[i];
7638 }
7639
7640 // Compute the index in the perfect shuffle table.
7641 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7642 PFIndexes[2] * 9 + PFIndexes[3];
7643 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7644 unsigned Cost = (PFEntry >> 30);
7645
7646 if (Cost <= 4)
7647 return true;
7648 }
7649
7650 bool DummyBool;
7651 int DummyInt;
7652 unsigned DummyUnsigned;
7653
7654 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7655 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7656 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7657 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7658 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7659 isZIPMask(M, VT, DummyUnsigned) ||
7660 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7661 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7662 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7663 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7664 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7665}
7666
7667/// getVShiftImm - Check if this is a valid build_vector for the immediate
7668/// operand of a vector shift operation, where all the elements of the
7669/// build_vector must have the same constant integer value.
7670static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7671 // Ignore bit_converts.
7672 while (Op.getOpcode() == ISD::BITCAST)
7673 Op = Op.getOperand(0);
7674 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7675 APInt SplatBits, SplatUndef;
7676 unsigned SplatBitSize;
7677 bool HasAnyUndefs;
7678 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7679 HasAnyUndefs, ElementBits) ||
7680 SplatBitSize > ElementBits)
7681 return false;
7682 Cnt = SplatBits.getSExtValue();
7683 return true;
7684}
7685
7686/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7687/// operand of a vector shift left operation. That value must be in the range:
7688/// 0 <= Value < ElementBits for a left shift; or
7689/// 0 <= Value <= ElementBits for a long left shift.
7690static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7691 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007692 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007693 if (!getVShiftImm(Op, ElementBits, Cnt))
7694 return false;
7695 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7696}
7697
7698/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007699/// operand of a vector shift right operation. The value must be in the range:
7700/// 1 <= Value <= ElementBits for a right shift; or
7701static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007702 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007703 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007704 if (!getVShiftImm(Op, ElementBits, Cnt))
7705 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007706 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7707}
7708
7709SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7710 SelectionDAG &DAG) const {
7711 EVT VT = Op.getValueType();
7712 SDLoc DL(Op);
7713 int64_t Cnt;
7714
7715 if (!Op.getOperand(1).getValueType().isVector())
7716 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007717 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007718
7719 switch (Op.getOpcode()) {
7720 default:
7721 llvm_unreachable("unexpected shift opcode");
7722
7723 case ISD::SHL:
7724 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007725 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7726 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007727 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007728 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7729 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007730 Op.getOperand(0), Op.getOperand(1));
7731 case ISD::SRA:
7732 case ISD::SRL:
7733 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007734 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007735 unsigned Opc =
7736 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007737 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7738 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007739 }
7740
7741 // Right shift register. Note, there is not a shift right register
7742 // instruction, but the shift left register instruction takes a signed
7743 // value, where negative numbers specify a right shift.
7744 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7745 : Intrinsic::aarch64_neon_ushl;
7746 // negate the shift amount
7747 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7748 SDValue NegShiftLeft =
7749 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007750 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7751 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007752 return NegShiftLeft;
7753 }
7754
7755 return SDValue();
7756}
7757
7758static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7759 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007760 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007761 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007762 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7763 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007764
7765 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7766 APInt CnstBits(VT.getSizeInBits(), 0);
7767 APInt UndefBits(VT.getSizeInBits(), 0);
7768 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7769 bool IsZero = IsCnst && (CnstBits == 0);
7770
7771 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7772 switch (CC) {
7773 default:
7774 return SDValue();
7775 case AArch64CC::NE: {
7776 SDValue Fcmeq;
7777 if (IsZero)
7778 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7779 else
7780 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7781 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7782 }
7783 case AArch64CC::EQ:
7784 if (IsZero)
7785 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7786 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7787 case AArch64CC::GE:
7788 if (IsZero)
7789 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7790 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7791 case AArch64CC::GT:
7792 if (IsZero)
7793 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7794 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7795 case AArch64CC::LS:
7796 if (IsZero)
7797 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7798 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7799 case AArch64CC::LT:
7800 if (!NoNans)
7801 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007802 // If we ignore NaNs then we can use to the MI implementation.
7803 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007804 case AArch64CC::MI:
7805 if (IsZero)
7806 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7807 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7808 }
7809 }
7810
7811 switch (CC) {
7812 default:
7813 return SDValue();
7814 case AArch64CC::NE: {
7815 SDValue Cmeq;
7816 if (IsZero)
7817 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7818 else
7819 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7820 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7821 }
7822 case AArch64CC::EQ:
7823 if (IsZero)
7824 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7825 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7826 case AArch64CC::GE:
7827 if (IsZero)
7828 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7829 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7830 case AArch64CC::GT:
7831 if (IsZero)
7832 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7833 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7834 case AArch64CC::LE:
7835 if (IsZero)
7836 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7837 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7838 case AArch64CC::LS:
7839 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7840 case AArch64CC::LO:
7841 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7842 case AArch64CC::LT:
7843 if (IsZero)
7844 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7845 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7846 case AArch64CC::HI:
7847 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7848 case AArch64CC::HS:
7849 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7850 }
7851}
7852
7853SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7854 SelectionDAG &DAG) const {
7855 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7856 SDValue LHS = Op.getOperand(0);
7857 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007858 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007859 SDLoc dl(Op);
7860
7861 if (LHS.getValueType().getVectorElementType().isInteger()) {
7862 assert(LHS.getValueType() == RHS.getValueType());
7863 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007864 SDValue Cmp =
7865 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7866 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007867 }
7868
Carey Williamsda15b5b2018-01-22 14:16:11 +00007869 const bool FullFP16 =
7870 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7871
7872 // Make v4f16 (only) fcmp operations utilise vector instructions
7873 // v8f16 support will be a litle more complicated
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007874 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7875 if (LHS.getValueType().getVectorNumElements() == 4) {
Carey Williamsda15b5b2018-01-22 14:16:11 +00007876 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7877 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7878 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7879 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7880 CmpVT = MVT::v4i32;
7881 } else
7882 return SDValue();
7883 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007884
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007885 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7886 LHS.getValueType().getVectorElementType() != MVT::f128);
Tim Northover3b0846e2014-05-24 12:50:23 +00007887
7888 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7889 // clean. Some of them require two branches to implement.
7890 AArch64CC::CondCode CC1, CC2;
7891 bool ShouldInvert;
7892 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7893
7894 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7895 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007896 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007897 if (!Cmp.getNode())
7898 return SDValue();
7899
7900 if (CC2 != AArch64CC::AL) {
7901 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007902 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007903 if (!Cmp2.getNode())
7904 return SDValue();
7905
Tim Northover45aa89c2015-02-08 00:50:47 +00007906 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007907 }
7908
Tim Northover45aa89c2015-02-08 00:50:47 +00007909 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7910
Tim Northover3b0846e2014-05-24 12:50:23 +00007911 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007912 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007913
7914 return Cmp;
7915}
7916
Amara Emersonc9916d72017-05-16 21:29:22 +00007917static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7918 SelectionDAG &DAG) {
7919 SDValue VecOp = ScalarOp.getOperand(0);
7920 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7921 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7922 DAG.getConstant(0, DL, MVT::i64));
7923}
7924
7925SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7926 SelectionDAG &DAG) const {
7927 SDLoc dl(Op);
7928 switch (Op.getOpcode()) {
7929 case ISD::VECREDUCE_ADD:
7930 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7931 case ISD::VECREDUCE_SMAX:
7932 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7933 case ISD::VECREDUCE_SMIN:
7934 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7935 case ISD::VECREDUCE_UMAX:
7936 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7937 case ISD::VECREDUCE_UMIN:
7938 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7939 case ISD::VECREDUCE_FMAX: {
7940 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7941 return DAG.getNode(
7942 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7943 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7944 Op.getOperand(0));
7945 }
7946 case ISD::VECREDUCE_FMIN: {
7947 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7948 return DAG.getNode(
7949 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7950 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7951 Op.getOperand(0));
7952 }
7953 default:
7954 llvm_unreachable("Unhandled reduction");
7955 }
7956}
7957
Oliver Stannard42699172018-02-12 14:22:03 +00007958SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7959 SelectionDAG &DAG) const {
7960 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7961 if (!Subtarget.hasLSE())
7962 return SDValue();
7963
7964 // LSE has an atomic load-add instruction, but not a load-sub.
7965 SDLoc dl(Op);
7966 MVT VT = Op.getSimpleValueType();
7967 SDValue RHS = Op.getOperand(2);
7968 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7969 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7970 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7971 Op.getOperand(0), Op.getOperand(1), RHS,
7972 AN->getMemOperand());
7973}
7974
Oliver Stannard02f08c92018-02-12 17:03:11 +00007975SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7976 SelectionDAG &DAG) const {
7977 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7978 if (!Subtarget.hasLSE())
7979 return SDValue();
7980
7981 // LSE has an atomic load-clear instruction, but not a load-and.
7982 SDLoc dl(Op);
7983 MVT VT = Op.getSimpleValueType();
7984 SDValue RHS = Op.getOperand(2);
7985 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7986 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7987 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7988 Op.getOperand(0), Op.getOperand(1), RHS,
7989 AN->getMemOperand());
7990}
7991
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007992SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7993 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7994 SDLoc dl(Op);
7995 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7996 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7997
Tri Vo6c47c622018-09-22 22:17:50 +00007998 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7999 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8000 if (Subtarget->hasCustomCallingConv())
8001 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008002
8003 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8004 DAG.getConstant(4, dl, MVT::i64));
8005 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8006 Chain =
8007 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8008 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8009 DAG.getRegisterMask(Mask), Chain.getValue(1));
8010 // To match the actual intent better, we should read the output from X15 here
8011 // again (instead of potentially spilling it to the stack), but rereading Size
8012 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8013 // here.
8014
8015 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8016 DAG.getConstant(4, dl, MVT::i64));
8017 return Chain;
8018}
8019
8020SDValue
8021AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8022 SelectionDAG &DAG) const {
8023 assert(Subtarget->isTargetWindows() &&
8024 "Only Windows alloca probing supported");
8025 SDLoc dl(Op);
8026 // Get the inputs.
8027 SDNode *Node = Op.getNode();
8028 SDValue Chain = Op.getOperand(0);
8029 SDValue Size = Op.getOperand(1);
8030 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8031 EVT VT = Node->getValueType(0);
8032
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00008033 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8034 "no-stack-arg-probe")) {
8035 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8036 Chain = SP.getValue(1);
8037 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8038 if (Align)
8039 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8040 DAG.getConstant(-(uint64_t)Align, dl, VT));
8041 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8042 SDValue Ops[2] = {SP, Chain};
8043 return DAG.getMergeValues(Ops, dl);
8044 }
8045
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008046 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8047
8048 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8049
8050 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8051 Chain = SP.getValue(1);
8052 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00008053 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008054 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8055 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00008056 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008057
8058 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8059 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8060
8061 SDValue Ops[2] = {SP, Chain};
8062 return DAG.getMergeValues(Ops, dl);
8063}
8064
Tim Northover3b0846e2014-05-24 12:50:23 +00008065/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8066/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8067/// specified in the intrinsic calls.
8068bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8069 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00008070 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00008071 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008072 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00008073 switch (Intrinsic) {
8074 case Intrinsic::aarch64_neon_ld2:
8075 case Intrinsic::aarch64_neon_ld3:
8076 case Intrinsic::aarch64_neon_ld4:
8077 case Intrinsic::aarch64_neon_ld1x2:
8078 case Intrinsic::aarch64_neon_ld1x3:
8079 case Intrinsic::aarch64_neon_ld1x4:
8080 case Intrinsic::aarch64_neon_ld2lane:
8081 case Intrinsic::aarch64_neon_ld3lane:
8082 case Intrinsic::aarch64_neon_ld4lane:
8083 case Intrinsic::aarch64_neon_ld2r:
8084 case Intrinsic::aarch64_neon_ld3r:
8085 case Intrinsic::aarch64_neon_ld4r: {
8086 Info.opc = ISD::INTRINSIC_W_CHAIN;
8087 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008088 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008089 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8090 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8091 Info.offset = 0;
8092 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008093 // volatile loads with NEON intrinsics not supported
8094 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008095 return true;
8096 }
8097 case Intrinsic::aarch64_neon_st2:
8098 case Intrinsic::aarch64_neon_st3:
8099 case Intrinsic::aarch64_neon_st4:
8100 case Intrinsic::aarch64_neon_st1x2:
8101 case Intrinsic::aarch64_neon_st1x3:
8102 case Intrinsic::aarch64_neon_st1x4:
8103 case Intrinsic::aarch64_neon_st2lane:
8104 case Intrinsic::aarch64_neon_st3lane:
8105 case Intrinsic::aarch64_neon_st4lane: {
8106 Info.opc = ISD::INTRINSIC_VOID;
8107 // Conservatively set memVT to the entire set of vectors stored.
8108 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008109 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008110 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8111 if (!ArgTy->isVectorTy())
8112 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008113 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008114 }
8115 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8116 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8117 Info.offset = 0;
8118 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008119 // volatile stores with NEON intrinsics not supported
8120 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008121 return true;
8122 }
8123 case Intrinsic::aarch64_ldaxr:
8124 case Intrinsic::aarch64_ldxr: {
8125 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8126 Info.opc = ISD::INTRINSIC_W_CHAIN;
8127 Info.memVT = MVT::getVT(PtrTy->getElementType());
8128 Info.ptrVal = I.getArgOperand(0);
8129 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008130 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008131 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008132 return true;
8133 }
8134 case Intrinsic::aarch64_stlxr:
8135 case Intrinsic::aarch64_stxr: {
8136 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8137 Info.opc = ISD::INTRINSIC_W_CHAIN;
8138 Info.memVT = MVT::getVT(PtrTy->getElementType());
8139 Info.ptrVal = I.getArgOperand(1);
8140 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008141 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008142 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008143 return true;
8144 }
8145 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008146 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008147 Info.opc = ISD::INTRINSIC_W_CHAIN;
8148 Info.memVT = MVT::i128;
8149 Info.ptrVal = I.getArgOperand(0);
8150 Info.offset = 0;
8151 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008152 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008153 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008154 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008155 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008156 Info.opc = ISD::INTRINSIC_W_CHAIN;
8157 Info.memVT = MVT::i128;
8158 Info.ptrVal = I.getArgOperand(2);
8159 Info.offset = 0;
8160 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008161 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008162 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008163 default:
8164 break;
8165 }
8166
8167 return false;
8168}
8169
John Brawne3b44f92018-03-23 14:47:07 +00008170bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8171 ISD::LoadExtType ExtTy,
8172 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008173 // TODO: This may be worth removing. Check regression tests for diffs.
8174 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8175 return false;
8176
John Brawne3b44f92018-03-23 14:47:07 +00008177 // If we're reducing the load width in order to avoid having to use an extra
8178 // instruction to do extension then it's probably a good idea.
8179 if (ExtTy != ISD::NON_EXTLOAD)
8180 return true;
8181 // Don't reduce load width if it would prevent us from combining a shift into
8182 // the offset.
8183 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8184 assert(Mem);
8185 const SDValue &Base = Mem->getBasePtr();
8186 if (Base.getOpcode() == ISD::ADD &&
8187 Base.getOperand(1).getOpcode() == ISD::SHL &&
8188 Base.getOperand(1).hasOneUse() &&
8189 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8190 // The shift can be combined if it matches the size of the value being
8191 // loaded (and so reducing the width would make it not match).
8192 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8193 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8194 if (ShiftAmount == Log2_32(LoadBytes))
8195 return false;
8196 }
8197 // We have no reason to disallow reducing the load width, so allow it.
8198 return true;
8199}
8200
Tim Northover3b0846e2014-05-24 12:50:23 +00008201// Truncations from 64-bit GPR to 32-bit GPR is free.
8202bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8203 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8204 return false;
8205 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8206 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008207 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008208}
8209bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008210 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008211 return false;
8212 unsigned NumBits1 = VT1.getSizeInBits();
8213 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008214 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008215}
8216
Chad Rosier54390052015-02-23 19:15:16 +00008217/// Check if it is profitable to hoist instruction in then/else to if.
8218/// Not profitable if I and it's user can form a FMA instruction
8219/// because we prefer FMSUB/FMADD.
8220bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8221 if (I->getOpcode() != Instruction::FMul)
8222 return true;
8223
Davide Italiano3e9986f2017-04-18 00:29:54 +00008224 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008225 return true;
8226
8227 Instruction *User = I->user_back();
8228
8229 if (User &&
8230 !(User->getOpcode() == Instruction::FSub ||
8231 User->getOpcode() == Instruction::FAdd))
8232 return true;
8233
8234 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008235 const DataLayout &DL = I->getModule()->getDataLayout();
8236 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008237
Eric Christopher114fa1c2016-02-29 22:50:49 +00008238 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8239 isOperationLegalOrCustom(ISD::FMA, VT) &&
8240 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8241 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008242}
8243
Tim Northover3b0846e2014-05-24 12:50:23 +00008244// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8245// 64-bit GPR.
8246bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8247 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8248 return false;
8249 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8250 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008251 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008252}
8253bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008254 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008255 return false;
8256 unsigned NumBits1 = VT1.getSizeInBits();
8257 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008258 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008259}
8260
8261bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8262 EVT VT1 = Val.getValueType();
8263 if (isZExtFree(VT1, VT2)) {
8264 return true;
8265 }
8266
8267 if (Val.getOpcode() != ISD::LOAD)
8268 return false;
8269
8270 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008271 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8272 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8273 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008274}
8275
Quentin Colombet6843ac42015-03-31 20:52:32 +00008276bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8277 if (isa<FPExtInst>(Ext))
8278 return false;
8279
Haicheng Wu50692a22017-08-01 21:26:45 +00008280 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008281 if (Ext->getType()->isVectorTy())
8282 return false;
8283
8284 for (const Use &U : Ext->uses()) {
8285 // The extension is free if we can fold it with a left shift in an
8286 // addressing mode or an arithmetic operation: add, sub, and cmp.
8287
8288 // Is there a shift?
8289 const Instruction *Instr = cast<Instruction>(U.getUser());
8290
8291 // Is this a constant shift?
8292 switch (Instr->getOpcode()) {
8293 case Instruction::Shl:
8294 if (!isa<ConstantInt>(Instr->getOperand(1)))
8295 return false;
8296 break;
8297 case Instruction::GetElementPtr: {
8298 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008299 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008300 std::advance(GTI, U.getOperandNo()-1);
8301 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008302 // This extension will end up with a shift because of the scaling factor.
8303 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8304 // Get the shift amount based on the scaling factor:
8305 // log2(sizeof(IdxTy)) - log2(8).
8306 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008307 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008308 // Is the constant foldable in the shift of the addressing mode?
8309 // I.e., shift amount is between 1 and 4 inclusive.
8310 if (ShiftAmt == 0 || ShiftAmt > 4)
8311 return false;
8312 break;
8313 }
8314 case Instruction::Trunc:
8315 // Check if this is a noop.
8316 // trunc(sext ty1 to ty2) to ty1.
8317 if (Instr->getType() == Ext->getOperand(0)->getType())
8318 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008319 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008320 default:
8321 return false;
8322 }
8323
8324 // At this point we can use the bfm family, so this extension is free
8325 // for that use.
8326 }
8327 return true;
8328}
8329
Florian Hahn3b251962019-02-05 10:27:40 +00008330/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8331/// or upper half of the vector elements.
8332static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8333 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8334 auto *FullVT = cast<VectorType>(FullV->getType());
8335 auto *HalfVT = cast<VectorType>(HalfV->getType());
8336 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8337 };
8338
8339 auto extractHalf = [](Value *FullV, Value *HalfV) {
8340 auto *FullVT = cast<VectorType>(FullV->getType());
8341 auto *HalfVT = cast<VectorType>(HalfV->getType());
8342 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8343 };
8344
8345 Constant *M1, *M2;
8346 Value *S1Op1, *S2Op1;
8347 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8348 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8349 return false;
8350
8351 // Check that the operands are half as wide as the result and we extract
8352 // half of the elements of the input vectors.
8353 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8354 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8355 return false;
8356
8357 // Check the mask extracts either the lower or upper half of vector
8358 // elements.
8359 int M1Start = -1;
8360 int M2Start = -1;
8361 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8362 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8363 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8364 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8365 return false;
8366
8367 return true;
8368}
8369
8370/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8371/// of the vector elements.
8372static bool areExtractExts(Value *Ext1, Value *Ext2) {
8373 auto areExtDoubled = [](Instruction *Ext) {
8374 return Ext->getType()->getScalarSizeInBits() ==
8375 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8376 };
8377
8378 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8379 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8380 !areExtDoubled(cast<Instruction>(Ext1)) ||
8381 !areExtDoubled(cast<Instruction>(Ext2)))
8382 return false;
8383
8384 return true;
8385}
8386
8387/// Check if sinking \p I's operands to I's basic block is profitable, because
8388/// the operands can be folded into a target instruction, e.g.
8389/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8390bool AArch64TargetLowering::shouldSinkOperands(
8391 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8392 if (!I->getType()->isVectorTy())
8393 return false;
8394
8395 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8396 switch (II->getIntrinsicID()) {
8397 case Intrinsic::aarch64_neon_umull:
8398 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8399 return false;
8400 Ops.push_back(&II->getOperandUse(0));
8401 Ops.push_back(&II->getOperandUse(1));
8402 return true;
8403 default:
8404 return false;
8405 }
8406 }
8407
8408 switch (I->getOpcode()) {
8409 case Instruction::Sub:
8410 case Instruction::Add: {
8411 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8412 return false;
8413
8414 // If the exts' operands extract either the lower or upper elements, we
8415 // can sink them too.
8416 auto Ext1 = cast<Instruction>(I->getOperand(0));
8417 auto Ext2 = cast<Instruction>(I->getOperand(1));
8418 if (areExtractShuffleVectors(Ext1, Ext2)) {
8419 Ops.push_back(&Ext1->getOperandUse(0));
8420 Ops.push_back(&Ext2->getOperandUse(0));
8421 }
8422
8423 Ops.push_back(&I->getOperandUse(0));
8424 Ops.push_back(&I->getOperandUse(1));
8425
8426 return true;
8427 }
8428 default:
8429 return false;
8430 }
8431 return false;
8432}
8433
Tim Northover3b0846e2014-05-24 12:50:23 +00008434bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8435 unsigned &RequiredAligment) const {
8436 if (!LoadedType.isSimple() ||
8437 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8438 return false;
8439 // Cyclone supports unaligned accesses.
8440 RequiredAligment = 0;
8441 unsigned NumBits = LoadedType.getSizeInBits();
8442 return NumBits == 32 || NumBits == 64;
8443}
8444
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008445/// A helper function for determining the number of interleaved accesses we
8446/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008447unsigned
8448AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8449 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008450 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8451}
8452
Geoff Berryb1e87142017-07-14 21:44:12 +00008453MachineMemOperand::Flags
8454AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8455 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8456 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8457 return MOStridedAccess;
8458 return MachineMemOperand::MONone;
8459}
8460
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008461bool AArch64TargetLowering::isLegalInterleavedAccessType(
8462 VectorType *VecTy, const DataLayout &DL) const {
8463
8464 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8465 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8466
8467 // Ensure the number of vector elements is greater than 1.
8468 if (VecTy->getNumElements() < 2)
8469 return false;
8470
8471 // Ensure the element type is legal.
8472 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8473 return false;
8474
8475 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8476 // 128 will be split into multiple interleaved accesses.
8477 return VecSize == 64 || VecSize % 128 == 0;
8478}
8479
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008480/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008481///
8482/// E.g. Lower an interleaved load (Factor = 2):
8483/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8484/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8485/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8486///
8487/// Into:
8488/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8489/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8490/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8491bool AArch64TargetLowering::lowerInterleavedLoad(
8492 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8493 ArrayRef<unsigned> Indices, unsigned Factor) const {
8494 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8495 "Invalid interleave factor");
8496 assert(!Shuffles.empty() && "Empty shufflevector input");
8497 assert(Shuffles.size() == Indices.size() &&
8498 "Unmatched number of shufflevectors and indices");
8499
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008500 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008501
8502 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008503
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008504 // Skip if we do not have NEON and skip illegal vector types. We can
8505 // "legalize" wide vector types into multiple interleaved accesses as long as
8506 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008507 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008508 return false;
8509
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008510 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8511
Hao Liu7ec8ee32015-06-26 02:32:07 +00008512 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8513 // load integer vectors first and then convert to pointer vectors.
8514 Type *EltTy = VecTy->getVectorElementType();
8515 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008516 VecTy =
8517 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008518
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008519 IRBuilder<> Builder(LI);
8520
8521 // The base address of the load.
8522 Value *BaseAddr = LI->getPointerOperand();
8523
8524 if (NumLoads > 1) {
8525 // If we're going to generate more than one load, reset the sub-vector type
8526 // to something legal.
8527 VecTy = VectorType::get(VecTy->getVectorElementType(),
8528 VecTy->getVectorNumElements() / NumLoads);
8529
8530 // We will compute the pointer operand of each load from the original base
8531 // address using GEPs. Cast the base address to a pointer to the scalar
8532 // element type.
8533 BaseAddr = Builder.CreateBitCast(
8534 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8535 LI->getPointerAddressSpace()));
8536 }
8537
Hao Liu7ec8ee32015-06-26 02:32:07 +00008538 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8539 Type *Tys[2] = {VecTy, PtrTy};
8540 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8541 Intrinsic::aarch64_neon_ld3,
8542 Intrinsic::aarch64_neon_ld4};
8543 Function *LdNFunc =
8544 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8545
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008546 // Holds sub-vectors extracted from the load intrinsic return values. The
8547 // sub-vectors are associated with the shufflevector instructions they will
8548 // replace.
8549 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008550
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008551 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008552
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008553 // If we're generating more than one load, compute the base address of
8554 // subsequent loads as an offset from the previous.
8555 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008556 BaseAddr =
8557 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8558 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008559
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008560 CallInst *LdN = Builder.CreateCall(
8561 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008562
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008563 // Extract and store the sub-vectors returned by the load intrinsic.
8564 for (unsigned i = 0; i < Shuffles.size(); i++) {
8565 ShuffleVectorInst *SVI = Shuffles[i];
8566 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008567
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008568 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8569
8570 // Convert the integer vector to pointer vector if the element is pointer.
8571 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008572 SubVec = Builder.CreateIntToPtr(
8573 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8574 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008575 SubVecs[SVI].push_back(SubVec);
8576 }
8577 }
8578
8579 // Replace uses of the shufflevector instructions with the sub-vectors
8580 // returned by the load intrinsic. If a shufflevector instruction is
8581 // associated with more than one sub-vector, those sub-vectors will be
8582 // concatenated into a single wide vector.
8583 for (ShuffleVectorInst *SVI : Shuffles) {
8584 auto &SubVec = SubVecs[SVI];
8585 auto *WideVec =
8586 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8587 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008588 }
8589
8590 return true;
8591}
8592
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008593/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008594///
8595/// E.g. Lower an interleaved store (Factor = 3):
8596/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008597/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008598/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8599///
8600/// Into:
8601/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8602/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8603/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8604/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8605///
8606/// Note that the new shufflevectors will be removed and we'll only generate one
8607/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008608///
8609/// Example for a more general valid mask (Factor 3). Lower:
8610/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8611/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8612/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8613///
8614/// Into:
8615/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8616/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8617/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8618/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008619bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8620 ShuffleVectorInst *SVI,
8621 unsigned Factor) const {
8622 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8623 "Invalid interleave factor");
8624
8625 VectorType *VecTy = SVI->getType();
8626 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8627 "Invalid interleaved store");
8628
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008629 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008630 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008631 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008632
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008633 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008634
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008635 // Skip if we do not have NEON and skip illegal vector types. We can
8636 // "legalize" wide vector types into multiple interleaved accesses as long as
8637 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008638 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008639 return false;
8640
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008641 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8642
Hao Liu7ec8ee32015-06-26 02:32:07 +00008643 Value *Op0 = SVI->getOperand(0);
8644 Value *Op1 = SVI->getOperand(1);
8645 IRBuilder<> Builder(SI);
8646
8647 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8648 // vectors to integer vectors.
8649 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008650 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008651 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008652
8653 // Convert to the corresponding integer vector.
8654 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8655 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8656 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8657
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008658 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008659 }
8660
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008661 // The base address of the store.
8662 Value *BaseAddr = SI->getPointerOperand();
8663
8664 if (NumStores > 1) {
8665 // If we're going to generate more than one store, reset the lane length
8666 // and sub-vector type to something legal.
8667 LaneLen /= NumStores;
8668 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8669
8670 // We will compute the pointer operand of each store from the original base
8671 // address using GEPs. Cast the base address to a pointer to the scalar
8672 // element type.
8673 BaseAddr = Builder.CreateBitCast(
8674 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8675 SI->getPointerAddressSpace()));
8676 }
8677
8678 auto Mask = SVI->getShuffleMask();
8679
Hao Liu7ec8ee32015-06-26 02:32:07 +00008680 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8681 Type *Tys[2] = {SubVecTy, PtrTy};
8682 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8683 Intrinsic::aarch64_neon_st3,
8684 Intrinsic::aarch64_neon_st4};
8685 Function *StNFunc =
8686 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8687
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008688 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008689
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008690 SmallVector<Value *, 5> Ops;
8691
8692 // Split the shufflevector operands into sub vectors for the new stN call.
8693 for (unsigned i = 0; i < Factor; i++) {
8694 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8695 if (Mask[IdxI] >= 0) {
8696 Ops.push_back(Builder.CreateShuffleVector(
8697 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8698 } else {
8699 unsigned StartMask = 0;
8700 for (unsigned j = 1; j < LaneLen; j++) {
8701 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8702 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8703 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8704 break;
8705 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008706 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008707 // Note: Filling undef gaps with random elements is ok, since
8708 // those elements were being written anyway (with undefs).
8709 // In the case of all undefs we're defaulting to using elems from 0
8710 // Note: StartMask cannot be negative, it's checked in
8711 // isReInterleaveMask
8712 Ops.push_back(Builder.CreateShuffleVector(
8713 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008714 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008715 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008716
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008717 // If we generating more than one store, we compute the base address of
8718 // subsequent stores as an offset from the previous.
8719 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008720 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8721 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008722
8723 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8724 Builder.CreateCall(StNFunc, Ops);
8725 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008726 return true;
8727}
8728
Tim Northover3b0846e2014-05-24 12:50:23 +00008729static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8730 unsigned AlignCheck) {
8731 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8732 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8733}
8734
Sjoerd Meijer180f1ae2019-04-30 08:38:12 +00008735EVT AArch64TargetLowering::getOptimalMemOpType(
8736 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8737 bool ZeroMemset, bool MemcpyStrSrc,
8738 const AttributeList &FuncAttributes) const {
8739 bool CanImplicitFloat =
8740 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
JF Bastien29200612018-09-06 16:03:32 +00008741 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8742 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8743 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8744 // taken one instruction to materialize the v2i64 zero and one store (with
8745 // restrictive addressing mode). Just do i64 stores.
8746 bool IsSmallMemset = IsMemset && Size < 32;
8747 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8748 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8749 return true;
8750 bool Fast;
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00008751 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8752 &Fast) &&
8753 Fast;
JF Bastien29200612018-09-06 16:03:32 +00008754 };
8755
8756 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8757 AlignmentIsAcceptable(MVT::v2i64, 16))
8758 return MVT::v2i64;
8759 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008760 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008761 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008762 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008763 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008764 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008765 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008766}
8767
Amara Emerson13af1ed2019-07-24 22:17:31 +00008768LLT AArch64TargetLowering::getOptimalMemOpLLT(
8769 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8770 bool ZeroMemset, bool MemcpyStrSrc,
8771 const AttributeList &FuncAttributes) const {
8772 bool CanImplicitFloat =
8773 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8774 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8775 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8776 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8777 // taken one instruction to materialize the v2i64 zero and one store (with
8778 // restrictive addressing mode). Just do i64 stores.
8779 bool IsSmallMemset = IsMemset && Size < 32;
8780 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8781 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8782 return true;
8783 bool Fast;
8784 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8785 &Fast) &&
8786 Fast;
8787 };
8788
8789 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8790 AlignmentIsAcceptable(MVT::v2i64, 16))
8791 return LLT::vector(2, 64);
8792 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8793 return LLT::scalar(128);
8794 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8795 return LLT::scalar(64);
8796 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8797 return LLT::scalar(32);
8798 return LLT();
8799}
8800
Tim Northover3b0846e2014-05-24 12:50:23 +00008801// 12-bit optionally shifted immediates are legal for adds.
8802bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008803 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008804 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8805 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008806 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008807 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008808 // Same encoding for add/sub, just flip the sign.
8809 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008810 bool IsLegal = ((Immed >> 12) == 0 ||
8811 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008812 LLVM_DEBUG(dbgs() << "Is " << Immed
8813 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008814 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008815}
8816
8817// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8818// immediates is the same as for an add or a sub.
8819bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008820 return isLegalAddImmediate(Immed);
8821}
8822
8823/// isLegalAddressingMode - Return true if the addressing mode represented
8824/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008825bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8826 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008827 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008828 // AArch64 has five basic addressing modes:
8829 // reg
8830 // reg + 9-bit signed offset
8831 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8832 // reg1 + reg2
8833 // reg + SIZE_IN_BYTES * reg
8834
8835 // No global is ever allowed as a base.
8836 if (AM.BaseGV)
8837 return false;
8838
8839 // No reg+reg+imm addressing.
8840 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8841 return false;
8842
8843 // check reg + imm case:
8844 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8845 uint64_t NumBytes = 0;
8846 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008847 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008848 NumBytes = NumBits / 8;
8849 if (!isPowerOf2_64(NumBits))
8850 NumBytes = 0;
8851 }
8852
8853 if (!AM.Scale) {
8854 int64_t Offset = AM.BaseOffs;
8855
8856 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008857 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008858 return true;
8859
8860 // 12-bit unsigned offset
8861 unsigned shift = Log2_64(NumBytes);
8862 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8863 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8864 (Offset >> shift) << shift == Offset)
8865 return true;
8866 return false;
8867 }
8868
8869 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8870
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008871 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008872}
8873
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008874bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8875 // Consider splitting large offset of struct or array.
8876 return true;
8877}
8878
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008879int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8880 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008881 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008882 // Scaling factors are not free at all.
8883 // Operands | Rt Latency
8884 // -------------------------------------------
8885 // Rt, [Xn, Xm] | 4
8886 // -------------------------------------------
8887 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8888 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008889 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008890 // Scale represents reg2 * scale, thus account for 1 if
8891 // it is not equal to 0 or 1.
8892 return AM.Scale != 0 && AM.Scale != 1;
8893 return -1;
8894}
8895
8896bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8897 VT = VT.getScalarType();
8898
8899 if (!VT.isSimple())
8900 return false;
8901
8902 switch (VT.getSimpleVT().SimpleTy) {
8903 case MVT::f32:
8904 case MVT::f64:
8905 return true;
8906 default:
8907 break;
8908 }
8909
8910 return false;
8911}
8912
8913const MCPhysReg *
8914AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8915 // LR is a callee-save register, but we must treat it as clobbered by any call
8916 // site. Hence we include LR in the scratch registers, which are in turn added
8917 // as implicit-defs for stackmaps and patchpoints.
8918 static const MCPhysReg ScratchRegs[] = {
8919 AArch64::X16, AArch64::X17, AArch64::LR, 0
8920 };
8921 return ScratchRegs;
8922}
8923
8924bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008925AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8926 CombineLevel Level) const {
8927 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008928 EVT VT = N->getValueType(0);
8929 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8930 // it with shift to let it be lowered to UBFX.
8931 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8932 isa<ConstantSDNode>(N->getOperand(1))) {
8933 uint64_t TruncMask = N->getConstantOperandVal(1);
8934 if (isMask_64(TruncMask) &&
8935 N->getOperand(0).getOpcode() == ISD::SRL &&
8936 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8937 return false;
8938 }
8939 return true;
8940}
8941
8942bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8943 Type *Ty) const {
8944 assert(Ty->isIntegerTy());
8945
8946 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8947 if (BitSize == 0)
8948 return false;
8949
8950 int64_t Val = Imm.getSExtValue();
8951 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8952 return true;
8953
8954 if ((int64_t)Val < 0)
8955 Val = ~Val;
8956 if (BitSize == 32)
8957 Val &= (1LL << 32) - 1;
8958
8959 unsigned LZ = countLeadingZeros((uint64_t)Val);
8960 unsigned Shift = (63 - LZ) / 16;
8961 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008962 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008963}
8964
Sebastian Pop41073e82018-03-06 16:54:55 +00008965bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8966 unsigned Index) const {
8967 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8968 return false;
8969
8970 return (Index == 0 || Index == ResVT.getVectorNumElements());
8971}
8972
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008973/// Turn vector tests of the signbit in the form of:
8974/// xor (sra X, elt_size(X)-1), -1
8975/// into:
8976/// cmge X, X, #0
8977static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8978 const AArch64Subtarget *Subtarget) {
8979 EVT VT = N->getValueType(0);
8980 if (!Subtarget->hasNEON() || !VT.isVector())
8981 return SDValue();
8982
8983 // There must be a shift right algebraic before the xor, and the xor must be a
8984 // 'not' operation.
8985 SDValue Shift = N->getOperand(0);
8986 SDValue Ones = N->getOperand(1);
8987 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8988 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8989 return SDValue();
8990
8991 // The shift should be smearing the sign bit across each vector element.
8992 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8993 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8994 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8995 return SDValue();
8996
8997 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8998}
8999
Tim Northover3b0846e2014-05-24 12:50:23 +00009000// Generate SUBS and CSEL for integer abs.
9001static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9002 EVT VT = N->getValueType(0);
9003
9004 SDValue N0 = N->getOperand(0);
9005 SDValue N1 = N->getOperand(1);
9006 SDLoc DL(N);
9007
9008 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9009 // and change it to SUB and CSEL.
9010 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9011 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9012 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9013 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9014 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009015 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00009016 N0.getOperand(0));
9017 // Generate SUBS & CSEL.
9018 SDValue Cmp =
9019 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009020 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009021 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009022 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00009023 SDValue(Cmp.getNode(), 1));
9024 }
9025 return SDValue();
9026}
9027
Tim Northover3b0846e2014-05-24 12:50:23 +00009028static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9029 TargetLowering::DAGCombinerInfo &DCI,
9030 const AArch64Subtarget *Subtarget) {
9031 if (DCI.isBeforeLegalizeOps())
9032 return SDValue();
9033
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00009034 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9035 return Cmp;
9036
Tim Northover3b0846e2014-05-24 12:50:23 +00009037 return performIntegerAbsCombine(N, DAG);
9038}
9039
Chad Rosier17020f92014-07-23 14:57:52 +00009040SDValue
9041AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9042 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00009043 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00009044 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00009045 if (isIntDivCheap(N->getValueType(0), Attr))
9046 return SDValue(N,0); // Lower SDIV as SDIV
9047
Chad Rosier17020f92014-07-23 14:57:52 +00009048 // fold (sdiv X, pow2)
9049 EVT VT = N->getValueType(0);
9050 if ((VT != MVT::i32 && VT != MVT::i64) ||
9051 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9052 return SDValue();
9053
9054 SDLoc DL(N);
9055 SDValue N0 = N->getOperand(0);
9056 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009057 SDValue Zero = DAG.getConstant(0, DL, VT);
9058 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00009059
9060 // Add (N0 < 0) ? Pow2 - 1 : 0;
9061 SDValue CCVal;
9062 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9063 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9064 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9065
Craig Toppera568a272018-07-30 21:04:34 +00009066 Created.push_back(Cmp.getNode());
9067 Created.push_back(Add.getNode());
9068 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00009069
9070 // Divide by pow2.
9071 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009072 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00009073
9074 // If we're dividing by a positive value, we're done. Otherwise, we must
9075 // negate the result.
9076 if (Divisor.isNonNegative())
9077 return SRA;
9078
Craig Toppera568a272018-07-30 21:04:34 +00009079 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009080 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00009081}
9082
Tim Northover3b0846e2014-05-24 12:50:23 +00009083static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9084 TargetLowering::DAGCombinerInfo &DCI,
9085 const AArch64Subtarget *Subtarget) {
9086 if (DCI.isBeforeLegalizeOps())
9087 return SDValue();
9088
Chad Rosier31ee8132016-11-11 17:07:37 +00009089 // The below optimizations require a constant RHS.
9090 if (!isa<ConstantSDNode>(N->getOperand(1)))
9091 return SDValue();
9092
9093 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9094 const APInt &ConstValue = C->getAPIntValue();
9095
Tim Northover3b0846e2014-05-24 12:50:23 +00009096 // Multiplication of a power of two plus/minus one can be done more
9097 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9098 // future CPUs have a cheaper MADD instruction, this may need to be
9099 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9100 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009101 // More aggressively, some multiplications N0 * C can be lowered to
9102 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9103 // e.g. 6=3*2=(2+1)*2.
9104 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9105 // which equals to (1+2)*16-(1+2).
9106 SDValue N0 = N->getOperand(0);
9107 // TrailingZeroes is used to test if the mul can be lowered to
9108 // shift+add+shift.
9109 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9110 if (TrailingZeroes) {
9111 // Conservatively do not lower to shift+add+shift if the mul might be
9112 // folded into smul or umul.
9113 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9114 isZeroExtended(N0.getNode(), DAG)))
9115 return SDValue();
9116 // Conservatively do not lower to shift+add+shift if the mul might be
9117 // folded into madd or msub.
9118 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9119 N->use_begin()->getOpcode() == ISD::SUB))
9120 return SDValue();
9121 }
9122 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9123 // and shift+add+shift.
9124 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9125
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009126 unsigned ShiftAmt, AddSubOpc;
9127 // Is the shifted value the LHS operand of the add/sub?
9128 bool ShiftValUseIsN0 = true;
9129 // Do we need to negate the result?
9130 bool NegateResult = false;
9131
Chad Rosier31ee8132016-11-11 17:07:37 +00009132 if (ConstValue.isNonNegative()) {
9133 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009134 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009135 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9136 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009137 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009138 if (SCVMinus1.isPowerOf2()) {
9139 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009140 AddSubOpc = ISD::ADD;
9141 } else if (CVPlus1.isPowerOf2()) {
9142 ShiftAmt = CVPlus1.logBase2();
9143 AddSubOpc = ISD::SUB;
9144 } else
9145 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009146 } else {
9147 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009148 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009149 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009150 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009151 if (CVNegPlus1.isPowerOf2()) {
9152 ShiftAmt = CVNegPlus1.logBase2();
9153 AddSubOpc = ISD::SUB;
9154 ShiftValUseIsN0 = false;
9155 } else if (CVNegMinus1.isPowerOf2()) {
9156 ShiftAmt = CVNegMinus1.logBase2();
9157 AddSubOpc = ISD::ADD;
9158 NegateResult = true;
9159 } else
9160 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009161 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009162
9163 SDLoc DL(N);
9164 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009165 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009166 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9167
9168 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9169 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9170 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009171 assert(!(NegateResult && TrailingZeroes) &&
9172 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009173 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009174 if (NegateResult)
9175 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9176 // Shift the result.
9177 if (TrailingZeroes)
9178 return DAG.getNode(ISD::SHL, DL, VT, Res,
9179 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9180 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009181}
9182
Jim Grosbachf7502c42014-07-18 00:40:52 +00009183static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9184 SelectionDAG &DAG) {
9185 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9186 // optimize away operation when it's from a constant.
9187 //
9188 // The general transformation is:
9189 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9190 // AND(VECTOR_CMP(x,y), constant2)
9191 // constant2 = UNARYOP(constant)
9192
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009193 // Early exit if this isn't a vector operation, the operand of the
9194 // unary operation isn't a bitwise AND, or if the sizes of the operations
9195 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009196 EVT VT = N->getValueType(0);
9197 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009198 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9199 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009200 return SDValue();
9201
Jim Grosbach724e4382014-07-23 20:41:43 +00009202 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009203 // make the transformation for non-constant splats as well, but it's unclear
9204 // that would be a benefit as it would not eliminate any operations, just
9205 // perform one more step in scalar code before moving to the vector unit.
9206 if (BuildVectorSDNode *BV =
9207 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009208 // Bail out if the vector isn't a constant.
9209 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009210 return SDValue();
9211
9212 // Everything checks out. Build up the new and improved node.
9213 SDLoc DL(N);
9214 EVT IntVT = BV->getValueType(0);
9215 // Create a new constant of the appropriate type for the transformed
9216 // DAG.
9217 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9218 // The AND node needs bitcasts to/from an integer vector type around it.
9219 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9220 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9221 N->getOperand(0)->getOperand(0), MaskConst);
9222 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9223 return Res;
9224 }
9225
9226 return SDValue();
9227}
9228
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009229static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9230 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009231 // First try to optimize away the conversion when it's conditionally from
9232 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009233 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009234 return Res;
9235
Tim Northover3b0846e2014-05-24 12:50:23 +00009236 EVT VT = N->getValueType(0);
9237 if (VT != MVT::f32 && VT != MVT::f64)
9238 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009239
Tim Northover3b0846e2014-05-24 12:50:23 +00009240 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009241 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009242 return SDValue();
9243
9244 // If the result of an integer load is only used by an integer-to-float
9245 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009246 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009247 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009248 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009249 // Do not change the width of a volatile load.
9250 !cast<LoadSDNode>(N0)->isVolatile()) {
9251 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9252 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009253 LN0->getPointerInfo(), LN0->getAlignment(),
9254 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009255
9256 // Make sure successors of the original load stay after it by updating them
9257 // to use the new Chain.
9258 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9259
9260 unsigned Opcode =
9261 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9262 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9263 }
9264
9265 return SDValue();
9266}
9267
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009268/// Fold a floating-point multiply by power of two into floating-point to
9269/// fixed-point conversion.
9270static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009271 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009272 const AArch64Subtarget *Subtarget) {
9273 if (!Subtarget->hasNEON())
9274 return SDValue();
9275
Sam Parkera0bd6f82019-06-03 08:49:17 +00009276 if (!N->getValueType(0).isSimple())
9277 return SDValue();
9278
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009279 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009280 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9281 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009282 return SDValue();
9283
9284 SDValue ConstVec = Op->getOperand(1);
9285 if (!isa<BuildVectorSDNode>(ConstVec))
9286 return SDValue();
9287
9288 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9289 uint32_t FloatBits = FloatTy.getSizeInBits();
9290 if (FloatBits != 32 && FloatBits != 64)
9291 return SDValue();
9292
9293 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9294 uint32_t IntBits = IntTy.getSizeInBits();
9295 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9296 return SDValue();
9297
9298 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9299 if (IntBits > FloatBits)
9300 return SDValue();
9301
9302 BitVector UndefElements;
9303 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9304 int32_t Bits = IntBits == 64 ? 64 : 32;
9305 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9306 if (C == -1 || C == 0 || C > Bits)
9307 return SDValue();
9308
9309 MVT ResTy;
9310 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9311 switch (NumLanes) {
9312 default:
9313 return SDValue();
9314 case 2:
9315 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9316 break;
9317 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009318 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009319 break;
9320 }
9321
Silviu Barangafa00ba32016-08-08 13:13:57 +00009322 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9323 return SDValue();
9324
9325 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9326 "Illegal vector type after legalization");
9327
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009328 SDLoc DL(N);
9329 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9330 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9331 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9332 SDValue FixConv =
9333 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9334 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9335 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9336 // We can handle smaller integers by generating an extra trunc.
9337 if (IntBits < FloatBits)
9338 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9339
9340 return FixConv;
9341}
9342
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009343/// Fold a floating-point divide by power of two into fixed-point to
9344/// floating-point conversion.
9345static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009346 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009347 const AArch64Subtarget *Subtarget) {
9348 if (!Subtarget->hasNEON())
9349 return SDValue();
9350
9351 SDValue Op = N->getOperand(0);
9352 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009353 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9354 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009355 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9356 return SDValue();
9357
9358 SDValue ConstVec = N->getOperand(1);
9359 if (!isa<BuildVectorSDNode>(ConstVec))
9360 return SDValue();
9361
9362 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9363 int32_t IntBits = IntTy.getSizeInBits();
9364 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9365 return SDValue();
9366
9367 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9368 int32_t FloatBits = FloatTy.getSizeInBits();
9369 if (FloatBits != 32 && FloatBits != 64)
9370 return SDValue();
9371
9372 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9373 if (IntBits > FloatBits)
9374 return SDValue();
9375
9376 BitVector UndefElements;
9377 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9378 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9379 if (C == -1 || C == 0 || C > FloatBits)
9380 return SDValue();
9381
9382 MVT ResTy;
9383 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9384 switch (NumLanes) {
9385 default:
9386 return SDValue();
9387 case 2:
9388 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9389 break;
9390 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009391 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009392 break;
9393 }
9394
Tim Northover85cf5642016-08-26 18:52:31 +00009395 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9396 return SDValue();
9397
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009398 SDLoc DL(N);
9399 SDValue ConvInput = Op.getOperand(0);
9400 bool IsSigned = Opc == ISD::SINT_TO_FP;
9401 if (IntBits < FloatBits)
9402 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9403 ResTy, ConvInput);
9404
9405 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9406 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9407 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9408 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9409 DAG.getConstant(C, DL, MVT::i32));
9410}
9411
Tim Northover3b0846e2014-05-24 12:50:23 +00009412/// An EXTR instruction is made up of two shifts, ORed together. This helper
9413/// searches for and classifies those shifts.
9414static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9415 bool &FromHi) {
9416 if (N.getOpcode() == ISD::SHL)
9417 FromHi = false;
9418 else if (N.getOpcode() == ISD::SRL)
9419 FromHi = true;
9420 else
9421 return false;
9422
9423 if (!isa<ConstantSDNode>(N.getOperand(1)))
9424 return false;
9425
9426 ShiftAmount = N->getConstantOperandVal(1);
9427 Src = N->getOperand(0);
9428 return true;
9429}
9430
9431/// EXTR instruction extracts a contiguous chunk of bits from two existing
9432/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009433/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9434/// with an EXTR. Can't quite be done in TableGen because the two immediates
9435/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009436static SDValue tryCombineToEXTR(SDNode *N,
9437 TargetLowering::DAGCombinerInfo &DCI) {
9438 SelectionDAG &DAG = DCI.DAG;
9439 SDLoc DL(N);
9440 EVT VT = N->getValueType(0);
9441
9442 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9443
9444 if (VT != MVT::i32 && VT != MVT::i64)
9445 return SDValue();
9446
9447 SDValue LHS;
9448 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009449 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009450 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9451 return SDValue();
9452
9453 SDValue RHS;
9454 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009455 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009456 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9457 return SDValue();
9458
9459 // If they're both trying to come from the high part of the register, they're
9460 // not really an EXTR.
9461 if (LHSFromHi == RHSFromHi)
9462 return SDValue();
9463
9464 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9465 return SDValue();
9466
9467 if (LHSFromHi) {
9468 std::swap(LHS, RHS);
9469 std::swap(ShiftLHS, ShiftRHS);
9470 }
9471
9472 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009473 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009474}
9475
9476static SDValue tryCombineToBSL(SDNode *N,
9477 TargetLowering::DAGCombinerInfo &DCI) {
9478 EVT VT = N->getValueType(0);
9479 SelectionDAG &DAG = DCI.DAG;
9480 SDLoc DL(N);
9481
9482 if (!VT.isVector())
9483 return SDValue();
9484
9485 SDValue N0 = N->getOperand(0);
9486 if (N0.getOpcode() != ISD::AND)
9487 return SDValue();
9488
9489 SDValue N1 = N->getOperand(1);
9490 if (N1.getOpcode() != ISD::AND)
9491 return SDValue();
9492
9493 // We only have to look for constant vectors here since the general, variable
9494 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009495 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009496 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9497 for (int i = 1; i >= 0; --i)
9498 for (int j = 1; j >= 0; --j) {
9499 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9500 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9501 if (!BVN0 || !BVN1)
9502 continue;
9503
9504 bool FoundMatch = true;
9505 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9506 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9507 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9508 if (!CN0 || !CN1 ||
9509 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9510 FoundMatch = false;
9511 break;
9512 }
9513 }
9514
9515 if (FoundMatch)
9516 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9517 N0->getOperand(1 - i), N1->getOperand(1 - j));
9518 }
9519
9520 return SDValue();
9521}
9522
9523static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9524 const AArch64Subtarget *Subtarget) {
9525 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009526 SelectionDAG &DAG = DCI.DAG;
9527 EVT VT = N->getValueType(0);
9528
9529 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9530 return SDValue();
9531
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009532 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009533 return Res;
9534
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009535 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009536 return Res;
9537
9538 return SDValue();
9539}
9540
Nikita Popov1a261442019-03-15 21:04:34 +00009541static SDValue performANDCombine(SDNode *N,
9542 TargetLowering::DAGCombinerInfo &DCI) {
9543 SelectionDAG &DAG = DCI.DAG;
9544 SDValue LHS = N->getOperand(0);
9545 EVT VT = N->getValueType(0);
9546 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9547 return SDValue();
9548
9549 BuildVectorSDNode *BVN =
9550 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9551 if (!BVN)
9552 return SDValue();
9553
9554 // AND does not accept an immediate, so check if we can use a BIC immediate
9555 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9556 // pattern in isel, because some immediates may be lowered to the preferred
9557 // (and x, (movi imm)) form, even though an mvni representation also exists.
9558 APInt DefBits(VT.getSizeInBits(), 0);
9559 APInt UndefBits(VT.getSizeInBits(), 0);
9560 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9561 SDValue NewOp;
9562
9563 DefBits = ~DefBits;
9564 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9565 DefBits, &LHS)) ||
9566 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9567 DefBits, &LHS)))
9568 return NewOp;
9569
9570 UndefBits = ~UndefBits;
9571 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9572 UndefBits, &LHS)) ||
9573 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9574 UndefBits, &LHS)))
9575 return NewOp;
9576 }
9577
9578 return SDValue();
9579}
9580
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009581static SDValue performSRLCombine(SDNode *N,
9582 TargetLowering::DAGCombinerInfo &DCI) {
9583 SelectionDAG &DAG = DCI.DAG;
9584 EVT VT = N->getValueType(0);
9585 if (VT != MVT::i32 && VT != MVT::i64)
9586 return SDValue();
9587
9588 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9589 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9590 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9591 SDValue N0 = N->getOperand(0);
9592 if (N0.getOpcode() == ISD::BSWAP) {
9593 SDLoc DL(N);
9594 SDValue N1 = N->getOperand(1);
9595 SDValue N00 = N0.getOperand(0);
9596 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9597 uint64_t ShiftAmt = C->getZExtValue();
9598 if (VT == MVT::i32 && ShiftAmt == 16 &&
9599 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9600 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9601 if (VT == MVT::i64 && ShiftAmt == 32 &&
9602 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9603 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9604 }
9605 }
9606 return SDValue();
9607}
9608
Tim Northover3b0846e2014-05-24 12:50:23 +00009609static SDValue performBitcastCombine(SDNode *N,
9610 TargetLowering::DAGCombinerInfo &DCI,
9611 SelectionDAG &DAG) {
9612 // Wait 'til after everything is legalized to try this. That way we have
9613 // legal vector types and such.
9614 if (DCI.isBeforeLegalizeOps())
9615 return SDValue();
9616
9617 // Remove extraneous bitcasts around an extract_subvector.
9618 // For example,
9619 // (v4i16 (bitconvert
9620 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9621 // becomes
9622 // (extract_subvector ((v8i16 ...), (i64 4)))
9623
9624 // Only interested in 64-bit vectors as the ultimate result.
9625 EVT VT = N->getValueType(0);
9626 if (!VT.isVector())
9627 return SDValue();
9628 if (VT.getSimpleVT().getSizeInBits() != 64)
9629 return SDValue();
9630 // Is the operand an extract_subvector starting at the beginning or halfway
9631 // point of the vector? A low half may also come through as an
9632 // EXTRACT_SUBREG, so look for that, too.
9633 SDValue Op0 = N->getOperand(0);
9634 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9635 !(Op0->isMachineOpcode() &&
9636 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9637 return SDValue();
9638 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9639 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9640 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9641 return SDValue();
9642 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9643 if (idx != AArch64::dsub)
9644 return SDValue();
9645 // The dsub reference is equivalent to a lane zero subvector reference.
9646 idx = 0;
9647 }
9648 // Look through the bitcast of the input to the extract.
9649 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9650 return SDValue();
9651 SDValue Source = Op0->getOperand(0)->getOperand(0);
9652 // If the source type has twice the number of elements as our destination
9653 // type, we know this is an extract of the high or low half of the vector.
9654 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009655 if (!SVT.isVector() ||
9656 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009657 return SDValue();
9658
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009659 LLVM_DEBUG(
9660 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009661
9662 // Create the simplified form to just extract the low or high half of the
9663 // vector directly rather than bothering with the bitcasts.
9664 SDLoc dl(N);
9665 unsigned NumElements = VT.getVectorNumElements();
9666 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009667 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009668 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9669 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009670 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009671 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9672 Source, SubReg),
9673 0);
9674 }
9675}
9676
9677static SDValue performConcatVectorsCombine(SDNode *N,
9678 TargetLowering::DAGCombinerInfo &DCI,
9679 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009680 SDLoc dl(N);
9681 EVT VT = N->getValueType(0);
9682 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9683
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009684 // Optimize concat_vectors of truncated vectors, where the intermediate
9685 // type is illegal, to avoid said illegality, e.g.,
9686 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9687 // (v2i16 (truncate (v2i64)))))
9688 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009689 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9690 // (v4i32 (bitcast (v2i64))),
9691 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009692 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9693 // on both input and result type, so we might generate worse code.
9694 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9695 if (N->getNumOperands() == 2 &&
9696 N0->getOpcode() == ISD::TRUNCATE &&
9697 N1->getOpcode() == ISD::TRUNCATE) {
9698 SDValue N00 = N0->getOperand(0);
9699 SDValue N10 = N1->getOperand(0);
9700 EVT N00VT = N00.getValueType();
9701
9702 if (N00VT == N10.getValueType() &&
9703 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9704 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009705 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9706 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9707 for (size_t i = 0; i < Mask.size(); ++i)
9708 Mask[i] = i * 2;
9709 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9710 DAG.getVectorShuffle(
9711 MidVT, dl,
9712 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9713 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009714 }
9715 }
9716
Tim Northover3b0846e2014-05-24 12:50:23 +00009717 // Wait 'til after everything is legalized to try this. That way we have
9718 // legal vector types and such.
9719 if (DCI.isBeforeLegalizeOps())
9720 return SDValue();
9721
Tim Northover3b0846e2014-05-24 12:50:23 +00009722 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9723 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9724 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009725 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009726 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009727 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009728 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009729 }
9730
9731 // Canonicalise concat_vectors so that the right-hand vector has as few
9732 // bit-casts as possible before its real operation. The primary matching
9733 // destination for these operations will be the narrowing "2" instructions,
9734 // which depend on the operation being performed on this right-hand vector.
9735 // For example,
9736 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9737 // becomes
9738 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9739
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009740 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009741 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009742 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009743 MVT RHSTy = RHS.getValueType().getSimpleVT();
9744 // If the RHS is not a vector, this is not the pattern we're looking for.
9745 if (!RHSTy.isVector())
9746 return SDValue();
9747
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009748 LLVM_DEBUG(
9749 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009750
9751 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9752 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009753 return DAG.getNode(ISD::BITCAST, dl, VT,
9754 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9755 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9756 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009757}
9758
9759static SDValue tryCombineFixedPointConvert(SDNode *N,
9760 TargetLowering::DAGCombinerInfo &DCI,
9761 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009762 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009763 // legal vector types and such.
9764 if (DCI.isBeforeLegalizeOps())
9765 return SDValue();
9766 // Transform a scalar conversion of a value from a lane extract into a
9767 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9768 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9769 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9770 //
9771 // The second form interacts better with instruction selection and the
9772 // register allocator to avoid cross-class register copies that aren't
9773 // coalescable due to a lane reference.
9774
9775 // Check the operand and see if it originates from a lane extract.
9776 SDValue Op1 = N->getOperand(1);
9777 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9778 // Yep, no additional predication needed. Perform the transform.
9779 SDValue IID = N->getOperand(0);
9780 SDValue Shift = N->getOperand(2);
9781 SDValue Vec = Op1.getOperand(0);
9782 SDValue Lane = Op1.getOperand(1);
9783 EVT ResTy = N->getValueType(0);
9784 EVT VecResTy;
9785 SDLoc DL(N);
9786
9787 // The vector width should be 128 bits by the time we get here, even
9788 // if it started as 64 bits (the extract_vector handling will have
9789 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009790 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009791 "unexpected vector size on extract_vector_elt!");
9792 if (Vec.getValueType() == MVT::v4i32)
9793 VecResTy = MVT::v4f32;
9794 else if (Vec.getValueType() == MVT::v2i64)
9795 VecResTy = MVT::v2f64;
9796 else
Craig Topper2a30d782014-06-18 05:05:13 +00009797 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009798
9799 SDValue Convert =
9800 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9801 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9802 }
9803 return SDValue();
9804}
9805
9806// AArch64 high-vector "long" operations are formed by performing the non-high
9807// version on an extract_subvector of each operand which gets the high half:
9808//
9809// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9810//
9811// However, there are cases which don't have an extract_high explicitly, but
9812// have another operation that can be made compatible with one for free. For
9813// example:
9814//
9815// (dupv64 scalar) --> (extract_high (dup128 scalar))
9816//
9817// This routine does the actual conversion of such DUPs, once outer routines
9818// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009819// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9820// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009821static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009822 switch (N.getOpcode()) {
9823 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009824 case AArch64ISD::DUPLANE8:
9825 case AArch64ISD::DUPLANE16:
9826 case AArch64ISD::DUPLANE32:
9827 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009828 case AArch64ISD::MOVI:
9829 case AArch64ISD::MOVIshift:
9830 case AArch64ISD::MOVIedit:
9831 case AArch64ISD::MOVImsl:
9832 case AArch64ISD::MVNIshift:
9833 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009834 break;
9835 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009836 // FMOV could be supported, but isn't very useful, as it would only occur
9837 // if you passed a bitcast' floating point immediate to an eligible long
9838 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009839 return SDValue();
9840 }
9841
9842 MVT NarrowTy = N.getSimpleValueType();
9843 if (!NarrowTy.is64BitVector())
9844 return SDValue();
9845
9846 MVT ElementTy = NarrowTy.getVectorElementType();
9847 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009848 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009849
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009850 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009851 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9852 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009853 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009854}
9855
Eli Friedman29c06092019-02-08 00:23:35 +00009856static bool isEssentiallyExtractHighSubvector(SDValue N) {
9857 if (N.getOpcode() == ISD::BITCAST)
9858 N = N.getOperand(0);
9859 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9860 return false;
9861 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9862 N.getOperand(0).getValueType().getVectorNumElements() / 2;
Tim Northover3b0846e2014-05-24 12:50:23 +00009863}
9864
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009865/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009866struct GenericSetCCInfo {
9867 const SDValue *Opnd0;
9868 const SDValue *Opnd1;
9869 ISD::CondCode CC;
9870};
9871
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009872/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009873struct AArch64SetCCInfo {
9874 const SDValue *Cmp;
9875 AArch64CC::CondCode CC;
9876};
9877
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009878/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009879union SetCCInfo {
9880 GenericSetCCInfo Generic;
9881 AArch64SetCCInfo AArch64;
9882};
9883
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009884/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009885/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9886/// GenericSetCCInfo.
9887struct SetCCInfoAndKind {
9888 SetCCInfo Info;
9889 bool IsAArch64;
9890};
9891
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009892/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009893/// an
9894/// AArch64 lowered one.
9895/// \p SetCCInfo is filled accordingly.
9896/// \post SetCCInfo is meanginfull only when this function returns true.
9897/// \return True when Op is a kind of SET_CC operation.
9898static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9899 // If this is a setcc, this is straight forward.
9900 if (Op.getOpcode() == ISD::SETCC) {
9901 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9902 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9903 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9904 SetCCInfo.IsAArch64 = false;
9905 return true;
9906 }
9907 // Otherwise, check if this is a matching csel instruction.
9908 // In other words:
9909 // - csel 1, 0, cc
9910 // - csel 0, 1, !cc
9911 if (Op.getOpcode() != AArch64ISD::CSEL)
9912 return false;
9913 // Set the information about the operands.
9914 // TODO: we want the operands of the Cmp not the csel
9915 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9916 SetCCInfo.IsAArch64 = true;
9917 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9918 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9919
9920 // Check that the operands matches the constraints:
9921 // (1) Both operands must be constants.
9922 // (2) One must be 1 and the other must be 0.
9923 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9924 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9925
9926 // Check (1).
9927 if (!TValue || !FValue)
9928 return false;
9929
9930 // Check (2).
9931 if (!TValue->isOne()) {
9932 // Update the comparison when we are interested in !cc.
9933 std::swap(TValue, FValue);
9934 SetCCInfo.Info.AArch64.CC =
9935 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9936 }
9937 return TValue->isOne() && FValue->isNullValue();
9938}
9939
9940// Returns true if Op is setcc or zext of setcc.
9941static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9942 if (isSetCC(Op, Info))
9943 return true;
9944 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9945 isSetCC(Op->getOperand(0), Info));
9946}
9947
9948// The folding we want to perform is:
9949// (add x, [zext] (setcc cc ...) )
9950// -->
9951// (csel x, (add x, 1), !cc ...)
9952//
9953// The latter will get matched to a CSINC instruction.
9954static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9955 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9956 SDValue LHS = Op->getOperand(0);
9957 SDValue RHS = Op->getOperand(1);
9958 SetCCInfoAndKind InfoAndKind;
9959
9960 // If neither operand is a SET_CC, give up.
9961 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9962 std::swap(LHS, RHS);
9963 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9964 return SDValue();
9965 }
9966
9967 // FIXME: This could be generatized to work for FP comparisons.
9968 EVT CmpVT = InfoAndKind.IsAArch64
9969 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9970 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9971 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9972 return SDValue();
9973
9974 SDValue CCVal;
9975 SDValue Cmp;
9976 SDLoc dl(Op);
9977 if (InfoAndKind.IsAArch64) {
9978 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009979 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9980 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009981 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9982 } else
9983 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9984 *InfoAndKind.Info.Generic.Opnd1,
9985 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9986 CCVal, DAG, dl);
9987
9988 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009989 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009990 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9991}
9992
9993// The basic add/sub long vector instructions have variants with "2" on the end
9994// which act on the high-half of their inputs. They are normally matched by
9995// patterns like:
9996//
9997// (add (zeroext (extract_high LHS)),
9998// (zeroext (extract_high RHS)))
9999// -> uaddl2 vD, vN, vM
10000//
10001// However, if one of the extracts is something like a duplicate, this
10002// instruction can still be used profitably. This function puts the DAG into a
10003// more appropriate form for those patterns to trigger.
10004static SDValue performAddSubLongCombine(SDNode *N,
10005 TargetLowering::DAGCombinerInfo &DCI,
10006 SelectionDAG &DAG) {
10007 if (DCI.isBeforeLegalizeOps())
10008 return SDValue();
10009
10010 MVT VT = N->getSimpleValueType(0);
10011 if (!VT.is128BitVector()) {
10012 if (N->getOpcode() == ISD::ADD)
10013 return performSetccAddFolding(N, DAG);
10014 return SDValue();
10015 }
10016
10017 // Make sure both branches are extended in the same way.
10018 SDValue LHS = N->getOperand(0);
10019 SDValue RHS = N->getOperand(1);
10020 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10021 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10022 LHS.getOpcode() != RHS.getOpcode())
10023 return SDValue();
10024
10025 unsigned ExtType = LHS.getOpcode();
10026
10027 // It's not worth doing if at least one of the inputs isn't already an
10028 // extract, but we don't know which it'll be so we have to try both.
Eli Friedman29c06092019-02-08 00:23:35 +000010029 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010030 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10031 if (!RHS.getNode())
10032 return SDValue();
10033
10034 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
Eli Friedman29c06092019-02-08 00:23:35 +000010035 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010036 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10037 if (!LHS.getNode())
10038 return SDValue();
10039
10040 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10041 }
10042
10043 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10044}
10045
10046// Massage DAGs which we can use the high-half "long" operations on into
10047// something isel will recognize better. E.g.
10048//
10049// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10050// (aarch64_neon_umull (extract_high (v2i64 vec)))
10051// (extract_high (v2i64 (dup128 scalar)))))
10052//
Hal Finkelcd8664c2015-12-11 23:11:52 +000010053static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +000010054 TargetLowering::DAGCombinerInfo &DCI,
10055 SelectionDAG &DAG) {
10056 if (DCI.isBeforeLegalizeOps())
10057 return SDValue();
10058
Hal Finkelcd8664c2015-12-11 23:11:52 +000010059 SDValue LHS = N->getOperand(1);
10060 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +000010061 assert(LHS.getValueType().is64BitVector() &&
10062 RHS.getValueType().is64BitVector() &&
10063 "unexpected shape for long operation");
10064
10065 // Either node could be a DUP, but it's not worth doing both of them (you'd
10066 // just as well use the non-high version) so look for a corresponding extract
10067 // operation on the other "wing".
Eli Friedman29c06092019-02-08 00:23:35 +000010068 if (isEssentiallyExtractHighSubvector(LHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010069 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10070 if (!RHS.getNode())
10071 return SDValue();
Eli Friedman29c06092019-02-08 00:23:35 +000010072 } else if (isEssentiallyExtractHighSubvector(RHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010073 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10074 if (!LHS.getNode())
10075 return SDValue();
10076 }
10077
Hal Finkelcd8664c2015-12-11 23:11:52 +000010078 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10079 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +000010080}
10081
10082static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10083 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10084 unsigned ElemBits = ElemTy.getSizeInBits();
10085
10086 int64_t ShiftAmount;
10087 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10088 APInt SplatValue, SplatUndef;
10089 unsigned SplatBitSize;
10090 bool HasAnyUndefs;
10091 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10092 HasAnyUndefs, ElemBits) ||
10093 SplatBitSize != ElemBits)
10094 return SDValue();
10095
10096 ShiftAmount = SplatValue.getSExtValue();
10097 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10098 ShiftAmount = CVN->getSExtValue();
10099 } else
10100 return SDValue();
10101
10102 unsigned Opcode;
10103 bool IsRightShift;
10104 switch (IID) {
10105 default:
10106 llvm_unreachable("Unknown shift intrinsic");
10107 case Intrinsic::aarch64_neon_sqshl:
10108 Opcode = AArch64ISD::SQSHL_I;
10109 IsRightShift = false;
10110 break;
10111 case Intrinsic::aarch64_neon_uqshl:
10112 Opcode = AArch64ISD::UQSHL_I;
10113 IsRightShift = false;
10114 break;
10115 case Intrinsic::aarch64_neon_srshl:
10116 Opcode = AArch64ISD::SRSHR_I;
10117 IsRightShift = true;
10118 break;
10119 case Intrinsic::aarch64_neon_urshl:
10120 Opcode = AArch64ISD::URSHR_I;
10121 IsRightShift = true;
10122 break;
10123 case Intrinsic::aarch64_neon_sqshlu:
10124 Opcode = AArch64ISD::SQSHLU_I;
10125 IsRightShift = false;
10126 break;
10127 }
10128
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010129 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10130 SDLoc dl(N);
10131 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10132 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10133 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10134 SDLoc dl(N);
10135 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10136 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10137 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010138
10139 return SDValue();
10140}
10141
10142// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10143// the intrinsics must be legal and take an i32, this means there's almost
10144// certainly going to be a zext in the DAG which we can eliminate.
10145static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10146 SDValue AndN = N->getOperand(2);
10147 if (AndN.getOpcode() != ISD::AND)
10148 return SDValue();
10149
10150 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10151 if (!CMask || CMask->getZExtValue() != Mask)
10152 return SDValue();
10153
10154 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10155 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10156}
10157
Ahmed Bougachafab58922015-03-10 20:45:38 +000010158static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10159 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010160 SDLoc dl(N);
10161 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10162 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +000010163 N->getOperand(1).getSimpleValueType(),
10164 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010165 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +000010166}
10167
Tim Northover3b0846e2014-05-24 12:50:23 +000010168static SDValue performIntrinsicCombine(SDNode *N,
10169 TargetLowering::DAGCombinerInfo &DCI,
10170 const AArch64Subtarget *Subtarget) {
10171 SelectionDAG &DAG = DCI.DAG;
10172 unsigned IID = getIntrinsicID(N);
10173 switch (IID) {
10174 default:
10175 break;
10176 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10177 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10178 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010179 case Intrinsic::aarch64_neon_saddv:
10180 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10181 case Intrinsic::aarch64_neon_uaddv:
10182 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10183 case Intrinsic::aarch64_neon_sminv:
10184 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10185 case Intrinsic::aarch64_neon_uminv:
10186 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10187 case Intrinsic::aarch64_neon_smaxv:
10188 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10189 case Intrinsic::aarch64_neon_umaxv:
10190 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010191 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010192 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010193 N->getOperand(1), N->getOperand(2));
10194 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010195 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010196 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010197 case Intrinsic::aarch64_neon_fmaxnm:
10198 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10199 N->getOperand(1), N->getOperand(2));
10200 case Intrinsic::aarch64_neon_fminnm:
10201 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10202 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010203 case Intrinsic::aarch64_neon_smull:
10204 case Intrinsic::aarch64_neon_umull:
10205 case Intrinsic::aarch64_neon_pmull:
10206 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010207 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010208 case Intrinsic::aarch64_neon_sqshl:
10209 case Intrinsic::aarch64_neon_uqshl:
10210 case Intrinsic::aarch64_neon_sqshlu:
10211 case Intrinsic::aarch64_neon_srshl:
10212 case Intrinsic::aarch64_neon_urshl:
10213 return tryCombineShiftImm(IID, N, DAG);
10214 case Intrinsic::aarch64_crc32b:
10215 case Intrinsic::aarch64_crc32cb:
10216 return tryCombineCRC32(0xff, N, DAG);
10217 case Intrinsic::aarch64_crc32h:
10218 case Intrinsic::aarch64_crc32ch:
10219 return tryCombineCRC32(0xffff, N, DAG);
10220 }
10221 return SDValue();
10222}
10223
10224static SDValue performExtendCombine(SDNode *N,
10225 TargetLowering::DAGCombinerInfo &DCI,
10226 SelectionDAG &DAG) {
10227 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10228 // we can convert that DUP into another extract_high (of a bigger DUP), which
10229 // helps the backend to decide that an sabdl2 would be useful, saving a real
10230 // extract_high operation.
10231 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010232 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010233 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010234 unsigned IID = getIntrinsicID(ABDNode);
10235 if (IID == Intrinsic::aarch64_neon_sabd ||
10236 IID == Intrinsic::aarch64_neon_uabd) {
10237 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10238 if (!NewABD.getNode())
10239 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010240
Hal Finkelcd8664c2015-12-11 23:11:52 +000010241 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10242 NewABD);
10243 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010244 }
10245
10246 // This is effectively a custom type legalization for AArch64.
10247 //
10248 // Type legalization will split an extend of a small, legal, type to a larger
10249 // illegal type by first splitting the destination type, often creating
10250 // illegal source types, which then get legalized in isel-confusing ways,
10251 // leading to really terrible codegen. E.g.,
10252 // %result = v8i32 sext v8i8 %value
10253 // becomes
10254 // %losrc = extract_subreg %value, ...
10255 // %hisrc = extract_subreg %value, ...
10256 // %lo = v4i32 sext v4i8 %losrc
10257 // %hi = v4i32 sext v4i8 %hisrc
10258 // Things go rapidly downhill from there.
10259 //
10260 // For AArch64, the [sz]ext vector instructions can only go up one element
10261 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10262 // take two instructions.
10263 //
10264 // This implies that the most efficient way to do the extend from v8i8
10265 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10266 // the normal splitting to happen for the v8i16->v8i32.
10267
10268 // This is pre-legalization to catch some cases where the default
10269 // type legalization will create ill-tempered code.
10270 if (!DCI.isBeforeLegalizeOps())
10271 return SDValue();
10272
10273 // We're only interested in cleaning things up for non-legal vector types
10274 // here. If both the source and destination are legal, things will just
10275 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010276 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010277 EVT ResVT = N->getValueType(0);
10278 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10279 return SDValue();
10280 // If the vector type isn't a simple VT, it's beyond the scope of what
10281 // we're worried about here. Let legalization do its thing and hope for
10282 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010283 SDValue Src = N->getOperand(0);
10284 EVT SrcVT = Src->getValueType(0);
10285 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010286 return SDValue();
10287
Tim Northover3b0846e2014-05-24 12:50:23 +000010288 // If the source VT is a 64-bit vector, we can play games and get the
10289 // better results we want.
10290 if (SrcVT.getSizeInBits() != 64)
10291 return SDValue();
10292
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010293 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010294 unsigned ElementCount = SrcVT.getVectorNumElements();
10295 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10296 SDLoc DL(N);
10297 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10298
10299 // Now split the rest of the operation into two halves, each with a 64
10300 // bit source.
10301 EVT LoVT, HiVT;
10302 SDValue Lo, Hi;
10303 unsigned NumElements = ResVT.getVectorNumElements();
10304 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10305 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10306 ResVT.getVectorElementType(), NumElements / 2);
10307
10308 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10309 LoVT.getVectorNumElements());
10310 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010311 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010312 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010313 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010314 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10315 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10316
10317 // Now combine the parts back together so we still have a single result
10318 // like the combiner expects.
10319 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10320}
10321
Geoff Berry8301c642016-11-16 19:35:19 +000010322static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10323 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010324 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010325 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010326 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010327
10328 // Create scalar stores. This is at least as good as the code sequence for a
10329 // split unaligned store which is a dup.s, ext.b, and two stores.
10330 // Most of the time the three stores should be replaced by store pair
10331 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010332 SDLoc DL(&St);
10333 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010334 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010335
John Brawn3a9c8422017-02-06 18:07:20 +000010336 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010337 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010338 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010339 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010340
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010341 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010342 if (BasePtr->getOpcode() == ISD::ADD &&
10343 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10344 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10345 BasePtr = BasePtr->getOperand(0);
10346 }
10347
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010348 unsigned Offset = EltOffset;
10349 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010350 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010351 SDValue OffsetPtr =
10352 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10353 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010354 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010355 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010356 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010357 Offset += EltOffset;
10358 }
10359 return NewST1;
10360}
10361
Geoff Berry526c5052016-11-14 19:39:04 +000010362/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10363/// load store optimizer pass will merge them to store pair stores. This should
10364/// be better than a movi to create the vector zero followed by a vector store
10365/// if the zero constant is not re-used, since one instructions and one register
10366/// live range will be removed.
10367///
10368/// For example, the final generated code should be:
10369///
10370/// stp xzr, xzr, [x0]
10371///
10372/// instead of:
10373///
10374/// movi v0.2d, #0
10375/// str q0, [x0]
10376///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010377static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10378 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010379 EVT VT = StVal.getValueType();
10380
Geoff Berry8301c642016-11-16 19:35:19 +000010381 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10382 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010383 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010384 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10385 VT.getVectorElementType().getSizeInBits() == 64) ||
10386 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10387 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010388 return SDValue();
10389
10390 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10391 return SDValue();
10392
10393 // If the zero constant has more than one use then the vector store could be
10394 // better since the constant mov will be amortized and stp q instructions
10395 // should be able to be formed.
10396 if (!StVal.hasOneUse())
10397 return SDValue();
10398
Tim Northover964eea72019-01-08 13:30:27 +000010399 // If the store is truncating then it's going down to i16 or smaller, which
10400 // means it can be implemented in a single store anyway.
10401 if (St.isTruncatingStore())
10402 return SDValue();
10403
Geoff Berry526c5052016-11-14 19:39:04 +000010404 // If the immediate offset of the address operand is too large for the stp
10405 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010406 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10407 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010408 if (Offset < -512 || Offset > 504)
10409 return SDValue();
10410 }
10411
10412 for (int I = 0; I < NumVecElts; ++I) {
10413 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010414 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010415 return SDValue();
10416 }
Geoff Berry8301c642016-11-16 19:35:19 +000010417
Geoff Berrybb23df92017-09-21 21:10:06 +000010418 // Use a CopyFromReg WZR/XZR here to prevent
10419 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10420 SDLoc DL(&St);
10421 unsigned ZeroReg;
10422 EVT ZeroVT;
10423 if (VT.getVectorElementType().getSizeInBits() == 32) {
10424 ZeroReg = AArch64::WZR;
10425 ZeroVT = MVT::i32;
10426 } else {
10427 ZeroReg = AArch64::XZR;
10428 ZeroVT = MVT::i64;
10429 }
10430 SDValue SplatVal =
10431 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010432 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010433}
10434
Tim Northover3b0846e2014-05-24 12:50:23 +000010435/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10436/// value. The load store optimizer pass will merge them to store pair stores.
10437/// This has better performance than a splat of the scalar followed by a split
10438/// vector store. Even if the stores are not merged it is four stores vs a dup,
10439/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010440static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10441 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010442 EVT VT = StVal.getValueType();
10443
10444 // Don't replace floating point stores, they possibly won't be transformed to
10445 // stp because of the store pair suppress pass.
10446 if (VT.isFloatingPoint())
10447 return SDValue();
10448
Tim Northover3b0846e2014-05-24 12:50:23 +000010449 // We can express a splat as store pair(s) for 2 or 4 elements.
10450 unsigned NumVecElts = VT.getVectorNumElements();
10451 if (NumVecElts != 4 && NumVecElts != 2)
10452 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010453
Tim Northover964eea72019-01-08 13:30:27 +000010454 // If the store is truncating then it's going down to i16 or smaller, which
10455 // means it can be implemented in a single store anyway.
10456 if (St.isTruncatingStore())
10457 return SDValue();
10458
Tim Northover3b0846e2014-05-24 12:50:23 +000010459 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010460 // Make sure that each of the relevant vector element locations are inserted
10461 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10462 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10463 SDValue SplatVal;
10464 for (unsigned I = 0; I < NumVecElts; ++I) {
10465 // Check for insert vector elements.
10466 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010467 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010468
10469 // Check that same value is inserted at each vector element.
10470 if (I == 0)
10471 SplatVal = StVal.getOperand(1);
10472 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010473 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010474
10475 // Check insert element index.
10476 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10477 if (!CIndex)
10478 return SDValue();
10479 uint64_t IndexVal = CIndex->getZExtValue();
10480 if (IndexVal >= NumVecElts)
10481 return SDValue();
10482 IndexNotInserted.reset(IndexVal);
10483
10484 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010485 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010486 // Check that all vector element locations were inserted to.
10487 if (IndexNotInserted.any())
10488 return SDValue();
10489
Geoff Berry8301c642016-11-16 19:35:19 +000010490 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010491}
10492
Geoff Berry8301c642016-11-16 19:35:19 +000010493static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10494 SelectionDAG &DAG,
10495 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010496
10497 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010498 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010499 return SDValue();
10500
Geoff Berry526c5052016-11-14 19:39:04 +000010501 SDValue StVal = S->getValue();
10502 EVT VT = StVal.getValueType();
10503 if (!VT.isVector())
10504 return SDValue();
10505
10506 // If we get a splat of zeros, convert this vector store to a store of
10507 // scalars. They will be merged into store pairs of xzr thereby removing one
10508 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010509 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010510 return ReplacedZeroSplat;
10511
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010512 // FIXME: The logic for deciding if an unaligned store should be split should
10513 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10514 // a call to that function here.
10515
Matthias Braun651cff42016-06-02 18:03:53 +000010516 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010517 return SDValue();
10518
Sanjay Patel924879a2015-08-04 15:49:57 +000010519 // Don't split at -Oz.
Evandro Menezes85bd3972019-04-04 22:40:06 +000010520 if (DAG.getMachineFunction().getFunction().hasMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010521 return SDValue();
10522
Tim Northover3b0846e2014-05-24 12:50:23 +000010523 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10524 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010525 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010526 return SDValue();
10527
10528 // Split unaligned 16B stores. They are terrible for performance.
10529 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10530 // extensions can use this to mark that it does not want splitting to happen
10531 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10532 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10533 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10534 S->getAlignment() <= 2)
10535 return SDValue();
10536
10537 // If we get a splat of a scalar convert this vector store to a store of
10538 // scalars. They will be merged into store pairs thereby removing two
10539 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010540 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010541 return ReplacedSplat;
10542
10543 SDLoc DL(S);
10544 unsigned NumElts = VT.getVectorNumElements() / 2;
10545 // Split VT into two.
10546 EVT HalfVT =
10547 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10548 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010549 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010550 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010551 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010552 SDValue BasePtr = S->getBasePtr();
10553 SDValue NewST1 =
10554 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010555 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010556 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010557 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010558 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010559 S->getPointerInfo(), S->getAlignment(),
10560 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010561}
10562
10563/// Target-specific DAG combine function for post-increment LD1 (lane) and
10564/// post-increment LD1R.
10565static SDValue performPostLD1Combine(SDNode *N,
10566 TargetLowering::DAGCombinerInfo &DCI,
10567 bool IsLaneOp) {
10568 if (DCI.isBeforeLegalizeOps())
10569 return SDValue();
10570
10571 SelectionDAG &DAG = DCI.DAG;
10572 EVT VT = N->getValueType(0);
10573
10574 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10575 SDNode *LD = N->getOperand(LoadIdx).getNode();
10576 // If it is not LOAD, can not do such combine.
10577 if (LD->getOpcode() != ISD::LOAD)
10578 return SDValue();
10579
Geoff Berry60460262018-05-11 16:25:06 +000010580 // The vector lane must be a constant in the LD1LANE opcode.
10581 SDValue Lane;
10582 if (IsLaneOp) {
10583 Lane = N->getOperand(2);
10584 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10585 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10586 return SDValue();
10587 }
10588
Tim Northover3b0846e2014-05-24 12:50:23 +000010589 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10590 EVT MemVT = LoadSDN->getMemoryVT();
10591 // Check if memory operand is the same type as the vector element.
10592 if (MemVT != VT.getVectorElementType())
10593 return SDValue();
10594
10595 // Check if there are other uses. If so, do not combine as it will introduce
10596 // an extra load.
10597 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10598 ++UI) {
10599 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10600 continue;
10601 if (*UI != N)
10602 return SDValue();
10603 }
10604
10605 SDValue Addr = LD->getOperand(1);
10606 SDValue Vector = N->getOperand(0);
10607 // Search for a use of the address operand that is an increment.
10608 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10609 Addr.getNode()->use_end(); UI != UE; ++UI) {
10610 SDNode *User = *UI;
10611 if (User->getOpcode() != ISD::ADD
10612 || UI.getUse().getResNo() != Addr.getResNo())
10613 continue;
10614
Tim Northover3b0846e2014-05-24 12:50:23 +000010615 // If the increment is a constant, it must match the memory ref size.
10616 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10617 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10618 uint32_t IncVal = CInc->getZExtValue();
10619 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10620 if (IncVal != NumBytes)
10621 continue;
10622 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10623 }
10624
Nirav Davee40e2bb2018-09-25 15:30:22 +000010625 // To avoid cycle construction make sure that neither the load nor the add
10626 // are predecessors to each other or the Vector.
10627 SmallPtrSet<const SDNode *, 32> Visited;
10628 SmallVector<const SDNode *, 16> Worklist;
10629 Visited.insert(N);
10630 Worklist.push_back(User);
10631 Worklist.push_back(LD);
10632 Worklist.push_back(Vector.getNode());
10633 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10634 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010635 continue;
10636
Tim Northover3b0846e2014-05-24 12:50:23 +000010637 SmallVector<SDValue, 8> Ops;
10638 Ops.push_back(LD->getOperand(0)); // Chain
10639 if (IsLaneOp) {
10640 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010641 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010642 }
10643 Ops.push_back(Addr);
10644 Ops.push_back(Inc);
10645
10646 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010647 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010648 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10649 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10650 MemVT,
10651 LoadSDN->getMemOperand());
10652
10653 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010654 SDValue NewResults[] = {
10655 SDValue(LD, 0), // The result of load
10656 SDValue(UpdN.getNode(), 2) // Chain
10657 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010658 DCI.CombineTo(LD, NewResults);
10659 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10660 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10661
10662 break;
10663 }
10664 return SDValue();
10665}
10666
Joel Jones7466ccf2017-07-10 22:11:50 +000010667/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010668/// address translation.
10669static bool performTBISimplification(SDValue Addr,
10670 TargetLowering::DAGCombinerInfo &DCI,
10671 SelectionDAG &DAG) {
10672 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010673 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010674 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10675 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010677 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010678 DCI.CommitTargetLoweringOpt(TLO);
10679 return true;
10680 }
10681 return false;
10682}
10683
10684static SDValue performSTORECombine(SDNode *N,
10685 TargetLowering::DAGCombinerInfo &DCI,
10686 SelectionDAG &DAG,
10687 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010688 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010689 return Split;
10690
10691 if (Subtarget->supportsAddressTopByteIgnored() &&
10692 performTBISimplification(N->getOperand(2), DCI, DAG))
10693 return SDValue(N, 0);
10694
10695 return SDValue();
10696}
10697
Chad Rosier6c36eff2015-09-03 18:13:57 +000010698
Tim Northover3b0846e2014-05-24 12:50:23 +000010699/// Target-specific DAG combine function for NEON load/store intrinsics
10700/// to merge base address updates.
10701static SDValue performNEONPostLDSTCombine(SDNode *N,
10702 TargetLowering::DAGCombinerInfo &DCI,
10703 SelectionDAG &DAG) {
10704 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10705 return SDValue();
10706
10707 unsigned AddrOpIdx = N->getNumOperands() - 1;
10708 SDValue Addr = N->getOperand(AddrOpIdx);
10709
10710 // Search for a use of the address operand that is an increment.
10711 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10712 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10713 SDNode *User = *UI;
10714 if (User->getOpcode() != ISD::ADD ||
10715 UI.getUse().getResNo() != Addr.getResNo())
10716 continue;
10717
10718 // Check that the add is independent of the load/store. Otherwise, folding
10719 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010720 SmallPtrSet<const SDNode *, 32> Visited;
10721 SmallVector<const SDNode *, 16> Worklist;
10722 Visited.insert(Addr.getNode());
10723 Worklist.push_back(N);
10724 Worklist.push_back(User);
10725 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10726 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010727 continue;
10728
10729 // Find the new opcode for the updating load/store.
10730 bool IsStore = false;
10731 bool IsLaneOp = false;
10732 bool IsDupOp = false;
10733 unsigned NewOpc = 0;
10734 unsigned NumVecs = 0;
10735 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10736 switch (IntNo) {
10737 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10738 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10739 NumVecs = 2; break;
10740 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10741 NumVecs = 3; break;
10742 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10743 NumVecs = 4; break;
10744 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10745 NumVecs = 2; IsStore = true; break;
10746 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10747 NumVecs = 3; IsStore = true; break;
10748 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10749 NumVecs = 4; IsStore = true; break;
10750 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10751 NumVecs = 2; break;
10752 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10753 NumVecs = 3; break;
10754 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10755 NumVecs = 4; break;
10756 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10757 NumVecs = 2; IsStore = true; break;
10758 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10759 NumVecs = 3; IsStore = true; break;
10760 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10761 NumVecs = 4; IsStore = true; break;
10762 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10763 NumVecs = 2; IsDupOp = true; break;
10764 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10765 NumVecs = 3; IsDupOp = true; break;
10766 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10767 NumVecs = 4; IsDupOp = true; break;
10768 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10769 NumVecs = 2; IsLaneOp = true; break;
10770 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10771 NumVecs = 3; IsLaneOp = true; break;
10772 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10773 NumVecs = 4; IsLaneOp = true; break;
10774 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10775 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10776 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10777 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10778 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10779 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10780 }
10781
10782 EVT VecTy;
10783 if (IsStore)
10784 VecTy = N->getOperand(2).getValueType();
10785 else
10786 VecTy = N->getValueType(0);
10787
10788 // If the increment is a constant, it must match the memory ref size.
10789 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10790 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10791 uint32_t IncVal = CInc->getZExtValue();
10792 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10793 if (IsLaneOp || IsDupOp)
10794 NumBytes /= VecTy.getVectorNumElements();
10795 if (IncVal != NumBytes)
10796 continue;
10797 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10798 }
10799 SmallVector<SDValue, 8> Ops;
10800 Ops.push_back(N->getOperand(0)); // Incoming chain
10801 // Load lane and store have vector list as input.
10802 if (IsLaneOp || IsStore)
10803 for (unsigned i = 2; i < AddrOpIdx; ++i)
10804 Ops.push_back(N->getOperand(i));
10805 Ops.push_back(Addr); // Base register
10806 Ops.push_back(Inc);
10807
10808 // Return Types.
10809 EVT Tys[6];
10810 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10811 unsigned n;
10812 for (n = 0; n < NumResultVecs; ++n)
10813 Tys[n] = VecTy;
10814 Tys[n++] = MVT::i64; // Type of write back register
10815 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010816 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010817
10818 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10819 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10820 MemInt->getMemoryVT(),
10821 MemInt->getMemOperand());
10822
10823 // Update the uses.
10824 std::vector<SDValue> NewResults;
10825 for (unsigned i = 0; i < NumResultVecs; ++i) {
10826 NewResults.push_back(SDValue(UpdN.getNode(), i));
10827 }
10828 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10829 DCI.CombineTo(N, NewResults);
10830 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10831
10832 break;
10833 }
10834 return SDValue();
10835}
10836
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010837// Checks to see if the value is the prescribed width and returns information
10838// about its extension mode.
10839static
10840bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10841 ExtType = ISD::NON_EXTLOAD;
10842 switch(V.getNode()->getOpcode()) {
10843 default:
10844 return false;
10845 case ISD::LOAD: {
10846 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10847 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10848 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10849 ExtType = LoadNode->getExtensionType();
10850 return true;
10851 }
10852 return false;
10853 }
10854 case ISD::AssertSext: {
10855 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10856 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10857 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10858 ExtType = ISD::SEXTLOAD;
10859 return true;
10860 }
10861 return false;
10862 }
10863 case ISD::AssertZext: {
10864 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10865 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10866 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10867 ExtType = ISD::ZEXTLOAD;
10868 return true;
10869 }
10870 return false;
10871 }
10872 case ISD::Constant:
10873 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010874 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10875 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010876 }
10877 }
10878
10879 return true;
10880}
10881
10882// This function does a whole lot of voodoo to determine if the tests are
10883// equivalent without and with a mask. Essentially what happens is that given a
10884// DAG resembling:
10885//
10886// +-------------+ +-------------+ +-------------+ +-------------+
10887// | Input | | AddConstant | | CompConstant| | CC |
10888// +-------------+ +-------------+ +-------------+ +-------------+
10889// | | | |
10890// V V | +----------+
10891// +-------------+ +----+ | |
10892// | ADD | |0xff| | |
10893// +-------------+ +----+ | |
10894// | | | |
10895// V V | |
10896// +-------------+ | |
10897// | AND | | |
10898// +-------------+ | |
10899// | | |
10900// +-----+ | |
10901// | | |
10902// V V V
10903// +-------------+
10904// | CMP |
10905// +-------------+
10906//
10907// The AND node may be safely removed for some combinations of inputs. In
10908// particular we need to take into account the extension type of the Input,
10909// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10910// width of the input (this can work for any width inputs, the above graph is
10911// specific to 8 bits.
10912//
10913// The specific equations were worked out by generating output tables for each
10914// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10915// problem was simplified by working with 4 bit inputs, which means we only
10916// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10917// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10918// patterns present in both extensions (0,7). For every distinct set of
10919// AddConstant and CompConstants bit patterns we can consider the masked and
10920// unmasked versions to be equivalent if the result of this function is true for
10921// all 16 distinct bit patterns of for the current extension type of Input (w0).
10922//
10923// sub w8, w0, w1
10924// and w10, w8, #0x0f
10925// cmp w8, w2
10926// cset w9, AArch64CC
10927// cmp w10, w2
10928// cset w11, AArch64CC
10929// cmp w9, w11
10930// cset w0, eq
10931// ret
10932//
10933// Since the above function shows when the outputs are equivalent it defines
10934// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10935// would be expensive to run during compiles. The equations below were written
10936// in a test harness that confirmed they gave equivalent outputs to the above
10937// for all inputs function, so they can be used determine if the removal is
10938// legal instead.
10939//
10940// isEquivalentMaskless() is the code for testing if the AND can be removed
10941// factored out of the DAG recognition as the DAG can take several forms.
10942
David Majnemere61e4bf2016-06-21 05:10:24 +000010943static bool isEquivalentMaskless(unsigned CC, unsigned width,
10944 ISD::LoadExtType ExtType, int AddConstant,
10945 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010946 // By being careful about our equations and only writing the in term
10947 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10948 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010949 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010950
10951 // For the purposes of these comparisons sign extending the type is
10952 // equivalent to zero extending the add and displacing it by half the integer
10953 // width. Provided we are careful and make sure our equations are valid over
10954 // the whole range we can just adjust the input and avoid writing equations
10955 // for sign extended inputs.
10956 if (ExtType == ISD::SEXTLOAD)
10957 AddConstant -= (1 << (width-1));
10958
10959 switch(CC) {
10960 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010961 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010962 if ((AddConstant == 0) ||
10963 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10964 (AddConstant >= 0 && CompConstant < 0) ||
10965 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10966 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010967 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010968 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010969 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010970 if ((AddConstant == 0) ||
10971 (AddConstant >= 0 && CompConstant <= 0) ||
10972 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10973 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010974 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010975 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010976 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010977 if ((AddConstant >= 0 && CompConstant < 0) ||
10978 (AddConstant <= 0 && CompConstant >= -1 &&
10979 CompConstant < AddConstant + MaxUInt))
10980 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010981 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010982 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010983 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010984 if ((AddConstant == 0) ||
10985 (AddConstant > 0 && CompConstant <= 0) ||
10986 (AddConstant < 0 && CompConstant <= AddConstant))
10987 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010988 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010989 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010990 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010991 if ((AddConstant >= 0 && CompConstant <= 0) ||
10992 (AddConstant <= 0 && CompConstant >= 0 &&
10993 CompConstant <= AddConstant + MaxUInt))
10994 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010995 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010996 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010997 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010998 if ((AddConstant > 0 && CompConstant < 0) ||
10999 (AddConstant < 0 && CompConstant >= 0 &&
11000 CompConstant < AddConstant + MaxUInt) ||
11001 (AddConstant >= 0 && CompConstant >= 0 &&
11002 CompConstant >= AddConstant) ||
11003 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011004 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011005 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011006 case AArch64CC::VS:
11007 case AArch64CC::VC:
11008 case AArch64CC::AL:
11009 case AArch64CC::NV:
11010 return true;
11011 case AArch64CC::Invalid:
11012 break;
11013 }
11014
11015 return false;
11016}
11017
11018static
11019SDValue performCONDCombine(SDNode *N,
11020 TargetLowering::DAGCombinerInfo &DCI,
11021 SelectionDAG &DAG, unsigned CCIndex,
11022 unsigned CmpIndex) {
11023 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11024 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11025 unsigned CondOpcode = SubsNode->getOpcode();
11026
11027 if (CondOpcode != AArch64ISD::SUBS)
11028 return SDValue();
11029
11030 // There is a SUBS feeding this condition. Is it fed by a mask we can
11031 // use?
11032
11033 SDNode *AndNode = SubsNode->getOperand(0).getNode();
11034 unsigned MaskBits = 0;
11035
11036 if (AndNode->getOpcode() != ISD::AND)
11037 return SDValue();
11038
11039 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11040 uint32_t CNV = CN->getZExtValue();
11041 if (CNV == 255)
11042 MaskBits = 8;
11043 else if (CNV == 65535)
11044 MaskBits = 16;
11045 }
11046
11047 if (!MaskBits)
11048 return SDValue();
11049
11050 SDValue AddValue = AndNode->getOperand(0);
11051
11052 if (AddValue.getOpcode() != ISD::ADD)
11053 return SDValue();
11054
11055 // The basic dag structure is correct, grab the inputs and validate them.
11056
11057 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11058 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11059 SDValue SubsInputValue = SubsNode->getOperand(1);
11060
11061 // The mask is present and the provenance of all the values is a smaller type,
11062 // lets see if the mask is superfluous.
11063
11064 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11065 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11066 return SDValue();
11067
11068 ISD::LoadExtType ExtType;
11069
11070 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11071 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11072 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11073 return SDValue();
11074
11075 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11076 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11077 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11078 return SDValue();
11079
11080 // The AND is not necessary, remove it.
11081
11082 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11083 SubsNode->getValueType(1));
11084 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11085
11086 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11087 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11088
11089 return SDValue(N, 0);
11090}
11091
Tim Northover3b0846e2014-05-24 12:50:23 +000011092// Optimize compare with zero and branch.
11093static SDValue performBRCONDCombine(SDNode *N,
11094 TargetLowering::DAGCombinerInfo &DCI,
11095 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000011096 MachineFunction &MF = DAG.getMachineFunction();
11097 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11098 // will not be produced, as they are conditional branch instructions that do
11099 // not set flags.
11100 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11101 return SDValue();
11102
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000011103 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011104 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000011105 SDValue Chain = N->getOperand(0);
11106 SDValue Dest = N->getOperand(1);
11107 SDValue CCVal = N->getOperand(2);
11108 SDValue Cmp = N->getOperand(3);
11109
11110 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11111 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11112 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11113 return SDValue();
11114
11115 unsigned CmpOpc = Cmp.getOpcode();
11116 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11117 return SDValue();
11118
11119 // Only attempt folding if there is only one use of the flag and no use of the
11120 // value.
11121 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11122 return SDValue();
11123
11124 SDValue LHS = Cmp.getOperand(0);
11125 SDValue RHS = Cmp.getOperand(1);
11126
11127 assert(LHS.getValueType() == RHS.getValueType() &&
11128 "Expected the value type to be the same for both operands!");
11129 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11130 return SDValue();
11131
Artyom Skrobov314ee042015-11-25 19:41:11 +000011132 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011133 std::swap(LHS, RHS);
11134
Artyom Skrobov314ee042015-11-25 19:41:11 +000011135 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011136 return SDValue();
11137
11138 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11139 LHS.getOpcode() == ISD::SRL)
11140 return SDValue();
11141
11142 // Fold the compare into the branch instruction.
11143 SDValue BR;
11144 if (CC == AArch64CC::EQ)
11145 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11146 else
11147 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11148
11149 // Do not add new nodes to DAG combiner worklist.
11150 DCI.CombineTo(N, BR, false);
11151
11152 return SDValue();
11153}
11154
Geoff Berry9e934b02016-01-04 18:55:47 +000011155// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11156// as well as whether the test should be inverted. This code is required to
11157// catch these cases (as opposed to standard dag combines) because
11158// AArch64ISD::TBZ is matched during legalization.
11159static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11160 SelectionDAG &DAG) {
11161
11162 if (!Op->hasOneUse())
11163 return Op;
11164
11165 // We don't handle undef/constant-fold cases below, as they should have
11166 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11167 // etc.)
11168
11169 // (tbz (trunc x), b) -> (tbz x, b)
11170 // This case is just here to enable more of the below cases to be caught.
11171 if (Op->getOpcode() == ISD::TRUNCATE &&
11172 Bit < Op->getValueType(0).getSizeInBits()) {
11173 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11174 }
11175
Craig Topper35fe0792019-04-10 17:27:29 +000011176 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11177 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11178 Bit < Op->getOperand(0).getValueSizeInBits()) {
11179 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11180 }
11181
Geoff Berry9e934b02016-01-04 18:55:47 +000011182 if (Op->getNumOperands() != 2)
11183 return Op;
11184
11185 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11186 if (!C)
11187 return Op;
11188
11189 switch (Op->getOpcode()) {
11190 default:
11191 return Op;
11192
11193 // (tbz (and x, m), b) -> (tbz x, b)
11194 case ISD::AND:
11195 if ((C->getZExtValue() >> Bit) & 1)
11196 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11197 return Op;
11198
11199 // (tbz (shl x, c), b) -> (tbz x, b-c)
11200 case ISD::SHL:
11201 if (C->getZExtValue() <= Bit &&
11202 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11203 Bit = Bit - C->getZExtValue();
11204 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11205 }
11206 return Op;
11207
11208 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11209 case ISD::SRA:
11210 Bit = Bit + C->getZExtValue();
11211 if (Bit >= Op->getValueType(0).getSizeInBits())
11212 Bit = Op->getValueType(0).getSizeInBits() - 1;
11213 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11214
11215 // (tbz (srl x, c), b) -> (tbz x, b+c)
11216 case ISD::SRL:
11217 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11218 Bit = Bit + C->getZExtValue();
11219 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11220 }
11221 return Op;
11222
11223 // (tbz (xor x, -1), b) -> (tbnz x, b)
11224 case ISD::XOR:
11225 if ((C->getZExtValue() >> Bit) & 1)
11226 Invert = !Invert;
11227 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11228 }
11229}
11230
11231// Optimize test single bit zero/non-zero and branch.
11232static SDValue performTBZCombine(SDNode *N,
11233 TargetLowering::DAGCombinerInfo &DCI,
11234 SelectionDAG &DAG) {
11235 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11236 bool Invert = false;
11237 SDValue TestSrc = N->getOperand(1);
11238 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11239
11240 if (TestSrc == NewTestSrc)
11241 return SDValue();
11242
11243 unsigned NewOpc = N->getOpcode();
11244 if (Invert) {
11245 if (NewOpc == AArch64ISD::TBZ)
11246 NewOpc = AArch64ISD::TBNZ;
11247 else {
11248 assert(NewOpc == AArch64ISD::TBNZ);
11249 NewOpc = AArch64ISD::TBZ;
11250 }
11251 }
11252
11253 SDLoc DL(N);
11254 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11255 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11256}
11257
Tim Northover3b0846e2014-05-24 12:50:23 +000011258// vselect (v1i1 setcc) ->
11259// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11260// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11261// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11262// such VSELECT.
11263static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11264 SDValue N0 = N->getOperand(0);
11265 EVT CCVT = N0.getValueType();
11266
11267 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11268 CCVT.getVectorElementType() != MVT::i1)
11269 return SDValue();
11270
11271 EVT ResVT = N->getValueType(0);
11272 EVT CmpVT = N0.getOperand(0).getValueType();
11273 // Only combine when the result type is of the same size as the compared
11274 // operands.
11275 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11276 return SDValue();
11277
11278 SDValue IfTrue = N->getOperand(1);
11279 SDValue IfFalse = N->getOperand(2);
11280 SDValue SetCC =
11281 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11282 N0.getOperand(0), N0.getOperand(1),
11283 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11284 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11285 IfTrue, IfFalse);
11286}
11287
11288/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11289/// the compare-mask instructions rather than going via NZCV, even if LHS and
11290/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11291/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011292static SDValue performSelectCombine(SDNode *N,
11293 TargetLowering::DAGCombinerInfo &DCI) {
11294 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011295 SDValue N0 = N->getOperand(0);
11296 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011297
Ahmed Bougachac004c602015-04-27 21:43:12 +000011298 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011299 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011300
Ahmed Bougachac004c602015-04-27 21:43:12 +000011301 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11302 // scalar SetCCResultType. We also don't expect vectors, because we assume
11303 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11304 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11305 "Scalar-SETCC feeding SELECT has unexpected result type!");
11306
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011307 // If NumMaskElts == 0, the comparison is larger than select result. The
11308 // largest real NEON comparison is 64-bits per lane, which means the result is
11309 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011310 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011311
11312 // Don't try to do this optimization when the setcc itself has i1 operands.
11313 // There are no legal vectors of i1, so this would be pointless.
11314 if (SrcVT == MVT::i1)
11315 return SDValue();
11316
Tim Northover3c0915e2014-08-29 15:34:58 +000011317 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011318 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011319 return SDValue();
11320
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011321 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011322 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11323
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011324 // Also bail out if the vector CCVT isn't the same size as ResVT.
11325 // This can happen if the SETCC operand size doesn't divide the ResVT size
11326 // (e.g., f64 vs v3f32).
11327 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11328 return SDValue();
11329
Ahmed Bougachac004c602015-04-27 21:43:12 +000011330 // Make sure we didn't create illegal types, if we're not supposed to.
11331 assert(DCI.isBeforeLegalize() ||
11332 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11333
Tim Northover3b0846e2014-05-24 12:50:23 +000011334 // First perform a vector comparison, where lane 0 is the one we're interested
11335 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011336 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011337 SDValue LHS =
11338 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11339 SDValue RHS =
11340 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11341 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11342
11343 // Now duplicate the comparison mask we want across all other lanes.
11344 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011345 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011346 Mask = DAG.getNode(ISD::BITCAST, DL,
11347 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011348
11349 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11350}
11351
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011352/// Get rid of unnecessary NVCASTs (that don't change the type).
11353static SDValue performNVCASTCombine(SDNode *N) {
11354 if (N->getValueType(0) == N->getOperand(0).getValueType())
11355 return N->getOperand(0);
11356
11357 return SDValue();
11358}
11359
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011360// If all users of the globaladdr are of the form (globaladdr + constant), find
11361// the smallest constant, fold it into the globaladdr's offset and rewrite the
11362// globaladdr as (globaladdr + constant) - constant.
11363static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11364 const AArch64Subtarget *Subtarget,
11365 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011366 auto *GN = cast<GlobalAddressSDNode>(N);
11367 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11368 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011369 return SDValue();
11370
11371 uint64_t MinOffset = -1ull;
11372 for (SDNode *N : GN->uses()) {
11373 if (N->getOpcode() != ISD::ADD)
11374 return SDValue();
11375 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11376 if (!C)
11377 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11378 if (!C)
11379 return SDValue();
11380 MinOffset = std::min(MinOffset, C->getZExtValue());
11381 }
11382 uint64_t Offset = MinOffset + GN->getOffset();
11383
11384 // Require that the new offset is larger than the existing one. Otherwise, we
11385 // can end up oscillating between two possible DAGs, for example,
11386 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11387 if (Offset <= uint64_t(GN->getOffset()))
11388 return SDValue();
11389
11390 // Check whether folding this offset is legal. It must not go out of bounds of
11391 // the referenced object to avoid violating the code model, and must be
11392 // smaller than 2^21 because this is the largest offset expressible in all
11393 // object formats.
11394 //
11395 // This check also prevents us from folding negative offsets, which will end
11396 // up being treated in the same way as large positive ones. They could also
11397 // cause code model violations, and aren't really common enough to matter.
11398 if (Offset >= (1 << 21))
11399 return SDValue();
11400
11401 const GlobalValue *GV = GN->getGlobal();
11402 Type *T = GV->getValueType();
11403 if (!T->isSized() ||
11404 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11405 return SDValue();
11406
11407 SDLoc DL(GN);
11408 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11409 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11410 DAG.getConstant(MinOffset, DL, MVT::i64));
11411}
11412
Tim Northover3b0846e2014-05-24 12:50:23 +000011413SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11414 DAGCombinerInfo &DCI) const {
11415 SelectionDAG &DAG = DCI.DAG;
11416 switch (N->getOpcode()) {
11417 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011418 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011419 break;
11420 case ISD::ADD:
11421 case ISD::SUB:
11422 return performAddSubLongCombine(N, DCI, DAG);
11423 case ISD::XOR:
11424 return performXorCombine(N, DAG, DCI, Subtarget);
11425 case ISD::MUL:
11426 return performMulCombine(N, DAG, DCI, Subtarget);
11427 case ISD::SINT_TO_FP:
11428 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011429 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011430 case ISD::FP_TO_SINT:
11431 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011432 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011433 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011434 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011435 case ISD::OR:
11436 return performORCombine(N, DCI, Subtarget);
Nikita Popov1a261442019-03-15 21:04:34 +000011437 case ISD::AND:
11438 return performANDCombine(N, DCI);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011439 case ISD::SRL:
11440 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011441 case ISD::INTRINSIC_WO_CHAIN:
11442 return performIntrinsicCombine(N, DCI, Subtarget);
11443 case ISD::ANY_EXTEND:
11444 case ISD::ZERO_EXTEND:
11445 case ISD::SIGN_EXTEND:
11446 return performExtendCombine(N, DCI, DAG);
11447 case ISD::BITCAST:
11448 return performBitcastCombine(N, DCI, DAG);
11449 case ISD::CONCAT_VECTORS:
11450 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011451 case ISD::SELECT:
11452 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011453 case ISD::VSELECT:
11454 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011455 case ISD::LOAD:
11456 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11457 return SDValue(N, 0);
11458 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011459 case ISD::STORE:
11460 return performSTORECombine(N, DCI, DAG, Subtarget);
11461 case AArch64ISD::BRCOND:
11462 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011463 case AArch64ISD::TBNZ:
11464 case AArch64ISD::TBZ:
11465 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011466 case AArch64ISD::CSEL:
11467 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011468 case AArch64ISD::DUP:
11469 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011470 case AArch64ISD::NVCAST:
11471 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011472 case ISD::INSERT_VECTOR_ELT:
11473 return performPostLD1Combine(N, DCI, true);
11474 case ISD::INTRINSIC_VOID:
11475 case ISD::INTRINSIC_W_CHAIN:
11476 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11477 case Intrinsic::aarch64_neon_ld2:
11478 case Intrinsic::aarch64_neon_ld3:
11479 case Intrinsic::aarch64_neon_ld4:
11480 case Intrinsic::aarch64_neon_ld1x2:
11481 case Intrinsic::aarch64_neon_ld1x3:
11482 case Intrinsic::aarch64_neon_ld1x4:
11483 case Intrinsic::aarch64_neon_ld2lane:
11484 case Intrinsic::aarch64_neon_ld3lane:
11485 case Intrinsic::aarch64_neon_ld4lane:
11486 case Intrinsic::aarch64_neon_ld2r:
11487 case Intrinsic::aarch64_neon_ld3r:
11488 case Intrinsic::aarch64_neon_ld4r:
11489 case Intrinsic::aarch64_neon_st2:
11490 case Intrinsic::aarch64_neon_st3:
11491 case Intrinsic::aarch64_neon_st4:
11492 case Intrinsic::aarch64_neon_st1x2:
11493 case Intrinsic::aarch64_neon_st1x3:
11494 case Intrinsic::aarch64_neon_st1x4:
11495 case Intrinsic::aarch64_neon_st2lane:
11496 case Intrinsic::aarch64_neon_st3lane:
11497 case Intrinsic::aarch64_neon_st4lane:
11498 return performNEONPostLDSTCombine(N, DCI, DAG);
11499 default:
11500 break;
11501 }
Reid Klecknereb568942018-11-01 18:02:27 +000011502 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011503 case ISD::GlobalAddress:
11504 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011505 }
11506 return SDValue();
11507}
11508
11509// Check if the return value is used as only a return value, as otherwise
11510// we can't perform a tail-call. In particular, we need to check for
11511// target ISD nodes that are returns and any other "odd" constructs
11512// that the generic analysis code won't necessarily catch.
11513bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11514 SDValue &Chain) const {
11515 if (N->getNumValues() != 1)
11516 return false;
11517 if (!N->hasNUsesOfValue(1, 0))
11518 return false;
11519
11520 SDValue TCChain = Chain;
11521 SDNode *Copy = *N->use_begin();
11522 if (Copy->getOpcode() == ISD::CopyToReg) {
11523 // If the copy has a glue operand, we conservatively assume it isn't safe to
11524 // perform a tail call.
11525 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11526 MVT::Glue)
11527 return false;
11528 TCChain = Copy->getOperand(0);
11529 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11530 return false;
11531
11532 bool HasRet = false;
11533 for (SDNode *Node : Copy->uses()) {
11534 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11535 return false;
11536 HasRet = true;
11537 }
11538
11539 if (!HasRet)
11540 return false;
11541
11542 Chain = TCChain;
11543 return true;
11544}
11545
11546// Return whether the an instruction can potentially be optimized to a tail
11547// call. This will cause the optimizers to attempt to move, or duplicate,
11548// return instructions to help enable tail call optimizations for this
11549// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011550bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011551 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011552}
11553
11554bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11555 SDValue &Offset,
11556 ISD::MemIndexedMode &AM,
11557 bool &IsInc,
11558 SelectionDAG &DAG) const {
11559 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11560 return false;
11561
11562 Base = Op->getOperand(0);
11563 // All of the indexed addressing mode instructions take a signed
11564 // 9 bit immediate offset.
11565 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011566 int64_t RHSC = RHS->getSExtValue();
11567 if (Op->getOpcode() == ISD::SUB)
11568 RHSC = -(uint64_t)RHSC;
11569 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011570 return false;
11571 IsInc = (Op->getOpcode() == ISD::ADD);
11572 Offset = Op->getOperand(1);
11573 return true;
11574 }
11575 return false;
11576}
11577
11578bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11579 SDValue &Offset,
11580 ISD::MemIndexedMode &AM,
11581 SelectionDAG &DAG) const {
11582 EVT VT;
11583 SDValue Ptr;
11584 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11585 VT = LD->getMemoryVT();
11586 Ptr = LD->getBasePtr();
11587 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11588 VT = ST->getMemoryVT();
11589 Ptr = ST->getBasePtr();
11590 } else
11591 return false;
11592
11593 bool IsInc;
11594 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11595 return false;
11596 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11597 return true;
11598}
11599
11600bool AArch64TargetLowering::getPostIndexedAddressParts(
11601 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11602 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11603 EVT VT;
11604 SDValue Ptr;
11605 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11606 VT = LD->getMemoryVT();
11607 Ptr = LD->getBasePtr();
11608 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11609 VT = ST->getMemoryVT();
11610 Ptr = ST->getBasePtr();
11611 } else
11612 return false;
11613
11614 bool IsInc;
11615 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11616 return false;
11617 // Post-indexing updates the base, so it's not a valid transform
11618 // if that's not the same as the load's pointer.
11619 if (Ptr != Base)
11620 return false;
11621 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11622 return true;
11623}
11624
Tim Northoverf8bfe212014-07-18 13:07:05 +000011625static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11626 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011627 SDLoc DL(N);
11628 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011629
11630 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11631 return;
11632
Tim Northoverf8bfe212014-07-18 13:07:05 +000011633 Op = SDValue(
11634 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11635 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011636 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011637 0);
11638 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11639 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11640}
11641
Charlie Turner434d4592015-10-16 15:38:25 +000011642static void ReplaceReductionResults(SDNode *N,
11643 SmallVectorImpl<SDValue> &Results,
11644 SelectionDAG &DAG, unsigned InterOp,
11645 unsigned AcrossOp) {
11646 EVT LoVT, HiVT;
11647 SDValue Lo, Hi;
11648 SDLoc dl(N);
11649 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11650 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11651 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11652 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11653 Results.push_back(SplitVal);
11654}
11655
Tim Northover2f32e7f2016-08-04 19:32:28 +000011656static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11657 SDLoc DL(N);
11658 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11659 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11660 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11661 DAG.getConstant(64, DL, MVT::i64)));
11662 return std::make_pair(Lo, Hi);
11663}
11664
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011665// Create an even/odd pair of X registers holding integer value V.
11666static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11667 SDLoc dl(V.getNode());
11668 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11669 SDValue VHi = DAG.getAnyExtOrTrunc(
11670 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11671 dl, MVT::i64);
11672 if (DAG.getDataLayout().isBigEndian())
11673 std::swap (VLo, VHi);
11674 SDValue RegClass =
11675 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11676 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11677 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11678 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11679 return SDValue(
11680 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11681}
11682
Tim Northovercdf15292016-04-14 17:03:29 +000011683static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011684 SmallVectorImpl<SDValue> &Results,
11685 SelectionDAG &DAG,
11686 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011687 assert(N->getValueType(0) == MVT::i128 &&
11688 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011689
11690 if (Subtarget->hasLSE()) {
11691 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11692 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11693 SDValue Ops[] = {
11694 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11695 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11696 N->getOperand(1), // Ptr
11697 N->getOperand(0), // Chain in
11698 };
11699
Chandler Carruth66654b72018-08-14 23:30:32 +000011700 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011701
11702 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011703 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011704 case AtomicOrdering::Monotonic:
11705 Opcode = AArch64::CASPX;
11706 break;
11707 case AtomicOrdering::Acquire:
11708 Opcode = AArch64::CASPAX;
11709 break;
11710 case AtomicOrdering::Release:
11711 Opcode = AArch64::CASPLX;
11712 break;
11713 case AtomicOrdering::AcquireRelease:
11714 case AtomicOrdering::SequentiallyConsistent:
11715 Opcode = AArch64::CASPALX;
11716 break;
11717 default:
11718 llvm_unreachable("Unexpected ordering!");
11719 }
11720
11721 MachineSDNode *CmpSwap = DAG.getMachineNode(
11722 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011723 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011724
11725 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11726 if (DAG.getDataLayout().isBigEndian())
11727 std::swap(SubReg1, SubReg2);
11728 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11729 SDValue(CmpSwap, 0)));
11730 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11731 SDValue(CmpSwap, 0)));
11732 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11733 return;
11734 }
11735
Tim Northover2f32e7f2016-08-04 19:32:28 +000011736 auto Desired = splitInt128(N->getOperand(2), DAG);
11737 auto New = splitInt128(N->getOperand(3), DAG);
11738 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11739 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011740 SDNode *CmpSwap = DAG.getMachineNode(
11741 AArch64::CMP_SWAP_128, SDLoc(N),
11742 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11743
Chandler Carruth66654b72018-08-14 23:30:32 +000011744 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11745 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011746
11747 Results.push_back(SDValue(CmpSwap, 0));
11748 Results.push_back(SDValue(CmpSwap, 1));
11749 Results.push_back(SDValue(CmpSwap, 3));
11750}
11751
Tim Northover3b0846e2014-05-24 12:50:23 +000011752void AArch64TargetLowering::ReplaceNodeResults(
11753 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11754 switch (N->getOpcode()) {
11755 default:
11756 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011757 case ISD::BITCAST:
11758 ReplaceBITCASTResults(N, Results, DAG);
11759 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011760 case ISD::VECREDUCE_ADD:
11761 case ISD::VECREDUCE_SMAX:
11762 case ISD::VECREDUCE_SMIN:
11763 case ISD::VECREDUCE_UMAX:
11764 case ISD::VECREDUCE_UMIN:
11765 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11766 return;
11767
Charlie Turner434d4592015-10-16 15:38:25 +000011768 case AArch64ISD::SADDV:
11769 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11770 return;
11771 case AArch64ISD::UADDV:
11772 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11773 return;
11774 case AArch64ISD::SMINV:
11775 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11776 return;
11777 case AArch64ISD::UMINV:
11778 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11779 return;
11780 case AArch64ISD::SMAXV:
11781 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11782 return;
11783 case AArch64ISD::UMAXV:
11784 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11785 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011786 case ISD::FP_TO_UINT:
11787 case ISD::FP_TO_SINT:
11788 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11789 // Let normal code take care of it by not adding anything to Results.
11790 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011791 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011792 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011793 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011794 }
11795}
11796
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011797bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011798 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11799 return TargetLowering::useLoadStackGuardNode();
11800 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011801}
11802
Sanjay Patel1dd15592015-07-28 23:05:48 +000011803unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011804 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11805 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011806 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011807}
11808
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011809TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011810AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011811 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11812 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011813 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11814 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011815 return TypeWidenVector;
11816
11817 return TargetLoweringBase::getPreferredVectorAction(VT);
11818}
11819
Robin Morisseted3d48f2014-09-03 21:29:59 +000011820// Loads and stores less than 128-bits are already atomic; ones above that
11821// are doomed anyway, so defer to the default libcall and blame the OS when
11822// things go wrong.
11823bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11824 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11825 return Size == 128;
11826}
11827
11828// Loads and stores less than 128-bits are already atomic; ones above that
11829// are doomed anyway, so defer to the default libcall and blame the OS when
11830// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011831TargetLowering::AtomicExpansionKind
11832AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011833 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011834 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011835}
11836
11837// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011838TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011839AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011840 if (AI->isFloatingPointOperation())
11841 return AtomicExpansionKind::CmpXChg;
11842
Robin Morisseted3d48f2014-09-03 21:29:59 +000011843 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011844 if (Size > 128) return AtomicExpansionKind::None;
11845 // Nand not supported in LSE.
11846 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011847 // Leave 128 bits to LLSC.
11848 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011849}
11850
Alex Bradbury79518b02018-09-19 14:51:42 +000011851TargetLowering::AtomicExpansionKind
11852AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011853 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011854 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011855 if (Subtarget->hasLSE())
11856 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011857 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11858 // implement cmpxchg without spilling. If the address being exchanged is also
11859 // on the stack and close enough to the spill slot, this can lead to a
11860 // situation where the monitor always gets cleared and the atomic operation
11861 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011862 if (getTargetMachine().getOptLevel() == 0)
11863 return AtomicExpansionKind::None;
11864 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011865}
11866
Tim Northover3b0846e2014-05-24 12:50:23 +000011867Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11868 AtomicOrdering Ord) const {
11869 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11870 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011871 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011872
11873 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11874 // intrinsic must return {i64, i64} and we have to recombine them into a
11875 // single i128 here.
11876 if (ValTy->getPrimitiveSizeInBits() == 128) {
11877 Intrinsic::ID Int =
11878 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011879 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011880
11881 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11882 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11883
11884 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11885 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11886 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11887 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11888 return Builder.CreateOr(
11889 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11890 }
11891
11892 Type *Tys[] = { Addr->getType() };
11893 Intrinsic::ID Int =
11894 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011895 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011896
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011897 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11898
11899 const DataLayout &DL = M->getDataLayout();
11900 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11901 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11902
11903 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011904}
11905
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011906void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11907 IRBuilder<> &Builder) const {
11908 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011909 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011910}
11911
Tim Northover3b0846e2014-05-24 12:50:23 +000011912Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11913 Value *Val, Value *Addr,
11914 AtomicOrdering Ord) const {
11915 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011916 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011917
11918 // Since the intrinsics must have legal type, the i128 intrinsics take two
11919 // parameters: "i64, i64". We must marshal Val into the appropriate form
11920 // before the call.
11921 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11922 Intrinsic::ID Int =
11923 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11924 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11925 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11926
11927 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11928 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11929 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011930 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011931 }
11932
11933 Intrinsic::ID Int =
11934 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11935 Type *Tys[] = { Addr->getType() };
11936 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11937
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011938 const DataLayout &DL = M->getDataLayout();
11939 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11940 Val = Builder.CreateBitCast(Val, IntValTy);
11941
David Blaikieff6409d2015-05-18 22:13:54 +000011942 return Builder.CreateCall(Stxr,
11943 {Builder.CreateZExtOrBitCast(
11944 Val, Stxr->getFunctionType()->getParamType(0)),
11945 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011946}
Tim Northover3c55cca2014-11-27 21:02:42 +000011947
11948bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11949 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11950 return Ty->isArrayTy();
11951}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011952
11953bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11954 EVT) const {
11955 return false;
11956}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011957
Petr Hoseka7d59162017-02-24 03:10:10 +000011958static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011959 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11960 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011961 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011962 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000011963 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11964 Offset),
11965 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011966}
11967
Petr Hoseka7d59162017-02-24 03:10:10 +000011968Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11969 // Android provides a fixed TLS slot for the stack cookie. See the definition
11970 // of TLS_SLOT_STACK_GUARD in
11971 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11972 if (Subtarget->isTargetAndroid())
11973 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011974
Petr Hoseka7d59162017-02-24 03:10:10 +000011975 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011976 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011977 if (Subtarget->isTargetFuchsia())
11978 return UseTlsOffset(IRB, -0x10);
11979
11980 return TargetLowering::getIRStackGuard(IRB);
11981}
11982
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011983void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11984 // MSVC CRT provides functionalities for stack protection.
11985 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11986 // MSVC CRT has a global variable holding security cookie.
11987 M.getOrInsertGlobal("__security_cookie",
11988 Type::getInt8PtrTy(M.getContext()));
11989
11990 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000011991 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11992 "__security_check_cookie", Type::getVoidTy(M.getContext()),
11993 Type::getInt8PtrTy(M.getContext()));
11994 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
11995 F->setCallingConv(CallingConv::Win64);
11996 F->addAttribute(1, Attribute::AttrKind::InReg);
11997 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011998 return;
11999 }
12000 TargetLowering::insertSSPDeclarations(M);
12001}
12002
12003Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12004 // MSVC CRT has a global variable holding security cookie.
12005 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12006 return M.getGlobalVariable("__security_cookie");
12007 return TargetLowering::getSDagStackGuard(M);
12008}
12009
James Y Knight7976eb52019-02-01 20:43:25 +000012010Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012011 // MSVC CRT has a function to validate security cookie.
12012 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12013 return M.getFunction("__security_check_cookie");
12014 return TargetLowering::getSSPStackGuardCheck(M);
12015}
12016
Petr Hoseka7d59162017-02-24 03:10:10 +000012017Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012018 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12019 // definition of TLS_SLOT_SAFESTACK in
12020 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000012021 if (Subtarget->isTargetAndroid())
12022 return UseTlsOffset(IRB, 0x48);
12023
12024 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000012025 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000012026 if (Subtarget->isTargetFuchsia())
12027 return UseTlsOffset(IRB, -0x8);
12028
12029 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012030}
Manman Rencbe4f942015-12-16 21:04:19 +000012031
Geoff Berry5d534b62017-02-21 18:53:14 +000012032bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12033 const Instruction &AndI) const {
12034 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12035 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12036 // may be beneficial to sink in other cases, but we would have to check that
12037 // the cmp would not get folded into the br to form a cbz for these to be
12038 // beneficial.
12039 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12040 if (!Mask)
12041 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000012042 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000012043}
12044
Manman Rencbe4f942015-12-16 21:04:19 +000012045void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12046 // Update IsSplitCSR in AArch64unctionInfo.
12047 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12048 AFI->setIsSplitCSR(true);
12049}
12050
12051void AArch64TargetLowering::insertCopiesSplitCSR(
12052 MachineBasicBlock *Entry,
12053 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12054 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12055 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12056 if (!IStart)
12057 return;
12058
12059 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12060 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000012061 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000012062 for (const MCPhysReg *I = IStart; *I; ++I) {
12063 const TargetRegisterClass *RC = nullptr;
12064 if (AArch64::GPR64RegClass.contains(*I))
12065 RC = &AArch64::GPR64RegClass;
12066 else if (AArch64::FPR64RegClass.contains(*I))
12067 RC = &AArch64::FPR64RegClass;
12068 else
12069 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12070
12071 unsigned NewVR = MRI->createVirtualRegister(RC);
12072 // Create copy from CSR to a virtual register.
12073 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12074 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12075 // nounwind. If we want to generalize this later, we may need to emit
12076 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000012077 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000012078 Attribute::NoUnwind) &&
12079 "Function should be nounwind in insertCopiesSplitCSR!");
12080 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000012081 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000012082 .addReg(*I);
12083
Manman Ren4632e8e2016-01-15 20:13:28 +000012084 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000012085 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000012086 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12087 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000012088 .addReg(NewVR);
12089 }
12090}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012091
Reid Klecknerb5180542017-03-21 16:57:19 +000012092bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012093 // Integer division on AArch64 is expensive. However, when aggressively
12094 // optimizing for code size, we prefer to use a div instruction, as it is
12095 // usually smaller than the alternative sequence.
12096 // The exception to this is vector division. Since AArch64 doesn't have vector
12097 // integer division, leaving the division as-is is a loss even in terms of
12098 // size, because it will have to be scalarized, while the alternative code
12099 // sequence can be performed in vector form.
12100 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000012101 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012102 return OptSize && !VT.isVector();
12103}
Tim Northoverf19d4672017-02-08 17:57:20 +000012104
Roman Lebedevc4b83a62019-07-03 09:41:35 +000012105bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12106 // We want inc-of-add for scalars and sub-of-not for vectors.
12107 return VT.isScalarInteger();
12108}
12109
Joel Jones07150922018-01-25 21:55:39 +000012110bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12111 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12112}
12113
Tim Northoverf19d4672017-02-08 17:57:20 +000012114unsigned
12115AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000012116 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000012117 return getPointerTy(DL).getSizeInBits();
12118
12119 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12120}
Matthias Braun5c290dc2018-01-19 03:16:36 +000012121
12122void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12123 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12124 TargetLoweringBase::finalizeLowering(MF);
12125}
Eli Friedmanad1151c2018-11-09 23:33:30 +000012126
12127// Unlike X86, we let frame lowering assign offsets to all catch objects.
12128bool AArch64TargetLowering::needsFixedCatchObjects() const {
12129 return false;
12130}