blob: 515da93cded089f1c15af4ff05f80bfc6dd64e3b [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
Tim Northover3b0846e2014-05-24 12:50:23 +00001103FastISel *
1104AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1105 const TargetLibraryInfo *libInfo) const {
1106 return AArch64::createFastISel(funcInfo, libInfo);
1107}
1108
1109const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001110 switch ((AArch64ISD::NodeType)Opcode) {
1111 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001112 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1113 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001114 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001115 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1116 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1117 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1118 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1119 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1120 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1121 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1122 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1123 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1124 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001125 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001126 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1127 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1128 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1129 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1130 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1131 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1132 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001133 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1134 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1135 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001136 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001137 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1138 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1139 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1140 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1141 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1142 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1143 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1144 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1145 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1146 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1147 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1148 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1149 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1150 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1151 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1152 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1153 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1154 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1155 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1156 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1157 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1158 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1159 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1160 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1161 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1162 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1163 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1164 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1165 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1166 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1167 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1168 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1169 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1170 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1171 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1172 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1173 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1174 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1175 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1176 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1177 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1178 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1179 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1180 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1181 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1182 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1183 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1184 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001185 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1186 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1187 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1188 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1189 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1190 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001191 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1192 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1193 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1194 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1195 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1196 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1197 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001198 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001199 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1200 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001201 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001202 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1203 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1204 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1205 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1206 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1207 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1208 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1209 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1210 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1211 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1212 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1213 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1214 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1215 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1216 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1217 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1218 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1219 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1220 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1221 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1222 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1223 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1224 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1225 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1226 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1227 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1228 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1229 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1230 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001231 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1232 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001233 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001234 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1235 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1236 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001237 }
Matthias Braund04893f2015-05-07 21:33:59 +00001238 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001239}
1240
1241MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001242AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001243 MachineBasicBlock *MBB) const {
1244 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1245 // phi node:
1246
1247 // OrigBB:
1248 // [... previous instrs leading to comparison ...]
1249 // b.ne TrueBB
1250 // b EndBB
1251 // TrueBB:
1252 // ; Fallthrough
1253 // EndBB:
1254 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1255
Tim Northover3b0846e2014-05-24 12:50:23 +00001256 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001257 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001258 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001259 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001260 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001261
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001262 unsigned DestReg = MI.getOperand(0).getReg();
1263 unsigned IfTrueReg = MI.getOperand(1).getReg();
1264 unsigned IfFalseReg = MI.getOperand(2).getReg();
1265 unsigned CondCode = MI.getOperand(3).getImm();
1266 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001267
1268 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1269 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1270 MF->insert(It, TrueBB);
1271 MF->insert(It, EndBB);
1272
1273 // Transfer rest of current basic-block to EndBB
1274 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1275 MBB->end());
1276 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1277
1278 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1279 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1280 MBB->addSuccessor(TrueBB);
1281 MBB->addSuccessor(EndBB);
1282
1283 // TrueBB falls through to the end.
1284 TrueBB->addSuccessor(EndBB);
1285
1286 if (!NZCVKilled) {
1287 TrueBB->addLiveIn(AArch64::NZCV);
1288 EndBB->addLiveIn(AArch64::NZCV);
1289 }
1290
1291 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1292 .addReg(IfTrueReg)
1293 .addMBB(TrueBB)
1294 .addReg(IfFalseReg)
1295 .addMBB(MBB);
1296
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001297 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001298 return EndBB;
1299}
1300
Eli Friedmanad1151c2018-11-09 23:33:30 +00001301MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1302 MachineInstr &MI, MachineBasicBlock *BB) const {
1303 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1304 BB->getParent()->getFunction().getPersonalityFn())) &&
1305 "SEH does not use catchret!");
1306 return BB;
1307}
1308
1309MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1310 MachineInstr &MI, MachineBasicBlock *BB) const {
1311 MI.eraseFromParent();
1312 return BB;
1313}
1314
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001315MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1316 MachineInstr &MI, MachineBasicBlock *BB) const {
1317 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001318 default:
1319#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001320 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001321#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001322 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001323
1324 case AArch64::F128CSEL:
1325 return EmitF128CSEL(MI, BB);
1326
1327 case TargetOpcode::STACKMAP:
1328 case TargetOpcode::PATCHPOINT:
1329 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001330
1331 case AArch64::CATCHRET:
1332 return EmitLoweredCatchRet(MI, BB);
1333 case AArch64::CATCHPAD:
1334 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001335 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001336}
1337
1338//===----------------------------------------------------------------------===//
1339// AArch64 Lowering private implementation.
1340//===----------------------------------------------------------------------===//
1341
1342//===----------------------------------------------------------------------===//
1343// Lowering Code
1344//===----------------------------------------------------------------------===//
1345
1346/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1347/// CC
1348static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1349 switch (CC) {
1350 default:
1351 llvm_unreachable("Unknown condition code!");
1352 case ISD::SETNE:
1353 return AArch64CC::NE;
1354 case ISD::SETEQ:
1355 return AArch64CC::EQ;
1356 case ISD::SETGT:
1357 return AArch64CC::GT;
1358 case ISD::SETGE:
1359 return AArch64CC::GE;
1360 case ISD::SETLT:
1361 return AArch64CC::LT;
1362 case ISD::SETLE:
1363 return AArch64CC::LE;
1364 case ISD::SETUGT:
1365 return AArch64CC::HI;
1366 case ISD::SETUGE:
1367 return AArch64CC::HS;
1368 case ISD::SETULT:
1369 return AArch64CC::LO;
1370 case ISD::SETULE:
1371 return AArch64CC::LS;
1372 }
1373}
1374
1375/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1376static void changeFPCCToAArch64CC(ISD::CondCode CC,
1377 AArch64CC::CondCode &CondCode,
1378 AArch64CC::CondCode &CondCode2) {
1379 CondCode2 = AArch64CC::AL;
1380 switch (CC) {
1381 default:
1382 llvm_unreachable("Unknown FP condition!");
1383 case ISD::SETEQ:
1384 case ISD::SETOEQ:
1385 CondCode = AArch64CC::EQ;
1386 break;
1387 case ISD::SETGT:
1388 case ISD::SETOGT:
1389 CondCode = AArch64CC::GT;
1390 break;
1391 case ISD::SETGE:
1392 case ISD::SETOGE:
1393 CondCode = AArch64CC::GE;
1394 break;
1395 case ISD::SETOLT:
1396 CondCode = AArch64CC::MI;
1397 break;
1398 case ISD::SETOLE:
1399 CondCode = AArch64CC::LS;
1400 break;
1401 case ISD::SETONE:
1402 CondCode = AArch64CC::MI;
1403 CondCode2 = AArch64CC::GT;
1404 break;
1405 case ISD::SETO:
1406 CondCode = AArch64CC::VC;
1407 break;
1408 case ISD::SETUO:
1409 CondCode = AArch64CC::VS;
1410 break;
1411 case ISD::SETUEQ:
1412 CondCode = AArch64CC::EQ;
1413 CondCode2 = AArch64CC::VS;
1414 break;
1415 case ISD::SETUGT:
1416 CondCode = AArch64CC::HI;
1417 break;
1418 case ISD::SETUGE:
1419 CondCode = AArch64CC::PL;
1420 break;
1421 case ISD::SETLT:
1422 case ISD::SETULT:
1423 CondCode = AArch64CC::LT;
1424 break;
1425 case ISD::SETLE:
1426 case ISD::SETULE:
1427 CondCode = AArch64CC::LE;
1428 break;
1429 case ISD::SETNE:
1430 case ISD::SETUNE:
1431 CondCode = AArch64CC::NE;
1432 break;
1433 }
1434}
1435
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001436/// Convert a DAG fp condition code to an AArch64 CC.
1437/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1438/// should be AND'ed instead of OR'ed.
1439static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1440 AArch64CC::CondCode &CondCode,
1441 AArch64CC::CondCode &CondCode2) {
1442 CondCode2 = AArch64CC::AL;
1443 switch (CC) {
1444 default:
1445 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1446 assert(CondCode2 == AArch64CC::AL);
1447 break;
1448 case ISD::SETONE:
1449 // (a one b)
1450 // == ((a olt b) || (a ogt b))
1451 // == ((a ord b) && (a une b))
1452 CondCode = AArch64CC::VC;
1453 CondCode2 = AArch64CC::NE;
1454 break;
1455 case ISD::SETUEQ:
1456 // (a ueq b)
1457 // == ((a uno b) || (a oeq b))
1458 // == ((a ule b) && (a uge b))
1459 CondCode = AArch64CC::PL;
1460 CondCode2 = AArch64CC::LE;
1461 break;
1462 }
1463}
1464
Tim Northover3b0846e2014-05-24 12:50:23 +00001465/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1466/// CC usable with the vector instructions. Fewer operations are available
1467/// without a real NZCV register, so we have to use less efficient combinations
1468/// to get the same effect.
1469static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1470 AArch64CC::CondCode &CondCode,
1471 AArch64CC::CondCode &CondCode2,
1472 bool &Invert) {
1473 Invert = false;
1474 switch (CC) {
1475 default:
1476 // Mostly the scalar mappings work fine.
1477 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1478 break;
1479 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001480 Invert = true;
1481 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001482 case ISD::SETO:
1483 CondCode = AArch64CC::MI;
1484 CondCode2 = AArch64CC::GE;
1485 break;
1486 case ISD::SETUEQ:
1487 case ISD::SETULT:
1488 case ISD::SETULE:
1489 case ISD::SETUGT:
1490 case ISD::SETUGE:
1491 // All of the compare-mask comparisons are ordered, but we can switch
1492 // between the two by a double inversion. E.g. ULE == !OGT.
1493 Invert = true;
1494 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1495 break;
1496 }
1497}
1498
1499static bool isLegalArithImmed(uint64_t C) {
1500 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001501 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001502 LLVM_DEBUG(dbgs() << "Is imm " << C
1503 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001504 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001505}
1506
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001507// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1508// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1509// can be set differently by this operation. It comes down to whether
1510// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1511// everything is fine. If not then the optimization is wrong. Thus general
1512// comparisons are only valid if op2 != 0.
1513//
1514// So, finally, the only LLVM-native comparisons that don't mention C and V
1515// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1516// the absence of information about op2.
1517static bool isCMN(SDValue Op, ISD::CondCode CC) {
1518 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1519 (CC == ISD::SETEQ || CC == ISD::SETNE);
1520}
1521
Tim Northover3b0846e2014-05-24 12:50:23 +00001522static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001523 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001524 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001525 const bool FullFP16 =
1526 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001527
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001528 if (VT.isFloatingPoint()) {
1529 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001530 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001531 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1532 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001533 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001534 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001535 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001536 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001537
1538 // The CMP instruction is just an alias for SUBS, and representing it as
1539 // SUBS means that it's possible to get CSE with subtract operations.
1540 // A later phase can perform the optimization of setting the destination
1541 // register to WZR/XZR if it ends up being unused.
1542 unsigned Opcode = AArch64ISD::SUBS;
1543
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001544 if (isCMN(RHS, CC)) {
1545 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001546 Opcode = AArch64ISD::ADDS;
1547 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001548 } else if (isCMN(LHS, CC)) {
1549 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1550 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1551 Opcode = AArch64ISD::ADDS;
1552 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001553 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001554 !isUnsignedIntSetCC(CC)) {
1555 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1556 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1557 // of the signed comparisons.
1558 Opcode = AArch64ISD::ANDS;
1559 RHS = LHS.getOperand(1);
1560 LHS = LHS.getOperand(0);
1561 }
1562
Matthias Braunaf7d7702015-07-16 20:02:37 +00001563 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001564 .getValue(1);
1565}
1566
Matthias Braunaf7d7702015-07-16 20:02:37 +00001567/// \defgroup AArch64CCMP CMP;CCMP matching
1568///
1569/// These functions deal with the formation of CMP;CCMP;... sequences.
1570/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1571/// a comparison. They set the NZCV flags to a predefined value if their
1572/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001573/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001574/// expressed as:
1575/// cmp A
1576/// ccmp B, inv(CB), CA
1577/// check for CB flags
1578///
Matthias Braund0412122018-12-06 01:40:23 +00001579/// This naturally lets us implement chains of AND operations with SETCC
1580/// operands. And we can even implement some other situations by transforming
1581/// them:
1582/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1583/// negating the flags used in a CCMP/FCCMP operations.
1584/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1585/// by negating the flags we test for afterwards. i.e.
1586/// NEG (CMP CCMP CCCMP ...) can be implemented.
1587/// - Note that we can only ever negate all previously processed results.
1588/// What we can not implement by flipping the flags to test is a negation
1589/// of two sub-trees (because the negation affects all sub-trees emitted so
1590/// far, so the 2nd sub-tree we emit would also affect the first).
1591/// With those tools we can implement some OR operations:
1592/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1593/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1594/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1595/// elimination rules from earlier to implement the whole thing as a
1596/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001597///
Matthias Braund0412122018-12-06 01:40:23 +00001598/// As complete example:
1599/// or (or (setCA (cmp A)) (setCB (cmp B)))
1600/// (and (setCC (cmp C)) (setCD (cmp D)))"
1601/// can be reassociated to:
1602/// or (and (setCC (cmp C)) setCD (cmp D))
1603// (or (setCA (cmp A)) (setCB (cmp B)))
1604/// can be transformed to:
1605/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1606/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1607/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001608/// cmp C
1609/// ccmp D, inv(CD), CC
1610/// ccmp A, CA, inv(CD)
1611/// ccmp B, CB, inv(CA)
1612/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001613///
1614/// A counterexample is "or (and A B) (and C D)" which translates to
1615/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1616/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001617/// @{
1618
Geoff Berrye41c2df2015-07-20 22:03:52 +00001619/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001620static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1621 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001622 AArch64CC::CondCode Predicate,
1623 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001624 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001625 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001626 const bool FullFP16 =
1627 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1628
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001629 if (LHS.getValueType().isFloatingPoint()) {
1630 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001631 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001632 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1633 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1634 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001635 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001636 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001637 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001638 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001639 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1640 Opcode = AArch64ISD::CCMN;
1641 RHS = RHS.getOperand(1);
1642 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001643 }
1644 if (Opcode == 0)
1645 Opcode = AArch64ISD::CCMP;
1646
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001647 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1648 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1649 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001650 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1651 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1652}
1653
Matthias Braun96d12512018-11-06 03:15:22 +00001654/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1655/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001656/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1657/// changing the conditions on the SETCC tests.
1658/// (this means we can call emitConjunctionRec() with
1659/// Negate==true on this sub-tree)
1660/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1661/// cannot do the negation naturally. We are required to
1662/// emit the subtree first in this case.
1663/// \param WillNegate Is true if are called when the result of this
1664/// subexpression must be negated. This happens when the
1665/// outer expression is an OR. We can use this fact to know
1666/// that we have a double negation (or (or ...) ...) that
1667/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001668static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001669 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001670 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001671 if (!Val.hasOneUse())
1672 return false;
1673 unsigned Opcode = Val->getOpcode();
1674 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001675 if (Val->getOperand(0).getValueType() == MVT::f128)
1676 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001677 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001678 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001679 return true;
1680 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001681 // Protect against exponential runtime and stack overflow.
1682 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001683 return false;
1684 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001685 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001686 SDValue O0 = Val->getOperand(0);
1687 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001688 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001689 bool MustBeFirstL;
1690 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001691 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001692 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001693 bool MustBeFirstR;
1694 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001695 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001696
Matthias Braund0412122018-12-06 01:40:23 +00001697 if (MustBeFirstL && MustBeFirstR)
1698 return false;
1699
1700 if (IsOR) {
1701 // For an OR expression we need to be able to naturally negate at least
1702 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001703 if (!CanNegateL && !CanNegateR)
1704 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001705 // If we the result of the OR will be negated and we can naturally negate
1706 // the leafs, then this sub-tree as a whole negates naturally.
1707 CanNegate = WillNegate && CanNegateL && CanNegateR;
1708 // If we cannot naturally negate the whole sub-tree, then this must be
1709 // emitted first.
1710 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001711 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001712 assert(Opcode == ISD::AND && "Must be OR or AND");
1713 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001714 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001715 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001716 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001717 return true;
1718 }
1719 return false;
1720}
1721
1722/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1723/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1724/// Tries to transform the given i1 producing node @p Val to a series compare
1725/// and conditional compare operations. @returns an NZCV flags producing node
1726/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1727/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001728/// \p Negate is true if we want this sub-tree being negated just by changing
1729/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001730static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001731 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001732 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001733 // We're at a tree leaf, produce a conditional comparison operation.
1734 unsigned Opcode = Val->getOpcode();
1735 if (Opcode == ISD::SETCC) {
1736 SDValue LHS = Val->getOperand(0);
1737 SDValue RHS = Val->getOperand(1);
1738 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1739 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001740 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001741 CC = getSetCCInverse(CC, isInteger);
1742 SDLoc DL(Val);
1743 // Determine OutCC and handle FP special case.
1744 if (isInteger) {
1745 OutCC = changeIntCCToAArch64CC(CC);
1746 } else {
1747 assert(LHS.getValueType().isFloatingPoint());
1748 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001749 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1750 // Some floating point conditions can't be tested with a single condition
1751 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001752 if (ExtraCC != AArch64CC::AL) {
1753 SDValue ExtraCmp;
1754 if (!CCOp.getNode())
1755 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001756 else
1757 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001758 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001759 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001760 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001761 }
1762 }
1763
1764 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001765 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001766 return emitComparison(LHS, RHS, CC, DL, DAG);
1767 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001768 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001769 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001770 }
Matthias Braund0412122018-12-06 01:40:23 +00001771 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001772
Matthias Braund0412122018-12-06 01:40:23 +00001773 bool IsOR = Opcode == ISD::OR;
1774
Matthias Braunaf7d7702015-07-16 20:02:37 +00001775 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001776 bool CanNegateL;
1777 bool MustBeFirstL;
1778 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1779 assert(ValidL && "Valid conjunction/disjunction tree");
1780 (void)ValidL;
1781
Matthias Braunaf7d7702015-07-16 20:02:37 +00001782 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001783 bool CanNegateR;
1784 bool MustBeFirstR;
1785 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1786 assert(ValidR && "Valid conjunction/disjunction tree");
1787 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001788
Matthias Braund0412122018-12-06 01:40:23 +00001789 // Swap sub-tree that must come first to the right side.
1790 if (MustBeFirstL) {
1791 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1792 std::swap(LHS, RHS);
1793 std::swap(CanNegateL, CanNegateR);
1794 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001795 }
1796
Matthias Braund0412122018-12-06 01:40:23 +00001797 bool NegateR;
1798 bool NegateAfterR;
1799 bool NegateL;
1800 bool NegateAfterAll;
1801 if (Opcode == ISD::OR) {
1802 // Swap the sub-tree that we can negate naturally to the left.
1803 if (!CanNegateL) {
1804 assert(CanNegateR && "at least one side must be negatable");
1805 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1806 assert(!Negate);
1807 std::swap(LHS, RHS);
1808 NegateR = false;
1809 NegateAfterR = true;
1810 } else {
1811 // Negate the left sub-tree if possible, otherwise negate the result.
1812 NegateR = CanNegateR;
1813 NegateAfterR = !CanNegateR;
1814 }
1815 NegateL = true;
1816 NegateAfterAll = !Negate;
1817 } else {
1818 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1819 assert(!Negate && "Valid conjunction/disjunction tree");
1820
1821 NegateL = false;
1822 NegateR = false;
1823 NegateAfterR = false;
1824 NegateAfterAll = false;
1825 }
1826
1827 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001828 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001829 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1830 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001831 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001832 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1833 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001834 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1835 return CmpL;
1836}
1837
Matthias Braun96d12512018-11-06 03:15:22 +00001838/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1839/// In some cases this is even possible with OR operations in the expression.
1840/// See \ref AArch64CCMP.
1841/// \see emitConjunctionRec().
1842static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1843 AArch64CC::CondCode &OutCC) {
1844 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001845 bool DummyMustBeFirst;
1846 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001847 return SDValue();
1848
Matthias Braun96d12512018-11-06 03:15:22 +00001849 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001850}
1851
Matthias Braunaf7d7702015-07-16 20:02:37 +00001852/// @}
1853
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001854/// Returns how profitable it is to fold a comparison's operand's shift and/or
1855/// extension operations.
1856static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1857 auto isSupportedExtend = [&](SDValue V) {
1858 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1859 return true;
1860
1861 if (V.getOpcode() == ISD::AND)
1862 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1863 uint64_t Mask = MaskCst->getZExtValue();
1864 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1865 }
1866
1867 return false;
1868 };
1869
1870 if (!Op.hasOneUse())
1871 return 0;
1872
1873 if (isSupportedExtend(Op))
1874 return 1;
1875
1876 unsigned Opc = Op.getOpcode();
1877 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1878 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1879 uint64_t Shift = ShiftCst->getZExtValue();
1880 if (isSupportedExtend(Op.getOperand(0)))
1881 return (Shift <= 4) ? 2 : 1;
1882 EVT VT = Op.getValueType();
1883 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1884 return 1;
1885 }
1886
1887 return 0;
1888}
1889
Tim Northover3b0846e2014-05-24 12:50:23 +00001890static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001891 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001892 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001893 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1894 EVT VT = RHS.getValueType();
1895 uint64_t C = RHSC->getZExtValue();
1896 if (!isLegalArithImmed(C)) {
1897 // Constant does not fit, try adjusting it by one?
1898 switch (CC) {
1899 default:
1900 break;
1901 case ISD::SETLT:
1902 case ISD::SETGE:
1903 if ((VT == MVT::i32 && C != 0x80000000 &&
1904 isLegalArithImmed((uint32_t)(C - 1))) ||
1905 (VT == MVT::i64 && C != 0x80000000ULL &&
1906 isLegalArithImmed(C - 1ULL))) {
1907 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1908 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001909 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001910 }
1911 break;
1912 case ISD::SETULT:
1913 case ISD::SETUGE:
1914 if ((VT == MVT::i32 && C != 0 &&
1915 isLegalArithImmed((uint32_t)(C - 1))) ||
1916 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1917 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1918 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001919 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001920 }
1921 break;
1922 case ISD::SETLE:
1923 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001924 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001925 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001926 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001927 isLegalArithImmed(C + 1ULL))) {
1928 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1929 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001930 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001931 }
1932 break;
1933 case ISD::SETULE:
1934 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001935 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001936 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001937 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001938 isLegalArithImmed(C + 1ULL))) {
1939 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1940 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001941 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001942 }
1943 break;
1944 }
1945 }
1946 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001947
1948 // Comparisons are canonicalized so that the RHS operand is simpler than the
1949 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1950 // can fold some shift+extend operations on the RHS operand, so swap the
1951 // operands if that can be done.
1952 //
1953 // For example:
1954 // lsl w13, w11, #1
1955 // cmp w13, w12
1956 // can be turned into:
1957 // cmp w12, w11, lsl #1
1958 if (!isa<ConstantSDNode>(RHS) ||
1959 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1960 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1961
1962 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1963 std::swap(LHS, RHS);
1964 CC = ISD::getSetCCSwappedOperands(CC);
1965 }
1966 }
1967
Matthias Braunaf7d7702015-07-16 20:02:37 +00001968 SDValue Cmp;
1969 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001970 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001971 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1972
1973 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1974 // For the i8 operand, the largest immediate is 255, so this can be easily
1975 // encoded in the compare instruction. For the i16 operand, however, the
1976 // largest immediate cannot be encoded in the compare.
1977 // Therefore, use a sign extending load and cmn to avoid materializing the
1978 // -1 constant. For example,
1979 // movz w1, #65535
1980 // ldrh w0, [x0, #0]
1981 // cmp w0, w1
1982 // >
1983 // ldrsh w0, [x0, #0]
1984 // cmn w0, #1
1985 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1986 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001987 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001988 // transformation is profitable.
1989 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1990 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1991 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1992 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1993 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1994 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1995 SDValue SExt =
1996 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1997 DAG.getValueType(MVT::i16));
1998 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1999 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002000 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002001 AArch64CC = changeIntCCToAArch64CC(CC);
2002 }
2003 }
2004
2005 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00002006 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002007 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2008 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00002009 }
2010 }
2011 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00002012
2013 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002014 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002015 AArch64CC = changeIntCCToAArch64CC(CC);
2016 }
2017 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00002018 return Cmp;
2019}
2020
2021static std::pair<SDValue, SDValue>
2022getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2023 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2024 "Unsupported value type");
2025 SDValue Value, Overflow;
2026 SDLoc DL(Op);
2027 SDValue LHS = Op.getOperand(0);
2028 SDValue RHS = Op.getOperand(1);
2029 unsigned Opc = 0;
2030 switch (Op.getOpcode()) {
2031 default:
2032 llvm_unreachable("Unknown overflow instruction!");
2033 case ISD::SADDO:
2034 Opc = AArch64ISD::ADDS;
2035 CC = AArch64CC::VS;
2036 break;
2037 case ISD::UADDO:
2038 Opc = AArch64ISD::ADDS;
2039 CC = AArch64CC::HS;
2040 break;
2041 case ISD::SSUBO:
2042 Opc = AArch64ISD::SUBS;
2043 CC = AArch64CC::VS;
2044 break;
2045 case ISD::USUBO:
2046 Opc = AArch64ISD::SUBS;
2047 CC = AArch64CC::LO;
2048 break;
2049 // Multiply needs a little bit extra work.
2050 case ISD::SMULO:
2051 case ISD::UMULO: {
2052 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002053 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002054 if (Op.getValueType() == MVT::i32) {
2055 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2056 // For a 32 bit multiply with overflow check we want the instruction
2057 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2058 // need to generate the following pattern:
2059 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2060 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2061 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2062 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2063 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002064 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002065 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2066 // operation. We need to clear out the upper 32 bits, because we used a
2067 // widening multiply that wrote all 64 bits. In the end this should be a
2068 // noop.
2069 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2070 if (IsSigned) {
2071 // The signed overflow check requires more than just a simple check for
2072 // any bit set in the upper 32 bits of the result. These bits could be
2073 // just the sign bits of a negative number. To perform the overflow
2074 // check we have to arithmetic shift right the 32nd bit of the result by
2075 // 31 bits. Then we compare the result to the upper 32 bits.
2076 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002077 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002078 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2079 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002080 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002081 // It is important that LowerBits is last, otherwise the arithmetic
2082 // shift will not be folded into the compare (SUBS).
2083 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2084 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2085 .getValue(1);
2086 } else {
2087 // The overflow check for unsigned multiply is easy. We only need to
2088 // check if any of the upper 32 bits are set. This can be done with a
2089 // CMP (shifted register). For that we need to generate the following
2090 // pattern:
2091 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2092 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002093 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002094 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2095 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002096 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2097 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002098 UpperBits).getValue(1);
2099 }
2100 break;
2101 }
2102 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2103 // For the 64 bit multiply
2104 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2105 if (IsSigned) {
2106 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2107 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002108 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002109 // It is important that LowerBits is last, otherwise the arithmetic
2110 // shift will not be folded into the compare (SUBS).
2111 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2112 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2113 .getValue(1);
2114 } else {
2115 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2116 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2117 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002118 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2119 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002120 UpperBits).getValue(1);
2121 }
2122 break;
2123 }
2124 } // switch (...)
2125
2126 if (Opc) {
2127 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2128
2129 // Emit the AArch64 operation with overflow check.
2130 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2131 Overflow = Value.getValue(1);
2132 }
2133 return std::make_pair(Value, Overflow);
2134}
2135
2136SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2137 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002138 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002139 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002140}
2141
Amara Emerson24ca39c2017-10-09 15:15:09 +00002142// Returns true if the given Op is the overflow flag result of an overflow
2143// intrinsic operation.
2144static bool isOverflowIntrOpRes(SDValue Op) {
2145 unsigned Opc = Op.getOpcode();
2146 return (Op.getResNo() == 1 &&
2147 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2148 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2149}
2150
Tim Northover3b0846e2014-05-24 12:50:23 +00002151static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2152 SDValue Sel = Op.getOperand(0);
2153 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002154 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002155
Amara Emerson24ca39c2017-10-09 15:15:09 +00002156 // If the operand is an overflow checking operation, invert the condition
2157 // code and kill the Not operation. I.e., transform:
2158 // (xor (overflow_op_bool, 1))
2159 // -->
2160 // (csel 1, 0, invert(cc), overflow_op_bool)
2161 // ... which later gets transformed to just a cset instruction with an
2162 // inverted condition code, rather than a cset + eor sequence.
2163 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2164 // Only lower legal XALUO ops.
2165 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2166 return SDValue();
2167
2168 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2169 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2170 AArch64CC::CondCode CC;
2171 SDValue Value, Overflow;
2172 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2173 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2174 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2175 CCVal, Overflow);
2176 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002177 // If neither operand is a SELECT_CC, give up.
2178 if (Sel.getOpcode() != ISD::SELECT_CC)
2179 std::swap(Sel, Other);
2180 if (Sel.getOpcode() != ISD::SELECT_CC)
2181 return Op;
2182
2183 // The folding we want to perform is:
2184 // (xor x, (select_cc a, b, cc, 0, -1) )
2185 // -->
2186 // (csel x, (xor x, -1), cc ...)
2187 //
2188 // The latter will get matched to a CSINV instruction.
2189
2190 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2191 SDValue LHS = Sel.getOperand(0);
2192 SDValue RHS = Sel.getOperand(1);
2193 SDValue TVal = Sel.getOperand(2);
2194 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002195
2196 // FIXME: This could be generalized to non-integer comparisons.
2197 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2198 return Op;
2199
2200 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2201 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2202
Eric Christopher572e03a2015-06-19 01:53:21 +00002203 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002204 if (!CFVal || !CTVal)
2205 return Op;
2206
2207 // We can commute the SELECT_CC by inverting the condition. This
2208 // might be needed to make this fit into a CSINV pattern.
2209 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2210 std::swap(TVal, FVal);
2211 std::swap(CTVal, CFVal);
2212 CC = ISD::getSetCCInverse(CC, true);
2213 }
2214
2215 // If the constants line up, perform the transform!
2216 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2217 SDValue CCVal;
2218 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2219
2220 FVal = Other;
2221 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002222 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002223
2224 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2225 CCVal, Cmp);
2226 }
2227
2228 return Op;
2229}
2230
2231static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2232 EVT VT = Op.getValueType();
2233
2234 // Let legalize expand this if it isn't a legal type yet.
2235 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2236 return SDValue();
2237
2238 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2239
2240 unsigned Opc;
2241 bool ExtraOp = false;
2242 switch (Op.getOpcode()) {
2243 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002244 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002245 case ISD::ADDC:
2246 Opc = AArch64ISD::ADDS;
2247 break;
2248 case ISD::SUBC:
2249 Opc = AArch64ISD::SUBS;
2250 break;
2251 case ISD::ADDE:
2252 Opc = AArch64ISD::ADCS;
2253 ExtraOp = true;
2254 break;
2255 case ISD::SUBE:
2256 Opc = AArch64ISD::SBCS;
2257 ExtraOp = true;
2258 break;
2259 }
2260
2261 if (!ExtraOp)
2262 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2263 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2264 Op.getOperand(2));
2265}
2266
2267static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2268 // Let legalize expand this if it isn't a legal type yet.
2269 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2270 return SDValue();
2271
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002272 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002273 AArch64CC::CondCode CC;
2274 // The actual operation that sets the overflow or carry flag.
2275 SDValue Value, Overflow;
2276 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2277
2278 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002279 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2280 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002281
2282 // We use an inverted condition, because the conditional select is inverted
2283 // too. This will allow it to be selected to a single instruction:
2284 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002285 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2286 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002287 CCVal, Overflow);
2288
2289 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002290 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002291}
2292
2293// Prefetch operands are:
2294// 1: Address to prefetch
2295// 2: bool isWrite
2296// 3: int locality (0 = no locality ... 3 = extreme locality)
2297// 4: bool isDataCache
2298static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2299 SDLoc DL(Op);
2300 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2301 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002302 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002303
2304 bool IsStream = !Locality;
2305 // When the locality number is set
2306 if (Locality) {
2307 // The front-end should have filtered out the out-of-range values
2308 assert(Locality <= 3 && "Prefetch locality out-of-range");
2309 // The locality degree is the opposite of the cache speed.
2310 // Put the number the other way around.
2311 // The encoding starts at 0 for level 1
2312 Locality = 3 - Locality;
2313 }
2314
2315 // built the mask value encoding the expected behavior.
2316 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002317 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002318 (Locality << 1) | // Cache level bits
2319 (unsigned)IsStream; // Stream bit
2320 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002321 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002322}
2323
2324SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2325 SelectionDAG &DAG) const {
2326 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2327
2328 RTLIB::Libcall LC;
2329 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2330
2331 return LowerF128Call(Op, DAG, LC);
2332}
2333
2334SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2335 SelectionDAG &DAG) const {
2336 if (Op.getOperand(0).getValueType() != MVT::f128) {
2337 // It's legal except when f128 is involved
2338 return Op;
2339 }
2340
2341 RTLIB::Libcall LC;
2342 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2343
2344 // FP_ROUND node has a second operand indicating whether it is known to be
2345 // precise. That doesn't take part in the LibCall so we can't directly use
2346 // LowerF128Call.
2347 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002348 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2349 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002350}
2351
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002352SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2353 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002354 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2355 // Any additional optimization in this function should be recorded
2356 // in the cost tables.
2357 EVT InVT = Op.getOperand(0).getValueType();
2358 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002359 unsigned NumElts = InVT.getVectorNumElements();
2360
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002361 // f16 conversions are promoted to f32 when full fp16 is not supported.
2362 if (InVT.getVectorElementType() == MVT::f16 &&
2363 !Subtarget->hasFullFP16()) {
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002364 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2365 SDLoc dl(Op);
2366 return DAG.getNode(
2367 Op.getOpcode(), dl, Op.getValueType(),
2368 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2369 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002370
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002371 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002372 SDLoc dl(Op);
2373 SDValue Cv =
2374 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2375 Op.getOperand(0));
2376 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002377 }
2378
2379 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002380 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002381 MVT ExtVT =
2382 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2383 VT.getVectorNumElements());
2384 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002385 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2386 }
2387
2388 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002389 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002390}
2391
2392SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2393 SelectionDAG &DAG) const {
2394 if (Op.getOperand(0).getValueType().isVector())
2395 return LowerVectorFP_TO_INT(Op, DAG);
2396
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002397 // f16 conversions are promoted to f32 when full fp16 is not supported.
2398 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2399 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002400 SDLoc dl(Op);
2401 return DAG.getNode(
2402 Op.getOpcode(), dl, Op.getValueType(),
2403 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2404 }
2405
Tim Northover3b0846e2014-05-24 12:50:23 +00002406 if (Op.getOperand(0).getValueType() != MVT::f128) {
2407 // It's legal except when f128 is involved
2408 return Op;
2409 }
2410
2411 RTLIB::Libcall LC;
2412 if (Op.getOpcode() == ISD::FP_TO_SINT)
2413 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2414 else
2415 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2416
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002417 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002418 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002419}
2420
2421static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2422 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2423 // Any additional optimization in this function should be recorded
2424 // in the cost tables.
2425 EVT VT = Op.getValueType();
2426 SDLoc dl(Op);
2427 SDValue In = Op.getOperand(0);
2428 EVT InVT = In.getValueType();
2429
Tim Northoveref0d7602014-06-15 09:27:06 +00002430 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2431 MVT CastVT =
2432 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2433 InVT.getVectorNumElements());
2434 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002435 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002436 }
2437
Tim Northoveref0d7602014-06-15 09:27:06 +00002438 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2439 unsigned CastOpc =
2440 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2441 EVT CastVT = VT.changeVectorElementTypeToInteger();
2442 In = DAG.getNode(CastOpc, dl, CastVT, In);
2443 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002444 }
2445
Tim Northoveref0d7602014-06-15 09:27:06 +00002446 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002447}
2448
2449SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2450 SelectionDAG &DAG) const {
2451 if (Op.getValueType().isVector())
2452 return LowerVectorINT_TO_FP(Op, DAG);
2453
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002454 // f16 conversions are promoted to f32 when full fp16 is not supported.
2455 if (Op.getValueType() == MVT::f16 &&
2456 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002457 SDLoc dl(Op);
2458 return DAG.getNode(
2459 ISD::FP_ROUND, dl, MVT::f16,
2460 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002461 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002462 }
2463
Tim Northover3b0846e2014-05-24 12:50:23 +00002464 // i128 conversions are libcalls.
2465 if (Op.getOperand(0).getValueType() == MVT::i128)
2466 return SDValue();
2467
2468 // Other conversions are legal, unless it's to the completely software-based
2469 // fp128.
2470 if (Op.getValueType() != MVT::f128)
2471 return Op;
2472
2473 RTLIB::Libcall LC;
2474 if (Op.getOpcode() == ISD::SINT_TO_FP)
2475 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2476 else
2477 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2478
2479 return LowerF128Call(Op, DAG, LC);
2480}
2481
2482SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2483 SelectionDAG &DAG) const {
2484 // For iOS, we want to call an alternative entry point: __sincos_stret,
2485 // which returns the values in two S / D registers.
2486 SDLoc dl(Op);
2487 SDValue Arg = Op.getOperand(0);
2488 EVT ArgVT = Arg.getValueType();
2489 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2490
2491 ArgListTy Args;
2492 ArgListEntry Entry;
2493
2494 Entry.Node = Arg;
2495 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002496 Entry.IsSExt = false;
2497 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002498 Args.push_back(Entry);
2499
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002500 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2501 : RTLIB::SINCOS_STRET_F32;
2502 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002503 SDValue Callee =
2504 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002505
Serge Gueltone38003f2017-05-09 19:31:13 +00002506 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002507 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002508 CLI.setDebugLoc(dl)
2509 .setChain(DAG.getEntryNode())
2510 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002511
2512 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2513 return CallResult.first;
2514}
2515
Tim Northoverf8bfe212014-07-18 13:07:05 +00002516static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2517 if (Op.getValueType() != MVT::f16)
2518 return SDValue();
2519
2520 assert(Op.getOperand(0).getValueType() == MVT::i16);
2521 SDLoc DL(Op);
2522
2523 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2524 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2525 return SDValue(
2526 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002527 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002528 0);
2529}
2530
Chad Rosierd9d0f862014-10-08 02:31:24 +00002531static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2532 if (OrigVT.getSizeInBits() >= 64)
2533 return OrigVT;
2534
2535 assert(OrigVT.isSimple() && "Expecting a simple value type");
2536
2537 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2538 switch (OrigSimpleTy) {
2539 default: llvm_unreachable("Unexpected Vector Type");
2540 case MVT::v2i8:
2541 case MVT::v2i16:
2542 return MVT::v2i32;
2543 case MVT::v4i8:
2544 return MVT::v4i16;
2545 }
2546}
2547
2548static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2549 const EVT &OrigTy,
2550 const EVT &ExtTy,
2551 unsigned ExtOpcode) {
2552 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2553 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2554 // 64-bits we need to insert a new extension so that it will be 64-bits.
2555 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2556 if (OrigTy.getSizeInBits() >= 64)
2557 return N;
2558
2559 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2560 EVT NewVT = getExtensionTo64Bits(OrigTy);
2561
2562 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2563}
2564
2565static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2566 bool isSigned) {
2567 EVT VT = N->getValueType(0);
2568
2569 if (N->getOpcode() != ISD::BUILD_VECTOR)
2570 return false;
2571
Pete Cooper3af9a252015-06-26 18:17:36 +00002572 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002574 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002575 unsigned HalfSize = EltSize / 2;
2576 if (isSigned) {
2577 if (!isIntN(HalfSize, C->getSExtValue()))
2578 return false;
2579 } else {
2580 if (!isUIntN(HalfSize, C->getZExtValue()))
2581 return false;
2582 }
2583 continue;
2584 }
2585 return false;
2586 }
2587
2588 return true;
2589}
2590
2591static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2592 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2593 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2594 N->getOperand(0)->getValueType(0),
2595 N->getValueType(0),
2596 N->getOpcode());
2597
2598 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2599 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002600 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002601 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002602 unsigned NumElts = VT.getVectorNumElements();
2603 MVT TruncVT = MVT::getIntegerVT(EltSize);
2604 SmallVector<SDValue, 8> Ops;
2605 for (unsigned i = 0; i != NumElts; ++i) {
2606 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2607 const APInt &CInt = C->getAPIntValue();
2608 // Element types smaller than 32 bits are not legal, so use i32 elements.
2609 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002610 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002611 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002612 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002613}
2614
2615static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002616 return N->getOpcode() == ISD::SIGN_EXTEND ||
2617 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002618}
2619
2620static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002621 return N->getOpcode() == ISD::ZERO_EXTEND ||
2622 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002623}
2624
2625static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2626 unsigned Opcode = N->getOpcode();
2627 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2628 SDNode *N0 = N->getOperand(0).getNode();
2629 SDNode *N1 = N->getOperand(1).getNode();
2630 return N0->hasOneUse() && N1->hasOneUse() &&
2631 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2632 }
2633 return false;
2634}
2635
2636static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2637 unsigned Opcode = N->getOpcode();
2638 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2639 SDNode *N0 = N->getOperand(0).getNode();
2640 SDNode *N1 = N->getOperand(1).getNode();
2641 return N0->hasOneUse() && N1->hasOneUse() &&
2642 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2643 }
2644 return false;
2645}
2646
Tim Northover70666e72018-06-20 12:09:01 +00002647SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2648 SelectionDAG &DAG) const {
2649 // The rounding mode is in bits 23:22 of the FPSCR.
2650 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2651 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2652 // so that the shift + and get folded into a bitfield extract.
2653 SDLoc dl(Op);
2654
2655 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2656 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2657 MVT::i64));
2658 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2659 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2660 DAG.getConstant(1U << 22, dl, MVT::i32));
2661 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2662 DAG.getConstant(22, dl, MVT::i32));
2663 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2664 DAG.getConstant(3, dl, MVT::i32));
2665}
2666
Chad Rosierd9d0f862014-10-08 02:31:24 +00002667static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2668 // Multiplications are only custom-lowered for 128-bit vectors so that
2669 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2670 EVT VT = Op.getValueType();
2671 assert(VT.is128BitVector() && VT.isInteger() &&
2672 "unexpected type for custom-lowering ISD::MUL");
2673 SDNode *N0 = Op.getOperand(0).getNode();
2674 SDNode *N1 = Op.getOperand(1).getNode();
2675 unsigned NewOpc = 0;
2676 bool isMLA = false;
2677 bool isN0SExt = isSignExtended(N0, DAG);
2678 bool isN1SExt = isSignExtended(N1, DAG);
2679 if (isN0SExt && isN1SExt)
2680 NewOpc = AArch64ISD::SMULL;
2681 else {
2682 bool isN0ZExt = isZeroExtended(N0, DAG);
2683 bool isN1ZExt = isZeroExtended(N1, DAG);
2684 if (isN0ZExt && isN1ZExt)
2685 NewOpc = AArch64ISD::UMULL;
2686 else if (isN1SExt || isN1ZExt) {
2687 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2688 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2689 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2690 NewOpc = AArch64ISD::SMULL;
2691 isMLA = true;
2692 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2693 NewOpc = AArch64ISD::UMULL;
2694 isMLA = true;
2695 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2696 std::swap(N0, N1);
2697 NewOpc = AArch64ISD::UMULL;
2698 isMLA = true;
2699 }
2700 }
2701
2702 if (!NewOpc) {
2703 if (VT == MVT::v2i64)
2704 // Fall through to expand this. It is not legal.
2705 return SDValue();
2706 else
2707 // Other vector multiplications are legal.
2708 return Op;
2709 }
2710 }
2711
2712 // Legalize to a S/UMULL instruction
2713 SDLoc DL(Op);
2714 SDValue Op0;
2715 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2716 if (!isMLA) {
2717 Op0 = skipExtensionForVectorMULL(N0, DAG);
2718 assert(Op0.getValueType().is64BitVector() &&
2719 Op1.getValueType().is64BitVector() &&
2720 "unexpected types for extended operands to VMULL");
2721 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2722 }
2723 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2724 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2725 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2726 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2727 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2728 EVT Op1VT = Op1.getValueType();
2729 return DAG.getNode(N0->getOpcode(), DL, VT,
2730 DAG.getNode(NewOpc, DL, VT,
2731 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2732 DAG.getNode(NewOpc, DL, VT,
2733 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2734}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002735
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002736SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2737 SelectionDAG &DAG) const {
2738 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2739 SDLoc dl(Op);
2740 switch (IntNo) {
2741 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002742 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002743 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2744 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2745 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002746 case Intrinsic::aarch64_neon_abs: {
2747 EVT Ty = Op.getValueType();
2748 if (Ty == MVT::i64) {
2749 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2750 Op.getOperand(1));
2751 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2752 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2753 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2754 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2755 } else {
2756 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2757 }
2758 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002759 case Intrinsic::aarch64_neon_smax:
2760 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2761 Op.getOperand(1), Op.getOperand(2));
2762 case Intrinsic::aarch64_neon_umax:
2763 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2764 Op.getOperand(1), Op.getOperand(2));
2765 case Intrinsic::aarch64_neon_smin:
2766 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2767 Op.getOperand(1), Op.getOperand(2));
2768 case Intrinsic::aarch64_neon_umin:
2769 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2770 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002771
2772 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002773 const auto &MF = DAG.getMachineFunction();
2774 const auto *RegInfo = Subtarget->getRegisterInfo();
2775 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002776 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2777 Op.getSimpleValueType());
2778 }
2779
2780 case Intrinsic::eh_recoverfp: {
2781 // FIXME: This needs to be implemented to correctly handle highly aligned
2782 // stack objects. For now we simply return the incoming FP. Refer D53541
2783 // for more details.
2784 SDValue FnOp = Op.getOperand(1);
2785 SDValue IncomingFPOp = Op.getOperand(2);
2786 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2787 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2788 if (!Fn)
2789 report_fatal_error(
2790 "llvm.eh.recoverfp must take a function as the first argument");
2791 return IncomingFPOp;
2792 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002793 }
2794}
2795
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002796// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2797static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2798 EVT VT, EVT MemVT,
2799 SelectionDAG &DAG) {
2800 assert(VT.isVector() && "VT should be a vector type");
2801 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2802
2803 SDValue Value = ST->getValue();
2804
2805 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2806 // the word lane which represent the v4i8 subvector. It optimizes the store
2807 // to:
2808 //
2809 // xtn v0.8b, v0.8h
2810 // str s0, [x0]
2811
2812 SDValue Undef = DAG.getUNDEF(MVT::i16);
2813 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2814 {Undef, Undef, Undef, Undef});
2815
2816 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2817 Value, UndefVec);
2818 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2819
2820 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2821 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2822 Trunc, DAG.getConstant(0, DL, MVT::i64));
2823
2824 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2825 ST->getBasePtr(), ST->getMemOperand());
2826}
2827
2828// Custom lowering for any store, vector or scalar and/or default or with
2829// a truncate operations. Currently only custom lower truncate operation
2830// from vector v4i16 to v4i8.
2831SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2832 SelectionDAG &DAG) const {
2833 SDLoc Dl(Op);
2834 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2835 assert (StoreNode && "Can only custom lower store nodes");
2836
2837 SDValue Value = StoreNode->getValue();
2838
2839 EVT VT = Value.getValueType();
2840 EVT MemVT = StoreNode->getMemoryVT();
2841
2842 assert (VT.isVector() && "Can only custom lower vector store types");
2843
2844 unsigned AS = StoreNode->getAddressSpace();
2845 unsigned Align = StoreNode->getAlignment();
2846 if (Align < MemVT.getStoreSize() &&
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00002847 !allowsMisalignedMemoryAccesses(
2848 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002849 return scalarizeVectorStore(StoreNode, DAG);
2850 }
2851
2852 if (StoreNode->isTruncatingStore()) {
2853 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2854 }
2855
2856 return SDValue();
2857}
2858
Tim Northover3b0846e2014-05-24 12:50:23 +00002859SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2860 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002861 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2862 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002863
Tim Northover3b0846e2014-05-24 12:50:23 +00002864 switch (Op.getOpcode()) {
2865 default:
2866 llvm_unreachable("unimplemented operand");
2867 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002868 case ISD::BITCAST:
2869 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002870 case ISD::GlobalAddress:
2871 return LowerGlobalAddress(Op, DAG);
2872 case ISD::GlobalTLSAddress:
2873 return LowerGlobalTLSAddress(Op, DAG);
2874 case ISD::SETCC:
2875 return LowerSETCC(Op, DAG);
2876 case ISD::BR_CC:
2877 return LowerBR_CC(Op, DAG);
2878 case ISD::SELECT:
2879 return LowerSELECT(Op, DAG);
2880 case ISD::SELECT_CC:
2881 return LowerSELECT_CC(Op, DAG);
2882 case ISD::JumpTable:
2883 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002884 case ISD::BR_JT:
2885 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002886 case ISD::ConstantPool:
2887 return LowerConstantPool(Op, DAG);
2888 case ISD::BlockAddress:
2889 return LowerBlockAddress(Op, DAG);
2890 case ISD::VASTART:
2891 return LowerVASTART(Op, DAG);
2892 case ISD::VACOPY:
2893 return LowerVACOPY(Op, DAG);
2894 case ISD::VAARG:
2895 return LowerVAARG(Op, DAG);
2896 case ISD::ADDC:
2897 case ISD::ADDE:
2898 case ISD::SUBC:
2899 case ISD::SUBE:
2900 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2901 case ISD::SADDO:
2902 case ISD::UADDO:
2903 case ISD::SSUBO:
2904 case ISD::USUBO:
2905 case ISD::SMULO:
2906 case ISD::UMULO:
2907 return LowerXALUO(Op, DAG);
2908 case ISD::FADD:
2909 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2910 case ISD::FSUB:
2911 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2912 case ISD::FMUL:
2913 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2914 case ISD::FDIV:
2915 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2916 case ISD::FP_ROUND:
2917 return LowerFP_ROUND(Op, DAG);
2918 case ISD::FP_EXTEND:
2919 return LowerFP_EXTEND(Op, DAG);
2920 case ISD::FRAMEADDR:
2921 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002922 case ISD::SPONENTRY:
2923 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002924 case ISD::RETURNADDR:
2925 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002926 case ISD::ADDROFRETURNADDR:
2927 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002928 case ISD::INSERT_VECTOR_ELT:
2929 return LowerINSERT_VECTOR_ELT(Op, DAG);
2930 case ISD::EXTRACT_VECTOR_ELT:
2931 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2932 case ISD::BUILD_VECTOR:
2933 return LowerBUILD_VECTOR(Op, DAG);
2934 case ISD::VECTOR_SHUFFLE:
2935 return LowerVECTOR_SHUFFLE(Op, DAG);
2936 case ISD::EXTRACT_SUBVECTOR:
2937 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2938 case ISD::SRA:
2939 case ISD::SRL:
2940 case ISD::SHL:
2941 return LowerVectorSRA_SRL_SHL(Op, DAG);
2942 case ISD::SHL_PARTS:
2943 return LowerShiftLeftParts(Op, DAG);
2944 case ISD::SRL_PARTS:
2945 case ISD::SRA_PARTS:
2946 return LowerShiftRightParts(Op, DAG);
2947 case ISD::CTPOP:
2948 return LowerCTPOP(Op, DAG);
2949 case ISD::FCOPYSIGN:
2950 return LowerFCOPYSIGN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002951 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002952 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002953 case ISD::XOR:
2954 return LowerXOR(Op, DAG);
2955 case ISD::PREFETCH:
2956 return LowerPREFETCH(Op, DAG);
2957 case ISD::SINT_TO_FP:
2958 case ISD::UINT_TO_FP:
2959 return LowerINT_TO_FP(Op, DAG);
2960 case ISD::FP_TO_SINT:
2961 case ISD::FP_TO_UINT:
2962 return LowerFP_TO_INT(Op, DAG);
2963 case ISD::FSINCOS:
2964 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002965 case ISD::FLT_ROUNDS_:
2966 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002967 case ISD::MUL:
2968 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002969 case ISD::INTRINSIC_WO_CHAIN:
2970 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002971 case ISD::STORE:
2972 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002973 case ISD::VECREDUCE_ADD:
2974 case ISD::VECREDUCE_SMAX:
2975 case ISD::VECREDUCE_SMIN:
2976 case ISD::VECREDUCE_UMAX:
2977 case ISD::VECREDUCE_UMIN:
2978 case ISD::VECREDUCE_FMAX:
2979 case ISD::VECREDUCE_FMIN:
2980 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002981 case ISD::ATOMIC_LOAD_SUB:
2982 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002983 case ISD::ATOMIC_LOAD_AND:
2984 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002985 case ISD::DYNAMIC_STACKALLOC:
2986 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002987 }
2988}
2989
Tim Northover3b0846e2014-05-24 12:50:23 +00002990//===----------------------------------------------------------------------===//
2991// Calling Convention Implementation
2992//===----------------------------------------------------------------------===//
2993
Robin Morisset039781e2014-08-29 21:53:01 +00002994/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002995CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2996 bool IsVarArg) const {
2997 switch (CC) {
2998 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002999 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00003000 case CallingConv::WebKit_JS:
3001 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00003002 case CallingConv::GHC:
3003 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00003004 case CallingConv::C:
3005 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00003006 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00003007 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00003008 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00003009 if (Subtarget->isTargetWindows() && IsVarArg)
3010 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00003011 if (!Subtarget->isTargetDarwin())
3012 return CC_AArch64_AAPCS;
3013 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00003014 case CallingConv::Win64:
3015 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00003016 case CallingConv::AArch64_VectorCall:
3017 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00003018 }
3019}
3020
Tim Northover406024a2016-08-10 21:44:01 +00003021CCAssignFn *
3022AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3023 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3024 : RetCC_AArch64_AAPCS;
3025}
3026
Tim Northover3b0846e2014-05-24 12:50:23 +00003027SDValue AArch64TargetLowering::LowerFormalArguments(
3028 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003029 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3030 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003031 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003032 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003033 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003034
3035 // Assign locations to all of the incoming arguments.
3036 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003037 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3038 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003039
3040 // At this point, Ins[].VT may already be promoted to i32. To correctly
3041 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3042 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3043 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3044 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3045 // LocVT.
3046 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003047 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003048 unsigned CurArgIdx = 0;
3049 for (unsigned i = 0; i != NumArgs; ++i) {
3050 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003051 if (Ins[i].isOrigArg()) {
3052 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3053 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003054
Andrew Trick05938a52015-02-16 18:10:47 +00003055 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003056 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3057 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003058 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3059 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3060 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3061 ValVT = MVT::i8;
3062 else if (ActualMVT == MVT::i16)
3063 ValVT = MVT::i16;
3064 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003065 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3066 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003067 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003068 assert(!Res && "Call operand has unhandled type");
3069 (void)Res;
3070 }
3071 assert(ArgLocs.size() == Ins.size());
3072 SmallVector<SDValue, 16> ArgValues;
3073 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3074 CCValAssign &VA = ArgLocs[i];
3075
3076 if (Ins[i].Flags.isByVal()) {
3077 // Byval is used for HFAs in the PCS, but the system should work in a
3078 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003079 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003080 int Size = Ins[i].Flags.getByValSize();
3081 unsigned NumRegs = (Size + 7) / 8;
3082
3083 // FIXME: This works on big-endian for composite byvals, which are the common
3084 // case. It should also work for fundamental types too.
3085 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003086 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003087 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003088 InVals.push_back(FrameIdxN);
3089
3090 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003091 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003092
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003093 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003094 // Arguments stored in registers.
3095 EVT RegVT = VA.getLocVT();
3096
3097 SDValue ArgValue;
3098 const TargetRegisterClass *RC;
3099
3100 if (RegVT == MVT::i32)
3101 RC = &AArch64::GPR32RegClass;
3102 else if (RegVT == MVT::i64)
3103 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003104 else if (RegVT == MVT::f16)
3105 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003106 else if (RegVT == MVT::f32)
3107 RC = &AArch64::FPR32RegClass;
3108 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3109 RC = &AArch64::FPR64RegClass;
3110 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3111 RC = &AArch64::FPR128RegClass;
3112 else
3113 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3114
3115 // Transform the arguments in physical registers into virtual ones.
3116 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3117 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3118
3119 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3120 // to 64 bits. Insert an assert[sz]ext to capture this, then
3121 // truncate to the right size.
3122 switch (VA.getLocInfo()) {
3123 default:
3124 llvm_unreachable("Unknown loc info!");
3125 case CCValAssign::Full:
3126 break;
3127 case CCValAssign::BCvt:
3128 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3129 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003130 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003131 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003132 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003133 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3134 // nodes after our lowering.
3135 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003136 break;
3137 }
3138
3139 InVals.push_back(ArgValue);
3140
3141 } else { // VA.isRegLoc()
3142 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3143 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003144 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003145
3146 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003147 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3148 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003149 BEAlign = 8 - ArgSize;
3150
Matthias Braun941a7052016-07-28 18:40:00 +00003151 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003152
3153 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003154 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003155 SDValue ArgValue;
3156
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003157 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003158 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003159 MVT MemVT = VA.getValVT();
3160
Tim Northover47e003c2014-05-26 17:21:53 +00003161 switch (VA.getLocInfo()) {
3162 default:
3163 break;
Tim Northover6890add2014-06-03 13:54:53 +00003164 case CCValAssign::BCvt:
3165 MemVT = VA.getLocVT();
3166 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003167 case CCValAssign::SExt:
3168 ExtType = ISD::SEXTLOAD;
3169 break;
3170 case CCValAssign::ZExt:
3171 ExtType = ISD::ZEXTLOAD;
3172 break;
3173 case CCValAssign::AExt:
3174 ExtType = ISD::EXTLOAD;
3175 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003176 }
3177
Alex Lorenze40c8a22015-08-11 23:09:45 +00003178 ArgValue = DAG.getExtLoad(
3179 ExtType, DL, VA.getLocVT(), Chain, FIN,
3180 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003181 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003182
Tim Northover3b0846e2014-05-24 12:50:23 +00003183 InVals.push_back(ArgValue);
3184 }
3185 }
3186
3187 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003188 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003189 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003190 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003191 // The AAPCS variadic function ABI is identical to the non-variadic
3192 // one. As a result there may be more arguments in registers and we should
3193 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003194 // Win64 variadic functions also pass arguments in registers, but all float
3195 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003196 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3197 }
3198
Tim Northover3b0846e2014-05-24 12:50:23 +00003199 // This will point to the next argument passed via stack.
3200 unsigned StackOffset = CCInfo.getNextStackOffset();
3201 // We currently pass all varargs at 8-byte alignment.
3202 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003203 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003204
3205 if (MFI.hasMustTailInVarArgFunc()) {
3206 SmallVector<MVT, 2> RegParmTypes;
3207 RegParmTypes.push_back(MVT::i64);
3208 RegParmTypes.push_back(MVT::f128);
3209 // Compute the set of forwarded registers. The rest are scratch.
3210 SmallVectorImpl<ForwardedRegister> &Forwards =
3211 FuncInfo->getForwardedMustTailRegParms();
3212 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3213 CC_AArch64_AAPCS);
Reid Klecknerb7a78c72019-05-24 01:27:20 +00003214
3215 // Conservatively forward X8, since it might be used for aggregate return.
3216 if (!CCInfo.isAllocated(AArch64::X8)) {
3217 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3218 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3219 }
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003220 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003221 }
3222
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003223 // On Windows, InReg pointers must be returned, so record the pointer in a
3224 // virtual register at the start of the function so it can be returned in the
3225 // epilogue.
3226 if (IsWin64) {
3227 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3228 if (Ins[I].Flags.isInReg()) {
3229 assert(!FuncInfo->getSRetReturnReg());
3230
3231 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3232 unsigned Reg =
3233 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3234 FuncInfo->setSRetReturnReg(Reg);
3235
3236 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3237 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3238 break;
3239 }
3240 }
3241 }
3242
Tim Northover3b0846e2014-05-24 12:50:23 +00003243 unsigned StackArgSize = CCInfo.getNextStackOffset();
3244 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3245 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3246 // This is a non-standard ABI so by fiat I say we're allowed to make full
3247 // use of the stack area to be popped, which must be aligned to 16 bytes in
3248 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003249 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003250
3251 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3252 // a multiple of 16.
3253 FuncInfo->setArgumentStackToRestore(StackArgSize);
3254
3255 // This realignment carries over to the available bytes below. Our own
3256 // callers will guarantee the space is free by giving an aligned value to
3257 // CALLSEQ_START.
3258 }
3259 // Even if we're not expected to free up the space, it's useful to know how
3260 // much is there while considering tail calls (because we can reuse it).
3261 FuncInfo->setBytesInStackArgArea(StackArgSize);
3262
Tri Vo6c47c622018-09-22 22:17:50 +00003263 if (Subtarget->hasCustomCallingConv())
3264 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3265
Tim Northover3b0846e2014-05-24 12:50:23 +00003266 return Chain;
3267}
3268
3269void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003270 SelectionDAG &DAG,
3271 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003272 SDValue &Chain) const {
3273 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003274 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003275 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003276 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003277 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003278
3279 SmallVector<SDValue, 8> MemOps;
3280
3281 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3282 AArch64::X3, AArch64::X4, AArch64::X5,
3283 AArch64::X6, AArch64::X7 };
3284 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003285 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003286
3287 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3288 int GPRIdx = 0;
3289 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003290 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003291 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003292 if (GPRSaveSize & 15)
3293 // The extra size here, if triggered, will always be 8.
3294 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3295 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003296 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003297
Mehdi Amini44ede332015-07-09 02:09:04 +00003298 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003299
3300 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3301 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3302 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003303 SDValue Store = DAG.getStore(
3304 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003305 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003306 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3307 GPRIdx,
3308 (i - FirstVariadicGPR) * 8)
3309 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003310 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003311 FIN =
3312 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003313 }
3314 }
3315 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3316 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3317
Martin Storsjo2f24e932017-07-17 20:05:19 +00003318 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003319 static const MCPhysReg FPRArgRegs[] = {
3320 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3321 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3322 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003323 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003324
3325 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3326 int FPRIdx = 0;
3327 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003328 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003329
Mehdi Amini44ede332015-07-09 02:09:04 +00003330 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003331
3332 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3333 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3334 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3335
Alex Lorenze40c8a22015-08-11 23:09:45 +00003336 SDValue Store = DAG.getStore(
3337 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003338 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003339 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003340 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3341 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003342 }
3343 }
3344 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3345 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3346 }
3347
3348 if (!MemOps.empty()) {
3349 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3350 }
3351}
3352
3353/// LowerCallResult - Lower the result values of a call into the
3354/// appropriate copies out of appropriate physical registers.
3355SDValue AArch64TargetLowering::LowerCallResult(
3356 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003357 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3358 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003359 SDValue ThisVal) const {
3360 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3361 ? RetCC_AArch64_WebKit_JS
3362 : RetCC_AArch64_AAPCS;
3363 // Assign locations to each value returned by this call.
3364 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003365 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3366 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003367 CCInfo.AnalyzeCallResult(Ins, RetCC);
3368
3369 // Copy all of the result registers out of their specified physreg.
3370 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3371 CCValAssign VA = RVLocs[i];
3372
3373 // Pass 'this' value directly from the argument to return value, to avoid
3374 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003375 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003376 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3377 "unexpected return calling convention register assignment");
3378 InVals.push_back(ThisVal);
3379 continue;
3380 }
3381
3382 SDValue Val =
3383 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3384 Chain = Val.getValue(1);
3385 InFlag = Val.getValue(2);
3386
3387 switch (VA.getLocInfo()) {
3388 default:
3389 llvm_unreachable("Unknown loc info!");
3390 case CCValAssign::Full:
3391 break;
3392 case CCValAssign::BCvt:
3393 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3394 break;
3395 }
3396
3397 InVals.push_back(Val);
3398 }
3399
3400 return Chain;
3401}
3402
Matthias Braun1af14142016-09-13 19:27:38 +00003403/// Return true if the calling convention is one that we can guarantee TCO for.
3404static bool canGuaranteeTCO(CallingConv::ID CC) {
3405 return CC == CallingConv::Fast;
3406}
3407
3408/// Return true if we might ever do TCO for calls with this calling convention.
3409static bool mayTailCallThisCC(CallingConv::ID CC) {
3410 switch (CC) {
3411 case CallingConv::C:
3412 case CallingConv::PreserveMost:
3413 case CallingConv::Swift:
3414 return true;
3415 default:
3416 return canGuaranteeTCO(CC);
3417 }
3418}
3419
Tim Northover3b0846e2014-05-24 12:50:23 +00003420bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3421 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003422 const SmallVectorImpl<ISD::OutputArg> &Outs,
3423 const SmallVectorImpl<SDValue> &OutVals,
3424 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003425 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003426 return false;
3427
Matthias Braun8d414362016-03-30 22:46:04 +00003428 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003429 const Function &CallerF = MF.getFunction();
3430 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003431 bool CCMatch = CallerCC == CalleeCC;
3432
3433 // Byval parameters hand the function a pointer directly into the stack area
3434 // we want to reuse during a tail call. Working around this *is* possible (see
3435 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003436 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3437 e = CallerF.arg_end();
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003438 i != e; ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003439 if (i->hasByValAttr())
3440 return false;
3441
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003442 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3443 // In this case, it is necessary to save/restore X0 in the callee. Tail
3444 // call opt interferes with this. So we disable tail call opt when the
3445 // caller has an argument with "inreg" attribute.
3446
3447 // FIXME: Check whether the callee also has an "inreg" argument.
3448 if (i->hasInRegAttr())
3449 return false;
3450 }
3451
Matthias Braun1af14142016-09-13 19:27:38 +00003452 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3453 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003454
Oliver Stannard12993dd2014-08-18 12:42:15 +00003455 // Externally-defined functions with weak linkage should not be
3456 // tail-called on AArch64 when the OS does not support dynamic
3457 // pre-emption of symbols, as the AAELF spec requires normal calls
3458 // to undefined weak functions to be replaced with a NOP or jump to the
3459 // next instruction. The behaviour of branch instructions in this
3460 // situation (as used for tail calls) is implementation-defined, so we
3461 // cannot rely on the linker replacing the tail call with a return.
3462 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3463 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003464 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003465 if (GV->hasExternalWeakLinkage() &&
3466 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003467 return false;
3468 }
3469
Tim Northover3b0846e2014-05-24 12:50:23 +00003470 // Now we search for cases where we can use a tail call without changing the
3471 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3472 // concept.
3473
3474 // I want anyone implementing a new calling convention to think long and hard
3475 // about this assert.
3476 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3477 "Unexpected variadic calling convention");
3478
Matthias Braun8d414362016-03-30 22:46:04 +00003479 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003480 if (isVarArg && !Outs.empty()) {
3481 // At least two cases here: if caller is fastcc then we can't have any
3482 // memory arguments (we'd be expected to clean up the stack afterwards). If
3483 // caller is C then we could potentially use its argument area.
3484
3485 // FIXME: for now we take the most conservative of these in both cases:
3486 // disallow all variadic memory operands.
3487 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003488 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003489
3490 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003491 for (const CCValAssign &ArgLoc : ArgLocs)
3492 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003493 return false;
3494 }
3495
Matthias Braun8d414362016-03-30 22:46:04 +00003496 // Check that the call results are passed in the same way.
3497 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3498 CCAssignFnForCall(CalleeCC, isVarArg),
3499 CCAssignFnForCall(CallerCC, isVarArg)))
3500 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003501 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003502 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3503 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003504 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003505 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003506 if (Subtarget->hasCustomCallingConv()) {
3507 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3508 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3509 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003510 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003511 return false;
3512 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003513
3514 // Nothing more to check if the callee is taking no arguments
3515 if (Outs.empty())
3516 return true;
3517
3518 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003519 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003520
3521 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3522
3523 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3524
Matthias Braun74a0bd32016-04-13 21:43:16 +00003525 // If the stack arguments for this call do not fit into our own save area then
3526 // the call cannot be made tail.
3527 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3528 return false;
3529
Matthias Braun46b0f032016-04-14 01:10:42 +00003530 const MachineRegisterInfo &MRI = MF.getRegInfo();
3531 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3532 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003533
3534 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003535}
3536
3537SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3538 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003539 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003540 int ClobberedFI) const {
3541 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003542 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3543 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003544
3545 // Include the original chain at the beginning of the list. When this is
3546 // used by target LowerCall hooks, this helps legalize find the
3547 // CALLSEQ_BEGIN node.
3548 ArgChains.push_back(Chain);
3549
3550 // Add a chain value for each stack argument corresponding
3551 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3552 UE = DAG.getEntryNode().getNode()->use_end();
3553 U != UE; ++U)
3554 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3555 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3556 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003557 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003558 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003559 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003560
3561 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3562 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3563 ArgChains.push_back(SDValue(L, 1));
3564 }
3565
3566 // Build a tokenfactor for all the chains.
3567 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3568}
3569
3570bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3571 bool TailCallOpt) const {
3572 return CallCC == CallingConv::Fast && TailCallOpt;
3573}
3574
Tim Northover3b0846e2014-05-24 12:50:23 +00003575/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3576/// and add input and output parameter nodes.
3577SDValue
3578AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3579 SmallVectorImpl<SDValue> &InVals) const {
3580 SelectionDAG &DAG = CLI.DAG;
3581 SDLoc &DL = CLI.DL;
3582 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3583 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3584 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3585 SDValue Chain = CLI.Chain;
3586 SDValue Callee = CLI.Callee;
3587 bool &IsTailCall = CLI.IsTailCall;
3588 CallingConv::ID CallConv = CLI.CallConv;
3589 bool IsVarArg = CLI.IsVarArg;
3590
3591 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003592 bool IsThisReturn = false;
3593
3594 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3595 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3596 bool IsSibCall = false;
3597
3598 if (IsTailCall) {
3599 // Check if it's really possible to do a tail call.
3600 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003601 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003602 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003603 report_fatal_error("failed to perform tail call elimination on a call "
3604 "site marked musttail");
3605
3606 // A sibling call is one where we're under the usual C ABI and not planning
3607 // to change that but can still do a tail call:
3608 if (!TailCallOpt && IsTailCall)
3609 IsSibCall = true;
3610
3611 if (IsTailCall)
3612 ++NumTailCalls;
3613 }
3614
3615 // Analyze operands of the call, assigning locations to each operand.
3616 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003617 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3618 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003619
3620 if (IsVarArg) {
3621 // Handle fixed and variable vector arguments differently.
3622 // Variable vector arguments always go into memory.
3623 unsigned NumArgs = Outs.size();
3624
3625 for (unsigned i = 0; i != NumArgs; ++i) {
3626 MVT ArgVT = Outs[i].VT;
3627 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3628 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3629 /*IsVarArg=*/ !Outs[i].IsFixed);
3630 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3631 assert(!Res && "Call operand has unhandled type");
3632 (void)Res;
3633 }
3634 } else {
3635 // At this point, Outs[].VT may already be promoted to i32. To correctly
3636 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3637 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3638 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3639 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3640 // LocVT.
3641 unsigned NumArgs = Outs.size();
3642 for (unsigned i = 0; i != NumArgs; ++i) {
3643 MVT ValVT = Outs[i].VT;
3644 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003645 EVT ActualVT = getValueType(DAG.getDataLayout(),
3646 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003647 /*AllowUnknown*/ true);
3648 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3649 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3650 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003651 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003652 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003653 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003654 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003655
3656 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003657 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003658 assert(!Res && "Call operand has unhandled type");
3659 (void)Res;
3660 }
3661 }
3662
3663 // Get a count of how many bytes are to be pushed on the stack.
3664 unsigned NumBytes = CCInfo.getNextStackOffset();
3665
3666 if (IsSibCall) {
3667 // Since we're not changing the ABI to make this a tail call, the memory
3668 // operands are already available in the caller's incoming argument space.
3669 NumBytes = 0;
3670 }
3671
3672 // FPDiff is the byte offset of the call's argument area from the callee's.
3673 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3674 // by this amount for a tail call. In a sibling call it must be 0 because the
3675 // caller will deallocate the entire stack and the callee still expects its
3676 // arguments to begin at SP+0. Completely unused for non-tail calls.
3677 int FPDiff = 0;
3678
3679 if (IsTailCall && !IsSibCall) {
3680 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3681
3682 // Since callee will pop argument stack as a tail call, we must keep the
3683 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003684 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003685
3686 // FPDiff will be negative if this tail call requires more space than we
3687 // would automatically have in our incoming argument space. Positive if we
3688 // can actually shrink the stack.
3689 FPDiff = NumReusableBytes - NumBytes;
3690
3691 // The stack pointer must be 16-byte aligned at all times it's used for a
3692 // memory operation, which in practice means at *all* times and in
3693 // particular across call boundaries. Therefore our own arguments started at
3694 // a 16-byte aligned SP and the delta applied for the tail call should
3695 // satisfy the same constraint.
3696 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3697 }
3698
3699 // Adjust the stack pointer for the new arguments...
3700 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003701 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003702 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003703
Mehdi Amini44ede332015-07-09 02:09:04 +00003704 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3705 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003706
3707 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3708 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003709 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003710
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003711 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3712 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3713 for (const auto &F : Forwards) {
3714 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3715 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3716 }
3717 }
3718
Tim Northover3b0846e2014-05-24 12:50:23 +00003719 // Walk the register/memloc assignments, inserting copies/loads.
3720 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3721 ++i, ++realArgIdx) {
3722 CCValAssign &VA = ArgLocs[i];
3723 SDValue Arg = OutVals[realArgIdx];
3724 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3725
3726 // Promote the value if needed.
3727 switch (VA.getLocInfo()) {
3728 default:
3729 llvm_unreachable("Unknown loc info!");
3730 case CCValAssign::Full:
3731 break;
3732 case CCValAssign::SExt:
3733 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3734 break;
3735 case CCValAssign::ZExt:
3736 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3737 break;
3738 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003739 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3740 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3741 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3742 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3743 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003744 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3745 break;
3746 case CCValAssign::BCvt:
3747 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3748 break;
3749 case CCValAssign::FPExt:
3750 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3751 break;
3752 }
3753
3754 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003755 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3756 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003757 assert(VA.getLocVT() == MVT::i64 &&
3758 "unexpected calling convention register assignment");
3759 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3760 "unexpected use of 'returned'");
3761 IsThisReturn = true;
3762 }
3763 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3764 } else {
3765 assert(VA.isMemLoc());
3766
3767 SDValue DstAddr;
3768 MachinePointerInfo DstInfo;
3769
3770 // FIXME: This works on big-endian for composite byvals, which are the
3771 // common case. It should also work for fundamental types too.
3772 uint32_t BEAlign = 0;
3773 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003774 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003775 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003776 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3777 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003778 if (OpSize < 8)
3779 BEAlign = 8 - OpSize;
3780 }
3781 unsigned LocMemOffset = VA.getLocMemOffset();
3782 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003783 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003784 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003785
3786 if (IsTailCall) {
3787 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003788 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003789
Mehdi Amini44ede332015-07-09 02:09:04 +00003790 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003791 DstInfo =
3792 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003793
3794 // Make sure any stack arguments overlapping with where we're storing
3795 // are loaded before this eventual operation. Otherwise they'll be
3796 // clobbered.
3797 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3798 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003799 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003800
Mehdi Amini44ede332015-07-09 02:09:04 +00003801 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003802 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3803 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003804 }
3805
3806 if (Outs[i].Flags.isByVal()) {
3807 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003808 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003809 SDValue Cpy = DAG.getMemcpy(
3810 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003811 /*isVol = */ false, /*AlwaysInline = */ false,
3812 /*isTailCall = */ false,
3813 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003814
3815 MemOpChains.push_back(Cpy);
3816 } else {
3817 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3818 // promoted to a legal register type i32, we should truncate Arg back to
3819 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003820 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3821 VA.getValVT() == MVT::i16)
3822 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003823
Justin Lebar9c375812016-07-15 18:27:10 +00003824 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003825 MemOpChains.push_back(Store);
3826 }
3827 }
3828 }
3829
3830 if (!MemOpChains.empty())
3831 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3832
3833 // Build a sequence of copy-to-reg nodes chained together with token chain
3834 // and flag operands which copy the outgoing args into the appropriate regs.
3835 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003836 for (auto &RegToPass : RegsToPass) {
3837 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3838 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003839 InFlag = Chain.getValue(1);
3840 }
3841
3842 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3843 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3844 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003845 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3846 auto GV = G->getGlobal();
3847 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3848 AArch64II::MO_GOT) {
3849 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3850 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003851 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3852 assert(Subtarget->isTargetWindows() &&
3853 "Windows is the only supported COFF target");
3854 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003855 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003856 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003857 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3858 }
3859 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3860 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3861 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003862 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003863 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3864 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003865 } else {
3866 const char *Sym = S->getSymbol();
3867 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003868 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003869 }
3870
3871 // We don't usually want to end the call-sequence here because we would tidy
3872 // the frame up *after* the call, however in the ABI-changing tail-call case
3873 // we've carefully laid out the parameters so that when sp is reset they'll be
3874 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003875 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003876 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3877 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003878 InFlag = Chain.getValue(1);
3879 }
3880
3881 std::vector<SDValue> Ops;
3882 Ops.push_back(Chain);
3883 Ops.push_back(Callee);
3884
3885 if (IsTailCall) {
3886 // Each tail call may have to adjust the stack by a different amount, so
3887 // this information must travel along with the operation for eventual
3888 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003889 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003890 }
3891
3892 // Add argument registers to the end of the list so that they are known live
3893 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003894 for (auto &RegToPass : RegsToPass)
3895 Ops.push_back(DAG.getRegister(RegToPass.first,
3896 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003897
3898 // Add a register mask operand representing the call-preserved registers.
3899 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003900 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003901 if (IsThisReturn) {
3902 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003903 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003904 if (!Mask) {
3905 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003906 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003907 }
3908 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003909 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003910
Tri Vo6c47c622018-09-22 22:17:50 +00003911 if (Subtarget->hasCustomCallingConv())
3912 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3913
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003914 if (TRI->isAnyArgRegReserved(MF))
3915 TRI->emitReservedArgRegCallError(MF);
3916
Tim Northover3b0846e2014-05-24 12:50:23 +00003917 assert(Mask && "Missing call preserved mask for calling convention");
3918 Ops.push_back(DAG.getRegisterMask(Mask));
3919
3920 if (InFlag.getNode())
3921 Ops.push_back(InFlag);
3922
3923 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3924
3925 // If we're doing a tall call, use a TC_RETURN here rather than an
3926 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003927 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003928 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003929 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003930 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003931
3932 // Returns a chain and a flag for retval copy to use.
3933 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3934 InFlag = Chain.getValue(1);
3935
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003936 uint64_t CalleePopBytes =
3937 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003938
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003939 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3940 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3941 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003942 if (!Ins.empty())
3943 InFlag = Chain.getValue(1);
3944
3945 // Handle result values, copying them out of physregs into vregs that we
3946 // return.
3947 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3948 InVals, IsThisReturn,
3949 IsThisReturn ? OutVals[0] : SDValue());
3950}
3951
3952bool AArch64TargetLowering::CanLowerReturn(
3953 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3954 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3955 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3956 ? RetCC_AArch64_WebKit_JS
3957 : RetCC_AArch64_AAPCS;
3958 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003959 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003960 return CCInfo.CheckReturn(Outs, RetCC);
3961}
3962
3963SDValue
3964AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3965 bool isVarArg,
3966 const SmallVectorImpl<ISD::OutputArg> &Outs,
3967 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003968 const SDLoc &DL, SelectionDAG &DAG) const {
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003969 auto &MF = DAG.getMachineFunction();
3970 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3971
Tim Northover3b0846e2014-05-24 12:50:23 +00003972 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3973 ? RetCC_AArch64_WebKit_JS
3974 : RetCC_AArch64_AAPCS;
3975 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003976 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3977 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003978 CCInfo.AnalyzeReturn(Outs, RetCC);
3979
3980 // Copy the result values into the output registers.
3981 SDValue Flag;
3982 SmallVector<SDValue, 4> RetOps(1, Chain);
3983 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3984 ++i, ++realRVLocIdx) {
3985 CCValAssign &VA = RVLocs[i];
3986 assert(VA.isRegLoc() && "Can only return in registers!");
3987 SDValue Arg = OutVals[realRVLocIdx];
3988
3989 switch (VA.getLocInfo()) {
3990 default:
3991 llvm_unreachable("Unknown loc info!");
3992 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003993 if (Outs[i].ArgVT == MVT::i1) {
3994 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3995 // value. This is strictly redundant on Darwin (which uses "zeroext
3996 // i1"), but will be optimised out before ISel.
3997 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3998 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3999 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004000 break;
4001 case CCValAssign::BCvt:
4002 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4003 break;
4004 }
4005
4006 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
4007 Flag = Chain.getValue(1);
4008 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4009 }
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00004010
4011 // Windows AArch64 ABIs require that for returning structs by value we copy
4012 // the sret argument into X0 for the return.
4013 // We saved the argument into a virtual register in the entry block,
4014 // so now we copy the value out and into X0.
4015 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4016 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4017 getPointerTy(MF.getDataLayout()));
4018
4019 unsigned RetValReg = AArch64::X0;
4020 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4021 Flag = Chain.getValue(1);
4022
4023 RetOps.push_back(
4024 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4025 }
4026
Manman Rencbe4f942015-12-16 21:04:19 +00004027 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4028 const MCPhysReg *I =
4029 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4030 if (I) {
4031 for (; *I; ++I) {
4032 if (AArch64::GPR64RegClass.contains(*I))
4033 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4034 else if (AArch64::FPR64RegClass.contains(*I))
4035 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4036 else
4037 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4038 }
4039 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004040
4041 RetOps[0] = Chain; // Update chain.
4042
4043 // Add the flag if we have it.
4044 if (Flag.getNode())
4045 RetOps.push_back(Flag);
4046
4047 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4048}
4049
4050//===----------------------------------------------------------------------===//
4051// Other Lowering Code
4052//===----------------------------------------------------------------------===//
4053
Joel Jonesa7c4a522017-04-21 17:31:03 +00004054SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4055 SelectionDAG &DAG,
4056 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004057 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4058 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004059}
4060
4061SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4062 SelectionDAG &DAG,
4063 unsigned Flag) const {
4064 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4065}
4066
4067SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4068 SelectionDAG &DAG,
4069 unsigned Flag) const {
4070 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4071 N->getOffset(), Flag);
4072}
4073
4074SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4075 SelectionDAG &DAG,
4076 unsigned Flag) const {
4077 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4078}
4079
4080// (loadGOT sym)
4081template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004082SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4083 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004084 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004085 SDLoc DL(N);
4086 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004087 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004088 // FIXME: Once remat is capable of dealing with instructions with register
4089 // operands, expand this into two nodes instead of using a wrapper node.
4090 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4091}
4092
4093// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4094template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004095SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4096 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004097 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004098 SDLoc DL(N);
4099 EVT Ty = getPointerTy(DAG.getDataLayout());
4100 const unsigned char MO_NC = AArch64II::MO_NC;
4101 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004102 AArch64ISD::WrapperLarge, DL, Ty,
4103 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4104 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4105 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4106 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004107}
4108
4109// (addlow (adrp %hi(sym)) %lo(sym))
4110template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004111SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4112 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004113 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004114 SDLoc DL(N);
4115 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004116 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004117 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004118 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004119 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4120 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4121}
4122
David Green9dd1d452018-08-22 11:31:39 +00004123// (adr sym)
4124template <class NodeTy>
4125SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4126 unsigned Flags) const {
4127 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4128 SDLoc DL(N);
4129 EVT Ty = getPointerTy(DAG.getDataLayout());
4130 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4131 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4132}
4133
Tim Northover3b0846e2014-05-24 12:50:23 +00004134SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4135 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004136 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004137 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004138 unsigned char OpFlags =
4139 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004140
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004141 if (OpFlags != AArch64II::MO_NO_FLAG)
4142 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4143 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004144
David Green9dd1d452018-08-22 11:31:39 +00004145 // This also catches the large code model case for Darwin, and tiny code
4146 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004147 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004148 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004149 }
4150
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004151 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004152 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004153 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004154 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004155 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004156 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004157 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004158 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004159 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4160 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004161 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004162 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4163 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4164 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004165}
4166
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004167/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004168/// and calls to compute the variable's address (for Darwin, currently) and
4169/// return an SDValue containing the final node.
4170
4171/// Darwin only has one TLS scheme which must be capable of dealing with the
4172/// fully general situation, in the worst case. This means:
4173/// + "extern __thread" declaration.
4174/// + Defined in a possibly unknown dynamic library.
4175///
4176/// The general system is that each __thread variable has a [3 x i64] descriptor
4177/// which contains information used by the runtime to calculate the address. The
4178/// only part of this the compiler needs to know about is the first xword, which
4179/// contains a function pointer that must be called with the address of the
4180/// entire descriptor in "x0".
4181///
4182/// Since this descriptor may be in a different unit, in general even the
4183/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4184/// is:
4185/// adrp x0, _var@TLVPPAGE
4186/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4187/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4188/// ; the function pointer
4189/// blr x1 ; Uses descriptor address in x0
4190/// ; Address of _var is now in x0.
4191///
4192/// If the address of _var's descriptor *is* known to the linker, then it can
4193/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4194/// a slight efficiency gain.
4195SDValue
4196AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4197 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004198 assert(Subtarget->isTargetDarwin() &&
4199 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004200
4201 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004202 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004203 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4204
4205 SDValue TLVPAddr =
4206 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4207 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4208
4209 // The first entry in the descriptor is a function pointer that we must call
4210 // to obtain the address of the variable.
4211 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004212 SDValue FuncTLVGet = DAG.getLoad(
4213 MVT::i64, DL, Chain, DescAddr,
4214 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4215 /* Alignment = */ 8,
4216 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4217 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004218 Chain = FuncTLVGet.getValue(1);
4219
Matthias Braun941a7052016-07-28 18:40:00 +00004220 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4221 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004222
4223 // TLS calls preserve all registers except those that absolutely must be
4224 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4225 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004226 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4227 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4228 if (Subtarget->hasCustomCallingConv())
4229 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004230
4231 // Finally, we can make the call. This is just a degenerate version of a
4232 // normal AArch64 call node: x0 takes the address of the descriptor, and
4233 // returns the address of the variable in this thread.
4234 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4235 Chain =
4236 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4237 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4238 DAG.getRegisterMask(Mask), Chain.getValue(1));
4239 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4240}
4241
4242/// When accessing thread-local variables under either the general-dynamic or
4243/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4244/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004245/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004246///
Kristof Beylsaea84612015-03-04 09:12:08 +00004247/// The sequence is:
4248/// adrp x0, :tlsdesc:var
4249/// ldr x1, [x0, #:tlsdesc_lo12:var]
4250/// add x0, x0, #:tlsdesc_lo12:var
4251/// .tlsdesccall var
4252/// blr x1
4253/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004254///
Kristof Beylsaea84612015-03-04 09:12:08 +00004255/// The above sequence must be produced unscheduled, to enable the linker to
4256/// optimize/relax this sequence.
4257/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4258/// above sequence, and expanded really late in the compilation flow, to ensure
4259/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004260SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4261 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004262 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004263 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004264
Kristof Beylsaea84612015-03-04 09:12:08 +00004265 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004266 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004267
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004268 Chain =
4269 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004270 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004271
4272 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4273}
4274
4275SDValue
4276AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4277 SelectionDAG &DAG) const {
4278 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004279 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4280 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004281 // Different choices can be made for the maximum size of the TLS area for a
4282 // module. For the small address model, the default TLS size is 16MiB and the
4283 // maximum TLS size is 4GiB.
4284 // FIXME: add -mtls-size command line option and make it control the 16MiB
4285 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004286 // FIXME: add tiny codemodel support. We currently generate the same code as
4287 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004288 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4289
4290 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004291
Kristof Beylsaea84612015-03-04 09:12:08 +00004292 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4293 if (Model == TLSModel::LocalDynamic)
4294 Model = TLSModel::GeneralDynamic;
4295 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004296
4297 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004298 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004299 SDLoc DL(Op);
4300 const GlobalValue *GV = GA->getGlobal();
4301
4302 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4303
4304 if (Model == TLSModel::LocalExec) {
4305 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004306 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004307 SDValue LoVar = DAG.getTargetGlobalAddress(
4308 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004309 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004310
Kristof Beylsaea84612015-03-04 09:12:08 +00004311 SDValue TPWithOff_lo =
4312 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004313 HiVar,
4314 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004315 0);
4316 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004317 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4318 LoVar,
4319 DAG.getTargetConstant(0, DL, MVT::i32)),
4320 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004321 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004322 } else if (Model == TLSModel::InitialExec) {
4323 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4324 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4325 } else if (Model == TLSModel::LocalDynamic) {
4326 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4327 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4328 // the beginning of the module's TLS region, followed by a DTPREL offset
4329 // calculation.
4330
4331 // These accesses will need deduplicating if there's more than one.
4332 AArch64FunctionInfo *MFI =
4333 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4334 MFI->incNumLocalDynamicTLSAccesses();
4335
Tim Northover3b0846e2014-05-24 12:50:23 +00004336 // The call needs a relocation too for linker relaxation. It doesn't make
4337 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4338 // the address.
4339 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4340 AArch64II::MO_TLS);
4341
4342 // Now we can calculate the offset from TPIDR_EL0 to this module's
4343 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004344 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004345
4346 // Now use :dtprel_whatever: operations to calculate this variable's offset
4347 // in its thread-storage area.
4348 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004349 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004350 SDValue LoVar = DAG.getTargetGlobalAddress(
4351 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004352 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4353
Kristof Beylsaea84612015-03-04 09:12:08 +00004354 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004355 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004356 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004357 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4358 DAG.getTargetConstant(0, DL, MVT::i32)),
4359 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004360 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004361 // The call needs a relocation too for linker relaxation. It doesn't make
4362 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4363 // the address.
4364 SDValue SymAddr =
4365 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4366
4367 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004368 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004369 } else
4370 llvm_unreachable("Unsupported ELF TLS access model");
4371
4372 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4373}
4374
Martin Storsjocc240962018-03-10 19:05:21 +00004375SDValue
4376AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4377 SelectionDAG &DAG) const {
4378 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4379
4380 SDValue Chain = DAG.getEntryNode();
4381 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4382 SDLoc DL(Op);
4383
4384 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4385
4386 // Load the ThreadLocalStoragePointer from the TEB
4387 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4388 SDValue TLSArray =
4389 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4390 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4391 Chain = TLSArray.getValue(1);
4392
4393 // Load the TLS index from the C runtime;
4394 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4395 // This also does the same as LOADgot, but using a generic i32 load,
4396 // while LOADgot only loads i64.
4397 SDValue TLSIndexHi =
4398 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4399 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4400 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4401 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4402 SDValue TLSIndex =
4403 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4404 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4405 Chain = TLSIndex.getValue(1);
4406
4407 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4408 // offset into the TLSArray.
4409 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4410 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4411 DAG.getConstant(3, DL, PtrVT));
4412 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4413 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4414 MachinePointerInfo());
4415 Chain = TLS.getValue(1);
4416
4417 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4418 const GlobalValue *GV = GA->getGlobal();
4419 SDValue TGAHi = DAG.getTargetGlobalAddress(
4420 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4421 SDValue TGALo = DAG.getTargetGlobalAddress(
4422 GV, DL, PtrVT, 0,
4423 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4424
4425 // Add the offset from the start of the .tls section (section base).
4426 SDValue Addr =
4427 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4428 DAG.getTargetConstant(0, DL, MVT::i32)),
4429 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004430 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004431 return Addr;
4432}
4433
Tim Northover3b0846e2014-05-24 12:50:23 +00004434SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4435 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004436 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004437 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004438 return LowerToTLSEmulatedModel(GA, DAG);
4439
Tim Northover3b0846e2014-05-24 12:50:23 +00004440 if (Subtarget->isTargetDarwin())
4441 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004442 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004443 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004444 if (Subtarget->isTargetWindows())
4445 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004446
4447 llvm_unreachable("Unexpected platform trying to use TLS");
4448}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004449
Tim Northover3b0846e2014-05-24 12:50:23 +00004450SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4451 SDValue Chain = Op.getOperand(0);
4452 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4453 SDValue LHS = Op.getOperand(2);
4454 SDValue RHS = Op.getOperand(3);
4455 SDValue Dest = Op.getOperand(4);
4456 SDLoc dl(Op);
4457
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004458 MachineFunction &MF = DAG.getMachineFunction();
4459 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4460 // will not be produced, as they are conditional branch instructions that do
4461 // not set flags.
4462 bool ProduceNonFlagSettingCondBr =
4463 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4464
Tim Northover3b0846e2014-05-24 12:50:23 +00004465 // Handle f128 first, since lowering it will result in comparing the return
4466 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4467 // is expecting to deal with.
4468 if (LHS.getValueType() == MVT::f128) {
4469 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4470
4471 // If softenSetCCOperands returned a scalar, we need to compare the result
4472 // against zero to select between true and false values.
4473 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004474 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004475 CC = ISD::SETNE;
4476 }
4477 }
4478
4479 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4480 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004481 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4482 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004483 // Only lower legal XALUO ops.
4484 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4485 return SDValue();
4486
4487 // The actual operation with overflow check.
4488 AArch64CC::CondCode OFCC;
4489 SDValue Value, Overflow;
4490 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4491
4492 if (CC == ISD::SETNE)
4493 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004494 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004495
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004496 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4497 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004498 }
4499
4500 if (LHS.getValueType().isInteger()) {
4501 assert((LHS.getValueType() == RHS.getValueType()) &&
4502 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4503
4504 // If the RHS of the comparison is zero, we can potentially fold this
4505 // to a specialized branch.
4506 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004507 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004508 if (CC == ISD::SETEQ) {
4509 // See if we can use a TBZ to fold in an AND as well.
4510 // TBZ has a smaller branch displacement than CBZ. If the offset is
4511 // out of bounds, a late MI-layer pass rewrites branches.
4512 // 403.gcc is an example that hits this case.
4513 if (LHS.getOpcode() == ISD::AND &&
4514 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4515 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4516 SDValue Test = LHS.getOperand(0);
4517 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004518 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004519 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4520 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004521 }
4522
4523 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4524 } else if (CC == ISD::SETNE) {
4525 // See if we can use a TBZ to fold in an AND as well.
4526 // TBZ has a smaller branch displacement than CBZ. If the offset is
4527 // out of bounds, a late MI-layer pass rewrites branches.
4528 // 403.gcc is an example that hits this case.
4529 if (LHS.getOpcode() == ISD::AND &&
4530 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4531 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4532 SDValue Test = LHS.getOperand(0);
4533 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004534 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004535 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4536 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004537 }
4538
4539 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004540 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4541 // Don't combine AND since emitComparison converts the AND to an ANDS
4542 // (a.k.a. TST) and the test in the test bit and branch instruction
4543 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004544 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004545 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004546 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004547 }
4548 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004549 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004550 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004551 // Don't combine AND since emitComparison converts the AND to an ANDS
4552 // (a.k.a. TST) and the test in the test bit and branch instruction
4553 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004554 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004555 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004556 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004557 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004558
4559 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004560 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004561 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4562 Cmp);
4563 }
4564
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004565 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4566 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004567
4568 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4569 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004570 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004571 AArch64CC::CondCode CC1, CC2;
4572 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004573 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004574 SDValue BR1 =
4575 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4576 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004577 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004578 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4579 Cmp);
4580 }
4581
4582 return BR1;
4583}
4584
4585SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4586 SelectionDAG &DAG) const {
4587 EVT VT = Op.getValueType();
4588 SDLoc DL(Op);
4589
4590 SDValue In1 = Op.getOperand(0);
4591 SDValue In2 = Op.getOperand(1);
4592 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004593
4594 if (SrcVT.bitsLT(VT))
4595 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4596 else if (SrcVT.bitsGT(VT))
4597 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004598
4599 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004600 uint64_t EltMask;
4601 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004602
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004603 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004604 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004605 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004606 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004607 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004608 DAG.getUNDEF(VecVT), In2);
4609 } else {
4610 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4611 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4612 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004613 };
4614
4615 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4616 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4617 EltMask = 0x80000000ULL;
4618 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004619 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004620 VecVT = MVT::v2i64;
4621
Eric Christopher572e03a2015-06-19 01:53:21 +00004622 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004623 // immediate moves cannot materialize that in a single instruction for
4624 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004625 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004626
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004627 setVecVal(AArch64::dsub);
4628 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4629 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4630 EltMask = 0x8000ULL;
4631 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004632 } else {
4633 llvm_unreachable("Invalid type for copysign!");
4634 }
4635
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004636 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004637
4638 // If we couldn't materialize the mask above, then the mask vector will be
4639 // the zero vector, and we need to negate it here.
4640 if (VT == MVT::f64 || VT == MVT::v2f64) {
4641 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4642 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4643 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4644 }
4645
4646 SDValue Sel =
4647 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4648
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004649 if (VT == MVT::f16)
4650 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004651 if (VT == MVT::f32)
4652 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4653 else if (VT == MVT::f64)
4654 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4655 else
4656 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4657}
4658
4659SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004660 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004661 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004662 return SDValue();
4663
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004664 if (!Subtarget->hasNEON())
4665 return SDValue();
4666
Tim Northover3b0846e2014-05-24 12:50:23 +00004667 // While there is no integer popcount instruction, it can
4668 // be more efficiently lowered to the following sequence that uses
4669 // AdvSIMD registers/instructions as long as the copies to/from
4670 // the AdvSIMD registers are cheap.
4671 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4672 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4673 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4674 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4675 SDValue Val = Op.getOperand(0);
4676 SDLoc DL(Op);
4677 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004678
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004679 if (VT == MVT::i32 || VT == MVT::i64) {
4680 if (VT == MVT::i32)
4681 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4682 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004683
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004684 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4685 SDValue UaddLV = DAG.getNode(
4686 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4687 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004688
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004689 if (VT == MVT::i64)
4690 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4691 return UaddLV;
4692 }
4693
4694 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4695 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4696 "Unexpected type for custom ctpop lowering");
4697
4698 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4699 Val = DAG.getBitcast(VT8Bit, Val);
4700 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4701
4702 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4703 unsigned EltSize = 8;
4704 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4705 while (EltSize != VT.getScalarSizeInBits()) {
4706 EltSize *= 2;
4707 NumElts /= 2;
4708 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4709 Val = DAG.getNode(
4710 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4711 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4712 }
4713
4714 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004715}
4716
4717SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4718
4719 if (Op.getValueType().isVector())
4720 return LowerVSETCC(Op, DAG);
4721
4722 SDValue LHS = Op.getOperand(0);
4723 SDValue RHS = Op.getOperand(1);
4724 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4725 SDLoc dl(Op);
4726
4727 // We chose ZeroOrOneBooleanContents, so use zero and one.
4728 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004729 SDValue TVal = DAG.getConstant(1, dl, VT);
4730 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004731
4732 // Handle f128 first, since one possible outcome is a normal integer
4733 // comparison which gets picked up by the next if statement.
4734 if (LHS.getValueType() == MVT::f128) {
4735 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4736
4737 // If softenSetCCOperands returned a scalar, use it.
4738 if (!RHS.getNode()) {
4739 assert(LHS.getValueType() == Op.getValueType() &&
4740 "Unexpected setcc expansion!");
4741 return LHS;
4742 }
4743 }
4744
4745 if (LHS.getValueType().isInteger()) {
4746 SDValue CCVal;
4747 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004748 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004749
4750 // Note that we inverted the condition above, so we reverse the order of
4751 // the true and false operands here. This will allow the setcc to be
4752 // matched to a single CSINC instruction.
4753 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4754 }
4755
4756 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004757 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4758 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004759
4760 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4761 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004762 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004763
4764 AArch64CC::CondCode CC1, CC2;
4765 changeFPCCToAArch64CC(CC, CC1, CC2);
4766 if (CC2 == AArch64CC::AL) {
4767 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004768 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004769
4770 // Note that we inverted the condition above, so we reverse the order of
4771 // the true and false operands here. This will allow the setcc to be
4772 // matched to a single CSINC instruction.
4773 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4774 } else {
4775 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4776 // totally clean. Some of them require two CSELs to implement. As is in
4777 // this case, we emit the first CSEL and then emit a second using the output
4778 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4779
4780 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004781 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004782 SDValue CS1 =
4783 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4784
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004785 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004786 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4787 }
4788}
4789
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004790SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4791 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004792 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004793 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004794 // Handle f128 first, because it will result in a comparison of some RTLIB
4795 // call result against zero.
4796 if (LHS.getValueType() == MVT::f128) {
4797 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4798
4799 // If softenSetCCOperands returned a scalar, we need to compare the result
4800 // against zero to select between true and false values.
4801 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004802 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004803 CC = ISD::SETNE;
4804 }
4805 }
4806
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004807 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004808 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004809 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4810 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4811 }
4812
4813 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004814 if (LHS.getValueType().isInteger()) {
4815 assert((LHS.getValueType() == RHS.getValueType()) &&
4816 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4817
4818 unsigned Opcode = AArch64ISD::CSEL;
4819
4820 // If both the TVal and the FVal are constants, see if we can swap them in
4821 // order to for a CSINV or CSINC out of them.
4822 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4823 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4824
4825 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4826 std::swap(TVal, FVal);
4827 std::swap(CTVal, CFVal);
4828 CC = ISD::getSetCCInverse(CC, true);
4829 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4830 std::swap(TVal, FVal);
4831 std::swap(CTVal, CFVal);
4832 CC = ISD::getSetCCInverse(CC, true);
4833 } else if (TVal.getOpcode() == ISD::XOR) {
4834 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4835 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004836 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004837 std::swap(TVal, FVal);
4838 std::swap(CTVal, CFVal);
4839 CC = ISD::getSetCCInverse(CC, true);
4840 }
4841 } else if (TVal.getOpcode() == ISD::SUB) {
4842 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4843 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004844 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004845 std::swap(TVal, FVal);
4846 std::swap(CTVal, CFVal);
4847 CC = ISD::getSetCCInverse(CC, true);
4848 }
4849 } else if (CTVal && CFVal) {
4850 const int64_t TrueVal = CTVal->getSExtValue();
4851 const int64_t FalseVal = CFVal->getSExtValue();
4852 bool Swap = false;
4853
4854 // If both TVal and FVal are constants, see if FVal is the
4855 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4856 // instead of a CSEL in that case.
4857 if (TrueVal == ~FalseVal) {
4858 Opcode = AArch64ISD::CSINV;
4859 } else if (TrueVal == -FalseVal) {
4860 Opcode = AArch64ISD::CSNEG;
4861 } else if (TVal.getValueType() == MVT::i32) {
4862 // If our operands are only 32-bit wide, make sure we use 32-bit
4863 // arithmetic for the check whether we can use CSINC. This ensures that
4864 // the addition in the check will wrap around properly in case there is
4865 // an overflow (which would not be the case if we do the check with
4866 // 64-bit arithmetic).
4867 const uint32_t TrueVal32 = CTVal->getZExtValue();
4868 const uint32_t FalseVal32 = CFVal->getZExtValue();
4869
4870 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4871 Opcode = AArch64ISD::CSINC;
4872
4873 if (TrueVal32 > FalseVal32) {
4874 Swap = true;
4875 }
4876 }
4877 // 64-bit check whether we can use CSINC.
4878 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4879 Opcode = AArch64ISD::CSINC;
4880
4881 if (TrueVal > FalseVal) {
4882 Swap = true;
4883 }
4884 }
4885
4886 // Swap TVal and FVal if necessary.
4887 if (Swap) {
4888 std::swap(TVal, FVal);
4889 std::swap(CTVal, CFVal);
4890 CC = ISD::getSetCCInverse(CC, true);
4891 }
4892
4893 if (Opcode != AArch64ISD::CSEL) {
4894 // Drop FVal since we can get its value by simply inverting/negating
4895 // TVal.
4896 FVal = TVal;
4897 }
4898 }
4899
Chad Rosier58f505b2016-08-26 18:05:50 +00004900 // Avoid materializing a constant when possible by reusing a known value in
4901 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004902 // is one, zero or negative one in the case of a CSEL. We can always
4903 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4904 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004905 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4906 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4907 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4908 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4909 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4910 // "a != C ? x : a" to avoid materializing C.
4911 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4912 TVal = LHS;
4913 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4914 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004915 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4916 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4917 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4918 // avoid materializing C.
4919 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4920 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4921 Opcode = AArch64ISD::CSINV;
4922 TVal = LHS;
4923 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4924 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004925 }
4926
Tim Northover3b0846e2014-05-24 12:50:23 +00004927 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004928 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004929 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004930 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4931 }
4932
4933 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004934 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4935 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004936 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004937 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004938 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004939
4940 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4941 // clean. Some of them require two CSELs to implement.
4942 AArch64CC::CondCode CC1, CC2;
4943 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004944
4945 if (DAG.getTarget().Options.UnsafeFPMath) {
4946 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4947 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4948 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4949 if (RHSVal && RHSVal->isZero()) {
4950 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4951 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4952
4953 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004954 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004955 TVal = LHS;
4956 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004957 CFVal && CFVal->isZero() &&
4958 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004959 FVal = LHS;
4960 }
4961 }
4962
4963 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004964 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004965 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4966
4967 // If we need a second CSEL, emit it, using the output of the first as the
4968 // RHS. We're effectively OR'ing the two CC's together.
4969 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004970 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004971 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4972 }
4973
4974 // Otherwise, return the output of the first CSEL.
4975 return CS1;
4976}
4977
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004978SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4979 SelectionDAG &DAG) const {
4980 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4981 SDValue LHS = Op.getOperand(0);
4982 SDValue RHS = Op.getOperand(1);
4983 SDValue TVal = Op.getOperand(2);
4984 SDValue FVal = Op.getOperand(3);
4985 SDLoc DL(Op);
4986 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4987}
4988
4989SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4990 SelectionDAG &DAG) const {
4991 SDValue CCVal = Op->getOperand(0);
4992 SDValue TVal = Op->getOperand(1);
4993 SDValue FVal = Op->getOperand(2);
4994 SDLoc DL(Op);
4995
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004996 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4997 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004998 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004999 // Only lower legal XALUO ops.
5000 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5001 return SDValue();
5002
5003 AArch64CC::CondCode OFCC;
5004 SDValue Value, Overflow;
5005 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005006 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005007
5008 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5009 CCVal, Overflow);
5010 }
5011
5012 // Lower it the same way as we would lower a SELECT_CC node.
5013 ISD::CondCode CC;
5014 SDValue LHS, RHS;
5015 if (CCVal.getOpcode() == ISD::SETCC) {
5016 LHS = CCVal.getOperand(0);
5017 RHS = CCVal.getOperand(1);
5018 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5019 } else {
5020 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005021 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005022 CC = ISD::SETNE;
5023 }
5024 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5025}
5026
Tim Northover3b0846e2014-05-24 12:50:23 +00005027SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5028 SelectionDAG &DAG) const {
5029 // Jump table entries as PC relative offsets. No additional tweaking
5030 // is necessary here. Just get the address of the jump table.
5031 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005032
5033 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5034 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005035 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005036 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5037 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005038 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005039 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005040}
5041
Tim Northover1c353412018-10-24 20:19:09 +00005042SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5043 SelectionDAG &DAG) const {
5044 // Jump table entries as PC relative offsets. No additional tweaking
5045 // is necessary here. Just get the address of the jump table.
5046 SDLoc DL(Op);
5047 SDValue JT = Op.getOperand(1);
5048 SDValue Entry = Op.getOperand(2);
5049 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5050
5051 SDNode *Dest =
5052 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5053 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5054 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5055 SDValue(Dest, 0));
5056}
5057
Tim Northover3b0846e2014-05-24 12:50:23 +00005058SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5059 SelectionDAG &DAG) const {
5060 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005061
5062 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5063 // Use the GOT for the large code model on iOS.
5064 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005065 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005066 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005067 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005068 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5069 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005070 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005071 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005072 }
5073}
5074
5075SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5076 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005077 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005078 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5079 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005080 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005081 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5082 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005083 }
David Green9dd1d452018-08-22 11:31:39 +00005084 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005085}
5086
5087SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5088 SelectionDAG &DAG) const {
5089 AArch64FunctionInfo *FuncInfo =
5090 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5091
5092 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005093 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5094 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005095 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5096 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005097 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005098}
5099
Martin Storsjo68266fa2017-07-13 17:03:12 +00005100SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5101 SelectionDAG &DAG) const {
5102 AArch64FunctionInfo *FuncInfo =
5103 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5104
5105 SDLoc DL(Op);
5106 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5107 ? FuncInfo->getVarArgsGPRIndex()
5108 : FuncInfo->getVarArgsStackIndex(),
5109 getPointerTy(DAG.getDataLayout()));
5110 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5111 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5112 MachinePointerInfo(SV));
5113}
5114
Tim Northover3b0846e2014-05-24 12:50:23 +00005115SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5116 SelectionDAG &DAG) const {
5117 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5118 // Standard, section B.3.
5119 MachineFunction &MF = DAG.getMachineFunction();
5120 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005121 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005122 SDLoc DL(Op);
5123
5124 SDValue Chain = Op.getOperand(0);
5125 SDValue VAList = Op.getOperand(1);
5126 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5127 SmallVector<SDValue, 4> MemOps;
5128
5129 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005130 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005131 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005132 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005133
5134 // void *__gr_top at offset 8
5135 int GPRSize = FuncInfo->getVarArgsGPRSize();
5136 if (GPRSize > 0) {
5137 SDValue GRTop, GRTopAddr;
5138
Mehdi Amini44ede332015-07-09 02:09:04 +00005139 GRTopAddr =
5140 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005141
Mehdi Amini44ede332015-07-09 02:09:04 +00005142 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5143 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5144 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005145
5146 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005147 MachinePointerInfo(SV, 8),
5148 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005149 }
5150
5151 // void *__vr_top at offset 16
5152 int FPRSize = FuncInfo->getVarArgsFPRSize();
5153 if (FPRSize > 0) {
5154 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005155 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5156 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005157
Mehdi Amini44ede332015-07-09 02:09:04 +00005158 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5159 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5160 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005161
5162 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005163 MachinePointerInfo(SV, 16),
5164 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005165 }
5166
5167 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005168 SDValue GROffsAddr =
5169 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005170 MemOps.push_back(DAG.getStore(
5171 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5172 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005173
5174 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005175 SDValue VROffsAddr =
5176 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005177 MemOps.push_back(DAG.getStore(
5178 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5179 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005180
5181 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5182}
5183
5184SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5185 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005186 MachineFunction &MF = DAG.getMachineFunction();
5187
Matthias Braunf1caa282017-12-15 22:22:58 +00005188 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005189 return LowerWin64_VASTART(Op, DAG);
5190 else if (Subtarget->isTargetDarwin())
5191 return LowerDarwin_VASTART(Op, DAG);
5192 else
5193 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005194}
5195
5196SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5197 SelectionDAG &DAG) const {
5198 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5199 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005200 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005201 unsigned VaListSize =
5202 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005203 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5204 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5205
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005206 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5207 Op.getOperand(2),
5208 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005209 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005210 MachinePointerInfo(SrcSV));
5211}
5212
5213SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5214 assert(Subtarget->isTargetDarwin() &&
5215 "automatic va_arg instruction only works on Darwin");
5216
5217 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5218 EVT VT = Op.getValueType();
5219 SDLoc DL(Op);
5220 SDValue Chain = Op.getOperand(0);
5221 SDValue Addr = Op.getOperand(1);
5222 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005223 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005224
Justin Lebar9c375812016-07-15 18:27:10 +00005225 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005226 Chain = VAList.getValue(1);
5227
5228 if (Align > 8) {
5229 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005230 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5231 DAG.getConstant(Align - 1, DL, PtrVT));
5232 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5233 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005234 }
5235
5236 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005237 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005238
5239 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5240 // up to 64 bits. At the very least, we have to increase the striding of the
5241 // vaargs list to match this, and for FP values we need to introduce
5242 // FP_ROUND nodes as well.
5243 if (VT.isInteger() && !VT.isVector())
5244 ArgSize = 8;
5245 bool NeedFPTrunc = false;
5246 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5247 ArgSize = 8;
5248 NeedFPTrunc = true;
5249 }
5250
5251 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005252 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5253 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005254 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005255 SDValue APStore =
5256 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005257
5258 // Load the actual argument out of the pointer VAList
5259 if (NeedFPTrunc) {
5260 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005261 SDValue WideFP =
5262 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005263 // Round the value down to an f32.
5264 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005265 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005266 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5267 // Merge the rounded value with the chain output of the load.
5268 return DAG.getMergeValues(Ops, DL);
5269 }
5270
Justin Lebar9c375812016-07-15 18:27:10 +00005271 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005272}
5273
5274SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5275 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005276 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5277 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005278
5279 EVT VT = Op.getValueType();
5280 SDLoc DL(Op);
5281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5282 SDValue FrameAddr =
5283 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5284 while (Depth--)
5285 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005286 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005287 return FrameAddr;
5288}
5289
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005290SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5291 SelectionDAG &DAG) const {
5292 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5293
5294 EVT VT = getPointerTy(DAG.getDataLayout());
5295 SDLoc DL(Op);
5296 int FI = MFI.CreateFixedObject(4, 0, false);
5297 return DAG.getFrameIndex(FI, VT);
5298}
5299
Petr Hosekfcbec022019-02-13 17:28:47 +00005300#define GET_REGISTER_MATCHER
5301#include "AArch64GenAsmMatcher.inc"
5302
Tim Northover3b0846e2014-05-24 12:50:23 +00005303// FIXME? Maybe this could be a TableGen attribute on some registers and
5304// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005305unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5306 SelectionDAG &DAG) const {
Petr Hosekfcbec022019-02-13 17:28:47 +00005307 unsigned Reg = MatchRegisterName(RegName);
5308 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5309 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5310 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5311 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5312 Reg = 0;
5313 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005314 if (Reg)
5315 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005316 report_fatal_error(Twine("Invalid register name \""
5317 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005318}
5319
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005320SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5321 SelectionDAG &DAG) const {
5322 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5323
5324 EVT VT = Op.getValueType();
5325 SDLoc DL(Op);
5326
5327 SDValue FrameAddr =
5328 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5329 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5330
5331 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5332}
5333
Tim Northover3b0846e2014-05-24 12:50:23 +00005334SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5335 SelectionDAG &DAG) const {
5336 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005337 MachineFrameInfo &MFI = MF.getFrameInfo();
5338 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005339
5340 EVT VT = Op.getValueType();
5341 SDLoc DL(Op);
5342 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5343 if (Depth) {
5344 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005345 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005346 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5347 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005348 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005349 }
5350
5351 // Return LR, which contains the return address. Mark it an implicit live-in.
5352 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5353 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5354}
5355
5356/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5357/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5358SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5359 SelectionDAG &DAG) const {
5360 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5361 EVT VT = Op.getValueType();
5362 unsigned VTBits = VT.getSizeInBits();
5363 SDLoc dl(Op);
5364 SDValue ShOpLo = Op.getOperand(0);
5365 SDValue ShOpHi = Op.getOperand(1);
5366 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005367 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5368
5369 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5370
5371 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005372 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005373 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5374
5375 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5376 // is "undef". We wanted 0, so CSEL it directly.
5377 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5378 ISD::SETEQ, dl, DAG);
5379 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5380 HiBitsForLo =
5381 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5382 HiBitsForLo, CCVal, Cmp);
5383
Tim Northover3b0846e2014-05-24 12:50:23 +00005384 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005385 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005386
Tim Northoverf3be9d52015-12-02 00:33:54 +00005387 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5388 SDValue LoForNormalShift =
5389 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005390
Tim Northoverf3be9d52015-12-02 00:33:54 +00005391 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5392 dl, DAG);
5393 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5394 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5395 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5396 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005397
5398 // AArch64 shifts larger than the register width are wrapped rather than
5399 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005400 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5401 SDValue HiForBigShift =
5402 Opc == ISD::SRA
5403 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5404 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5405 : DAG.getConstant(0, dl, VT);
5406 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5407 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005408
5409 SDValue Ops[2] = { Lo, Hi };
5410 return DAG.getMergeValues(Ops, dl);
5411}
5412
5413/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5414/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5415SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005416 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005417 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5418 EVT VT = Op.getValueType();
5419 unsigned VTBits = VT.getSizeInBits();
5420 SDLoc dl(Op);
5421 SDValue ShOpLo = Op.getOperand(0);
5422 SDValue ShOpHi = Op.getOperand(1);
5423 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005424
5425 assert(Op.getOpcode() == ISD::SHL_PARTS);
5426 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005427 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005428 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5429
5430 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5431 // is "undef". We wanted 0, so CSEL it directly.
5432 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5433 ISD::SETEQ, dl, DAG);
5434 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5435 LoBitsForHi =
5436 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5437 LoBitsForHi, CCVal, Cmp);
5438
Tim Northover3b0846e2014-05-24 12:50:23 +00005439 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005440 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005441 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5442 SDValue HiForNormalShift =
5443 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005444
Tim Northoverf3be9d52015-12-02 00:33:54 +00005445 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005446
Tim Northoverf3be9d52015-12-02 00:33:54 +00005447 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5448 dl, DAG);
5449 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5450 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5451 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005452
5453 // AArch64 shifts of larger than register sizes are wrapped rather than
5454 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005455 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5456 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5457 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5458 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005459
5460 SDValue Ops[2] = { Lo, Hi };
5461 return DAG.getMergeValues(Ops, dl);
5462}
5463
5464bool AArch64TargetLowering::isOffsetFoldingLegal(
5465 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005466 // Offsets are folded in the DAG combine rather than here so that we can
5467 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005468 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005469}
5470
Adhemerval Zanella664c1ef2019-03-18 18:40:07 +00005471bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5472 bool OptForSize) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005473 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005474 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5475 // 16-bit case when target has full fp16 support.
5476 // FIXME: We should be able to handle f128 as well with a clever lowering.
5477 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005478 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005479 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005480 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005481 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005482 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005483 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5484 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5485 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005486
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005487 // If we can not materialize in immediate field for fmov, check if the
5488 // value can be encoded as the immediate operand of a logical instruction.
5489 // The immediate value will be created with either MOVZ, MOVN, or ORR.
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +00005490 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5491 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5492 // however the mov+fmov sequence is always better because of the reduced
5493 // cache pressure. The timings are still the same if you consider
5494 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5495 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5496 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5497 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5498 Insn);
5499 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5500 IsLegal = Insn.size() <= Limit;
5501 }
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005502
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005503 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5504 << " imm value: "; Imm.dump(););
5505 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005506}
5507
5508//===----------------------------------------------------------------------===//
5509// AArch64 Optimization Hooks
5510//===----------------------------------------------------------------------===//
5511
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005512static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5513 SDValue Operand, SelectionDAG &DAG,
5514 int &ExtraSteps) {
5515 EVT VT = Operand.getValueType();
5516 if (ST->hasNEON() &&
5517 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5518 VT == MVT::f32 || VT == MVT::v1f32 ||
5519 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5520 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5521 // For the reciprocal estimates, convergence is quadratic, so the number
5522 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5523 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5524 // the result for float (23 mantissa bits) is 2 and for double (52
5525 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005526 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005527
5528 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5529 }
5530
5531 return SDValue();
5532}
5533
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005534SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5535 SelectionDAG &DAG, int Enabled,
5536 int &ExtraSteps,
5537 bool &UseOneConst,
5538 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005539 if (Enabled == ReciprocalEstimate::Enabled ||
5540 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5541 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5542 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005543 SDLoc DL(Operand);
5544 EVT VT = Operand.getValueType();
5545
5546 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005547 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005548
5549 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5550 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5551 for (int i = ExtraSteps; i > 0; --i) {
5552 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005553 Flags);
5554 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5555 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005556 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005557 if (!Reciprocal) {
5558 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5559 VT);
5560 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5561 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5562
Amara Emersond28f0cd42017-05-01 15:17:51 +00005563 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005564 // Correct the result if the operand is 0.0.
5565 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5566 VT, Eq, Operand, Estimate);
5567 }
5568
5569 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005570 return Estimate;
5571 }
5572
5573 return SDValue();
5574}
5575
5576SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5577 SelectionDAG &DAG, int Enabled,
5578 int &ExtraSteps) const {
5579 if (Enabled == ReciprocalEstimate::Enabled)
5580 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005581 DAG, ExtraSteps)) {
5582 SDLoc DL(Operand);
5583 EVT VT = Operand.getValueType();
5584
5585 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005586 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005587
5588 // Newton reciprocal iteration: E * (2 - X * E)
5589 // AArch64 reciprocal iteration instruction: (2 - M * N)
5590 for (int i = ExtraSteps; i > 0; --i) {
5591 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005592 Estimate, Flags);
5593 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005594 }
5595
5596 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005597 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005598 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005599
5600 return SDValue();
5601}
5602
Tim Northover3b0846e2014-05-24 12:50:23 +00005603//===----------------------------------------------------------------------===//
5604// AArch64 Inline Assembly Support
5605//===----------------------------------------------------------------------===//
5606
5607// Table of Constraints
5608// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005609// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005610//
5611// r - A general register
5612// w - An FP/SIMD register of some size in the range v0-v31
5613// x - An FP/SIMD register of some size in the range v0-v15
5614// I - Constant that can be used with an ADD instruction
5615// J - Constant that can be used with a SUB instruction
5616// K - Constant that can be used with a 32-bit logical instruction
5617// L - Constant that can be used with a 64-bit logical instruction
5618// M - Constant that can be used as a 32-bit MOV immediate
5619// N - Constant that can be used as a 64-bit MOV immediate
5620// Q - A memory reference with base register and no offset
5621// S - A symbolic address
5622// Y - Floating point constant zero
5623// Z - Integer constant zero
5624//
5625// Note that general register operands will be output using their 64-bit x
5626// register name, whatever the size of the variable, unless the asm operand
5627// is prefixed by the %w modifier. Floating-point and SIMD register operands
5628// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5629// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005630const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5631 // At this point, we have to lower this constraint to something else, so we
5632 // lower it to an "r" or "w". However, by doing this we will force the result
5633 // to be in register, while the X constraint is much more permissive.
5634 //
5635 // Although we are correct (we are free to emit anything, without
5636 // constraints), we might break use cases that would expect us to be more
5637 // efficient and emit something else.
5638 if (!Subtarget->hasFPARMv8())
5639 return "r";
5640
5641 if (ConstraintVT.isFloatingPoint())
5642 return "w";
5643
5644 if (ConstraintVT.isVector() &&
5645 (ConstraintVT.getSizeInBits() == 64 ||
5646 ConstraintVT.getSizeInBits() == 128))
5647 return "w";
5648
5649 return "r";
5650}
Tim Northover3b0846e2014-05-24 12:50:23 +00005651
5652/// getConstraintType - Given a constraint letter, return the type of
5653/// constraint it is for this target.
5654AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005655AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005656 if (Constraint.size() == 1) {
5657 switch (Constraint[0]) {
5658 default:
5659 break;
5660 case 'z':
5661 return C_Other;
5662 case 'x':
5663 case 'w':
5664 return C_RegisterClass;
5665 // An address with a single base register. Due to the way we
5666 // currently handle addresses it is the same as 'r'.
5667 case 'Q':
5668 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005669 case 'S': // A symbolic address
5670 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005671 }
5672 }
5673 return TargetLowering::getConstraintType(Constraint);
5674}
5675
5676/// Examine constraint type and operand type and determine a weight value.
5677/// This object must already have been set up with the operand type
5678/// and the current alternative constraint selected.
5679TargetLowering::ConstraintWeight
5680AArch64TargetLowering::getSingleConstraintMatchWeight(
5681 AsmOperandInfo &info, const char *constraint) const {
5682 ConstraintWeight weight = CW_Invalid;
5683 Value *CallOperandVal = info.CallOperandVal;
5684 // If we don't have a value, we can't do a match,
5685 // but allow it at the lowest weight.
5686 if (!CallOperandVal)
5687 return CW_Default;
5688 Type *type = CallOperandVal->getType();
5689 // Look at the constraint type.
5690 switch (*constraint) {
5691 default:
5692 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5693 break;
5694 case 'x':
5695 case 'w':
5696 if (type->isFloatingPointTy() || type->isVectorTy())
5697 weight = CW_Register;
5698 break;
5699 case 'z':
5700 weight = CW_Constant;
5701 break;
5702 }
5703 return weight;
5704}
5705
5706std::pair<unsigned, const TargetRegisterClass *>
5707AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005708 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005709 if (Constraint.size() == 1) {
5710 switch (Constraint[0]) {
5711 case 'r':
5712 if (VT.getSizeInBits() == 64)
5713 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5714 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5715 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005716 if (!Subtarget->hasFPARMv8())
5717 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005718 if (VT.getSizeInBits() == 16)
5719 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005720 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005721 return std::make_pair(0U, &AArch64::FPR32RegClass);
5722 if (VT.getSizeInBits() == 64)
5723 return std::make_pair(0U, &AArch64::FPR64RegClass);
5724 if (VT.getSizeInBits() == 128)
5725 return std::make_pair(0U, &AArch64::FPR128RegClass);
5726 break;
5727 // The instructions that this constraint is designed for can
5728 // only take 128-bit registers so just use that regclass.
5729 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005730 if (!Subtarget->hasFPARMv8())
5731 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005732 if (VT.getSizeInBits() == 128)
5733 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5734 break;
5735 }
5736 }
5737 if (StringRef("{cc}").equals_lower(Constraint))
5738 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5739
5740 // Use the default implementation in TargetLowering to convert the register
5741 // constraint into a member of a register class.
5742 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005743 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005744
5745 // Not found as a standard register?
5746 if (!Res.second) {
5747 unsigned Size = Constraint.size();
5748 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5749 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005750 int RegNo;
5751 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5752 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005753 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005754 // By default we'll emit v0-v31 for this unless there's a modifier where
5755 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005756 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5757 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5758 Res.second = &AArch64::FPR64RegClass;
5759 } else {
5760 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5761 Res.second = &AArch64::FPR128RegClass;
5762 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005763 }
5764 }
5765 }
5766
Eli Friedman071203b2018-08-24 19:12:13 +00005767 if (Res.second && !Subtarget->hasFPARMv8() &&
5768 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5769 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5770 return std::make_pair(0U, nullptr);
5771
Tim Northover3b0846e2014-05-24 12:50:23 +00005772 return Res;
5773}
5774
5775/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5776/// vector. If it is invalid, don't add anything to Ops.
5777void AArch64TargetLowering::LowerAsmOperandForConstraint(
5778 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5779 SelectionDAG &DAG) const {
5780 SDValue Result;
5781
5782 // Currently only support length 1 constraints.
5783 if (Constraint.length() != 1)
5784 return;
5785
5786 char ConstraintLetter = Constraint[0];
5787 switch (ConstraintLetter) {
5788 default:
5789 break;
5790
5791 // This set of constraints deal with valid constants for various instructions.
5792 // Validate and return a target constant for them if we can.
5793 case 'z': {
5794 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005795 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005796 return;
5797
5798 if (Op.getValueType() == MVT::i64)
5799 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5800 else
5801 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5802 break;
5803 }
Peter Smithc8117582018-05-16 09:33:25 +00005804 case 'S': {
5805 // An absolute symbolic address or label reference.
5806 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5807 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5808 GA->getValueType(0));
5809 } else if (const BlockAddressSDNode *BA =
5810 dyn_cast<BlockAddressSDNode>(Op)) {
5811 Result =
5812 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5813 } else if (const ExternalSymbolSDNode *ES =
5814 dyn_cast<ExternalSymbolSDNode>(Op)) {
5815 Result =
5816 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5817 } else
5818 return;
5819 break;
5820 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005821
5822 case 'I':
5823 case 'J':
5824 case 'K':
5825 case 'L':
5826 case 'M':
5827 case 'N':
5828 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5829 if (!C)
5830 return;
5831
5832 // Grab the value and do some validation.
5833 uint64_t CVal = C->getZExtValue();
5834 switch (ConstraintLetter) {
5835 // The I constraint applies only to simple ADD or SUB immediate operands:
5836 // i.e. 0 to 4095 with optional shift by 12
5837 // The J constraint applies only to ADD or SUB immediates that would be
5838 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5839 // instruction [or vice versa], in other words -1 to -4095 with optional
5840 // left shift by 12.
5841 case 'I':
5842 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5843 break;
5844 return;
5845 case 'J': {
5846 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005847 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5848 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005849 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005850 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005851 return;
5852 }
5853 // The K and L constraints apply *only* to logical immediates, including
5854 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5855 // been removed and MOV should be used). So these constraints have to
5856 // distinguish between bit patterns that are valid 32-bit or 64-bit
5857 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5858 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5859 // versa.
5860 case 'K':
5861 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5862 break;
5863 return;
5864 case 'L':
5865 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5866 break;
5867 return;
5868 // The M and N constraints are a superset of K and L respectively, for use
5869 // with the MOV (immediate) alias. As well as the logical immediates they
5870 // also match 32 or 64-bit immediates that can be loaded either using a
5871 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5872 // (M) or 64-bit 0x1234000000000000 (N) etc.
5873 // As a note some of this code is liberally stolen from the asm parser.
5874 case 'M': {
5875 if (!isUInt<32>(CVal))
5876 return;
5877 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5878 break;
5879 if ((CVal & 0xFFFF) == CVal)
5880 break;
5881 if ((CVal & 0xFFFF0000ULL) == CVal)
5882 break;
5883 uint64_t NCVal = ~(uint32_t)CVal;
5884 if ((NCVal & 0xFFFFULL) == NCVal)
5885 break;
5886 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5887 break;
5888 return;
5889 }
5890 case 'N': {
5891 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5892 break;
5893 if ((CVal & 0xFFFFULL) == CVal)
5894 break;
5895 if ((CVal & 0xFFFF0000ULL) == CVal)
5896 break;
5897 if ((CVal & 0xFFFF00000000ULL) == CVal)
5898 break;
5899 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5900 break;
5901 uint64_t NCVal = ~CVal;
5902 if ((NCVal & 0xFFFFULL) == NCVal)
5903 break;
5904 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5905 break;
5906 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5907 break;
5908 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5909 break;
5910 return;
5911 }
5912 default:
5913 return;
5914 }
5915
5916 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005917 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005918 break;
5919 }
5920
5921 if (Result.getNode()) {
5922 Ops.push_back(Result);
5923 return;
5924 }
5925
5926 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5927}
5928
5929//===----------------------------------------------------------------------===//
5930// AArch64 Advanced SIMD Support
5931//===----------------------------------------------------------------------===//
5932
5933/// WidenVector - Given a value in the V64 register class, produce the
5934/// equivalent value in the V128 register class.
5935static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5936 EVT VT = V64Reg.getValueType();
5937 unsigned NarrowSize = VT.getVectorNumElements();
5938 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5939 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5940 SDLoc DL(V64Reg);
5941
5942 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005943 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005944}
5945
5946/// getExtFactor - Determine the adjustment factor for the position when
5947/// generating an "extract from vector registers" instruction.
5948static unsigned getExtFactor(SDValue &V) {
5949 EVT EltType = V.getValueType().getVectorElementType();
5950 return EltType.getSizeInBits() / 8;
5951}
5952
5953/// NarrowVector - Given a value in the V128 register class, produce the
5954/// equivalent value in the V64 register class.
5955static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5956 EVT VT = V128Reg.getValueType();
5957 unsigned WideSize = VT.getVectorNumElements();
5958 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5959 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5960 SDLoc DL(V128Reg);
5961
5962 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5963}
5964
5965// Gather data to see if the operation can be modelled as a
5966// shuffle in combination with VEXTs.
5967SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5968 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005969 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005970 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005971 SDLoc dl(Op);
5972 EVT VT = Op.getValueType();
5973 unsigned NumElts = VT.getVectorNumElements();
5974
Tim Northover7324e842014-07-24 15:39:55 +00005975 struct ShuffleSourceInfo {
5976 SDValue Vec;
5977 unsigned MinElt;
5978 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005979
Tim Northover7324e842014-07-24 15:39:55 +00005980 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5981 // be compatible with the shuffle we intend to construct. As a result
5982 // ShuffleVec will be some sliding window into the original Vec.
5983 SDValue ShuffleVec;
5984
5985 // Code should guarantee that element i in Vec starts at element "WindowBase
5986 // + i * WindowScale in ShuffleVec".
5987 int WindowBase;
5988 int WindowScale;
5989
Tim Northover7324e842014-07-24 15:39:55 +00005990 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005991 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5992 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5993
5994 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005995 };
5996
5997 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5998 // node.
5999 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00006000 for (unsigned i = 0; i < NumElts; ++i) {
6001 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006002 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006003 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00006004 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6005 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006006 LLVM_DEBUG(
6007 dbgs() << "Reshuffle failed: "
6008 "a shuffle can only come from building a vector from "
6009 "various elements of other vectors, provided their "
6010 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006011 return SDValue();
6012 }
6013
Tim Northover7324e842014-07-24 15:39:55 +00006014 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00006015 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00006016 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00006017 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00006018 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00006019
Tim Northover7324e842014-07-24 15:39:55 +00006020 // Update the minimum and maximum lane number seen.
6021 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6022 Source->MinElt = std::min(Source->MinElt, EltNo);
6023 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00006024 }
6025
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006026 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006027 LLVM_DEBUG(
6028 dbgs() << "Reshuffle failed: currently only do something sane when at "
6029 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006030 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006031 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006032
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006033 // Find out the smallest element size among result and two sources, and use
6034 // it as element size to build the shuffle_vector.
6035 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00006036 for (auto &Source : Sources) {
6037 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006038 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6039 SmallestEltTy = SrcEltTy;
6040 }
6041 }
6042 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006043 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006044 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6045 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00006046
Tim Northover7324e842014-07-24 15:39:55 +00006047 // If the source vector is too wide or too narrow, we may nevertheless be able
6048 // to construct a compatible shuffle either by concatenating it with UNDEF or
6049 // extracting a suitable range of elements.
6050 for (auto &Src : Sources) {
6051 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006052
Tim Northover7324e842014-07-24 15:39:55 +00006053 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00006054 continue;
Tim Northover7324e842014-07-24 15:39:55 +00006055
6056 // This stage of the search produces a source with the same element type as
6057 // the original, but with a total width matching the BUILD_VECTOR output.
6058 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00006059 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6060 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00006061
6062 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6063 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006064 // We can pad out the smaller vector for free, so if it's part of a
6065 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00006066 Src.ShuffleVec =
6067 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6068 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00006069 continue;
6070 }
6071
Tim Northover7324e842014-07-24 15:39:55 +00006072 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006073
James Molloyf497d552014-10-17 17:06:31 +00006074 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006075 LLVM_DEBUG(
6076 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006077 return SDValue();
6078 }
6079
James Molloyf497d552014-10-17 17:06:31 +00006080 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006081 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00006082 Src.ShuffleVec =
6083 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006084 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00006085 Src.WindowBase = -NumSrcElts;
6086 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006087 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006088 Src.ShuffleVec =
6089 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006090 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006091 } else {
6092 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006093 SDValue VEXTSrc1 =
6094 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006095 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006096 SDValue VEXTSrc2 =
6097 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006098 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006099 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6100
6101 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006102 VEXTSrc2,
6103 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006104 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006105 }
6106 }
6107
Tim Northover7324e842014-07-24 15:39:55 +00006108 // Another possible incompatibility occurs from the vector element types. We
6109 // can fix this by bitcasting the source vectors to the same type we intend
6110 // for the shuffle.
6111 for (auto &Src : Sources) {
6112 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6113 if (SrcEltTy == SmallestEltTy)
6114 continue;
6115 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6116 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6117 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6118 Src.WindowBase *= Src.WindowScale;
6119 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006120
Tim Northover7324e842014-07-24 15:39:55 +00006121 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006122 LLVM_DEBUG(for (auto Src
6123 : Sources)
6124 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006125
6126 // The stars all align, our next step is to produce the mask for the shuffle.
6127 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006128 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006129 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006130 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006131 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006132 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006133
David Majnemer0d955d02016-08-11 22:21:41 +00006134 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006135 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6136
6137 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6138 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6139 // segment.
6140 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006141 int BitsDefined =
6142 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006143 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6144
6145 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6146 // starting at the appropriate offset.
6147 int *LaneMask = &Mask[i * ResMultiplier];
6148
6149 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6150 ExtractBase += NumElts * (Src - Sources.begin());
6151 for (int j = 0; j < LanesDefined; ++j)
6152 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006153 }
6154
6155 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006156 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006157 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006158 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006159 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006160
Tim Northover7324e842014-07-24 15:39:55 +00006161 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6162 for (unsigned i = 0; i < Sources.size(); ++i)
6163 ShuffleOps[i] = Sources[i].ShuffleVec;
6164
6165 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006166 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006167 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6168
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006169 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6170 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006171
6172 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006173}
6174
6175// check if an EXT instruction can handle the shuffle mask when the
6176// vector sources of the shuffle are the same.
6177static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6178 unsigned NumElts = VT.getVectorNumElements();
6179
6180 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6181 if (M[0] < 0)
6182 return false;
6183
6184 Imm = M[0];
6185
6186 // If this is a VEXT shuffle, the immediate value is the index of the first
6187 // element. The other shuffle indices must be the successive elements after
6188 // the first one.
6189 unsigned ExpectedElt = Imm;
6190 for (unsigned i = 1; i < NumElts; ++i) {
6191 // Increment the expected index. If it wraps around, just follow it
6192 // back to index zero and keep going.
6193 ++ExpectedElt;
6194 if (ExpectedElt == NumElts)
6195 ExpectedElt = 0;
6196
6197 if (M[i] < 0)
6198 continue; // ignore UNDEF indices
6199 if (ExpectedElt != static_cast<unsigned>(M[i]))
6200 return false;
6201 }
6202
6203 return true;
6204}
6205
6206// check if an EXT instruction can handle the shuffle mask when the
6207// vector sources of the shuffle are different.
6208static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6209 unsigned &Imm) {
6210 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006211 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006212
6213 // Benefit form APInt to handle overflow when calculating expected element.
6214 unsigned NumElts = VT.getVectorNumElements();
6215 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6216 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6217 // The following shuffle indices must be the successive elements after the
6218 // first real element.
6219 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6220 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6221 if (FirstWrongElt != M.end())
6222 return false;
6223
6224 // The index of an EXT is the first element if it is not UNDEF.
6225 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006226 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006227 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6228 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6229 // ExpectedElt is the last mask index plus 1.
6230 Imm = ExpectedElt.getZExtValue();
6231
6232 // There are two difference cases requiring to reverse input vectors.
6233 // For example, for vector <4 x i32> we have the following cases,
6234 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6235 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6236 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6237 // to reverse two input vectors.
6238 if (Imm < NumElts)
6239 ReverseEXT = true;
6240 else
6241 Imm -= NumElts;
6242
6243 return true;
6244}
6245
6246/// isREVMask - Check if a vector shuffle corresponds to a REV
6247/// instruction with the specified blocksize. (The order of the elements
6248/// within each block of the vector is reversed.)
6249static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6250 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6251 "Only possible block sizes for REV are: 16, 32, 64");
6252
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006253 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006254 if (EltSz == 64)
6255 return false;
6256
6257 unsigned NumElts = VT.getVectorNumElements();
6258 unsigned BlockElts = M[0] + 1;
6259 // If the first shuffle index is UNDEF, be optimistic.
6260 if (M[0] < 0)
6261 BlockElts = BlockSize / EltSz;
6262
6263 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6264 return false;
6265
6266 for (unsigned i = 0; i < NumElts; ++i) {
6267 if (M[i] < 0)
6268 continue; // ignore UNDEF indices
6269 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6270 return false;
6271 }
6272
6273 return true;
6274}
6275
6276static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6277 unsigned NumElts = VT.getVectorNumElements();
6278 WhichResult = (M[0] == 0 ? 0 : 1);
6279 unsigned Idx = WhichResult * NumElts / 2;
6280 for (unsigned i = 0; i != NumElts; i += 2) {
6281 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6282 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6283 return false;
6284 Idx += 1;
6285 }
6286
6287 return true;
6288}
6289
6290static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6291 unsigned NumElts = VT.getVectorNumElements();
6292 WhichResult = (M[0] == 0 ? 0 : 1);
6293 for (unsigned i = 0; i != NumElts; ++i) {
6294 if (M[i] < 0)
6295 continue; // ignore UNDEF indices
6296 if ((unsigned)M[i] != 2 * i + WhichResult)
6297 return false;
6298 }
6299
6300 return true;
6301}
6302
6303static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6304 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006305 if (NumElts % 2 != 0)
6306 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006307 WhichResult = (M[0] == 0 ? 0 : 1);
6308 for (unsigned i = 0; i < NumElts; i += 2) {
6309 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6310 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6311 return false;
6312 }
6313 return true;
6314}
6315
6316/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6317/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6318/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6319static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6320 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006321 if (NumElts % 2 != 0)
6322 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006323 WhichResult = (M[0] == 0 ? 0 : 1);
6324 unsigned Idx = WhichResult * NumElts / 2;
6325 for (unsigned i = 0; i != NumElts; i += 2) {
6326 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6327 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6328 return false;
6329 Idx += 1;
6330 }
6331
6332 return true;
6333}
6334
6335/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6336/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6337/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6338static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6339 unsigned Half = VT.getVectorNumElements() / 2;
6340 WhichResult = (M[0] == 0 ? 0 : 1);
6341 for (unsigned j = 0; j != 2; ++j) {
6342 unsigned Idx = WhichResult;
6343 for (unsigned i = 0; i != Half; ++i) {
6344 int MIdx = M[i + j * Half];
6345 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6346 return false;
6347 Idx += 2;
6348 }
6349 }
6350
6351 return true;
6352}
6353
6354/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6355/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6356/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6357static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6358 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006359 if (NumElts % 2 != 0)
6360 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006361 WhichResult = (M[0] == 0 ? 0 : 1);
6362 for (unsigned i = 0; i < NumElts; i += 2) {
6363 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6364 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6365 return false;
6366 }
6367 return true;
6368}
6369
6370static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6371 bool &DstIsLeft, int &Anomaly) {
6372 if (M.size() != static_cast<size_t>(NumInputElements))
6373 return false;
6374
6375 int NumLHSMatch = 0, NumRHSMatch = 0;
6376 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6377
6378 for (int i = 0; i < NumInputElements; ++i) {
6379 if (M[i] == -1) {
6380 ++NumLHSMatch;
6381 ++NumRHSMatch;
6382 continue;
6383 }
6384
6385 if (M[i] == i)
6386 ++NumLHSMatch;
6387 else
6388 LastLHSMismatch = i;
6389
6390 if (M[i] == i + NumInputElements)
6391 ++NumRHSMatch;
6392 else
6393 LastRHSMismatch = i;
6394 }
6395
6396 if (NumLHSMatch == NumInputElements - 1) {
6397 DstIsLeft = true;
6398 Anomaly = LastLHSMismatch;
6399 return true;
6400 } else if (NumRHSMatch == NumInputElements - 1) {
6401 DstIsLeft = false;
6402 Anomaly = LastRHSMismatch;
6403 return true;
6404 }
6405
6406 return false;
6407}
6408
6409static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6410 if (VT.getSizeInBits() != 128)
6411 return false;
6412
6413 unsigned NumElts = VT.getVectorNumElements();
6414
6415 for (int I = 0, E = NumElts / 2; I != E; I++) {
6416 if (Mask[I] != I)
6417 return false;
6418 }
6419
6420 int Offset = NumElts / 2;
6421 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6422 if (Mask[I] != I + SplitLHS * Offset)
6423 return false;
6424 }
6425
6426 return true;
6427}
6428
6429static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6430 SDLoc DL(Op);
6431 EVT VT = Op.getValueType();
6432 SDValue V0 = Op.getOperand(0);
6433 SDValue V1 = Op.getOperand(1);
6434 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6435
6436 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6437 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6438 return SDValue();
6439
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006440 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006441
6442 if (!isConcatMask(Mask, VT, SplitV0))
6443 return SDValue();
6444
6445 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6446 VT.getVectorNumElements() / 2);
6447 if (SplitV0) {
6448 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006449 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006450 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006451 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006452 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006453 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006454 }
6455 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6456}
6457
6458/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6459/// the specified operations to build the shuffle.
6460static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6461 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006462 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006463 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6464 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6465 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6466
6467 enum {
6468 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6469 OP_VREV,
6470 OP_VDUP0,
6471 OP_VDUP1,
6472 OP_VDUP2,
6473 OP_VDUP3,
6474 OP_VEXT1,
6475 OP_VEXT2,
6476 OP_VEXT3,
6477 OP_VUZPL, // VUZP, left result
6478 OP_VUZPR, // VUZP, right result
6479 OP_VZIPL, // VZIP, left result
6480 OP_VZIPR, // VZIP, right result
6481 OP_VTRNL, // VTRN, left result
6482 OP_VTRNR // VTRN, right result
6483 };
6484
6485 if (OpNum == OP_COPY) {
6486 if (LHSID == (1 * 9 + 2) * 9 + 3)
6487 return LHS;
6488 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6489 return RHS;
6490 }
6491
6492 SDValue OpLHS, OpRHS;
6493 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6494 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6495 EVT VT = OpLHS.getValueType();
6496
6497 switch (OpNum) {
6498 default:
6499 llvm_unreachable("Unknown shuffle opcode!");
6500 case OP_VREV:
6501 // VREV divides the vector in half and swaps within the half.
6502 if (VT.getVectorElementType() == MVT::i32 ||
6503 VT.getVectorElementType() == MVT::f32)
6504 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6505 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006506 if (VT.getVectorElementType() == MVT::i16 ||
6507 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006508 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6509 // vrev <4 x i8> -> REV16
6510 assert(VT.getVectorElementType() == MVT::i8);
6511 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6512 case OP_VDUP0:
6513 case OP_VDUP1:
6514 case OP_VDUP2:
6515 case OP_VDUP3: {
6516 EVT EltTy = VT.getVectorElementType();
6517 unsigned Opcode;
6518 if (EltTy == MVT::i8)
6519 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006520 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006521 Opcode = AArch64ISD::DUPLANE16;
6522 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6523 Opcode = AArch64ISD::DUPLANE32;
6524 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6525 Opcode = AArch64ISD::DUPLANE64;
6526 else
6527 llvm_unreachable("Invalid vector element type?");
6528
6529 if (VT.getSizeInBits() == 64)
6530 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006531 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006532 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6533 }
6534 case OP_VEXT1:
6535 case OP_VEXT2:
6536 case OP_VEXT3: {
6537 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6538 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006539 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006540 }
6541 case OP_VUZPL:
6542 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6543 OpRHS);
6544 case OP_VUZPR:
6545 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6546 OpRHS);
6547 case OP_VZIPL:
6548 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6549 OpRHS);
6550 case OP_VZIPR:
6551 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6552 OpRHS);
6553 case OP_VTRNL:
6554 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6555 OpRHS);
6556 case OP_VTRNR:
6557 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6558 OpRHS);
6559 }
6560}
6561
6562static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6563 SelectionDAG &DAG) {
6564 // Check to see if we can use the TBL instruction.
6565 SDValue V1 = Op.getOperand(0);
6566 SDValue V2 = Op.getOperand(1);
6567 SDLoc DL(Op);
6568
6569 EVT EltVT = Op.getValueType().getVectorElementType();
6570 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6571
6572 SmallVector<SDValue, 8> TBLMask;
6573 for (int Val : ShuffleMask) {
6574 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6575 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006576 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006577 }
6578 }
6579
6580 MVT IndexVT = MVT::v8i8;
6581 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006582 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006583 IndexVT = MVT::v16i8;
6584 IndexLen = 16;
6585 }
6586
6587 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6588 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6589
6590 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006591 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006592 if (IndexLen == 8)
6593 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6594 Shuffle = DAG.getNode(
6595 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006596 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006597 DAG.getBuildVector(IndexVT, DL,
6598 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006599 } else {
6600 if (IndexLen == 8) {
6601 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6602 Shuffle = DAG.getNode(
6603 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006604 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006605 DAG.getBuildVector(IndexVT, DL,
6606 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006607 } else {
6608 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6609 // cannot currently represent the register constraints on the input
6610 // table registers.
6611 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006612 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6613 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006614 Shuffle = DAG.getNode(
6615 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006616 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6617 V2Cst, DAG.getBuildVector(IndexVT, DL,
6618 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006619 }
6620 }
6621 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6622}
6623
6624static unsigned getDUPLANEOp(EVT EltType) {
6625 if (EltType == MVT::i8)
6626 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006627 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006628 return AArch64ISD::DUPLANE16;
6629 if (EltType == MVT::i32 || EltType == MVT::f32)
6630 return AArch64ISD::DUPLANE32;
6631 if (EltType == MVT::i64 || EltType == MVT::f64)
6632 return AArch64ISD::DUPLANE64;
6633
6634 llvm_unreachable("Invalid vector element type?");
6635}
6636
6637SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6638 SelectionDAG &DAG) const {
6639 SDLoc dl(Op);
6640 EVT VT = Op.getValueType();
6641
6642 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6643
6644 // Convert shuffles that are directly supported on NEON to target-specific
6645 // DAG nodes, instead of keeping them as shuffles and matching them again
6646 // during code selection. This is more efficient and avoids the possibility
6647 // of inconsistencies between legalization and selection.
6648 ArrayRef<int> ShuffleMask = SVN->getMask();
6649
6650 SDValue V1 = Op.getOperand(0);
6651 SDValue V2 = Op.getOperand(1);
6652
Craig Topperbc56e3b2016-06-30 04:38:51 +00006653 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006654 int Lane = SVN->getSplatIndex();
6655 // If this is undef splat, generate it via "just" vdup, if possible.
6656 if (Lane == -1)
6657 Lane = 0;
6658
6659 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6660 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6661 V1.getOperand(0));
6662 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6663 // constant. If so, we can just reference the lane's definition directly.
6664 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6665 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6666 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6667
6668 // Otherwise, duplicate from the lane of the input vector.
6669 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6670
6671 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6672 // to make a vector of the same size as this SHUFFLE. We can ignore the
6673 // extract entirely, and canonicalise the concat using WidenVector.
6674 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6675 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6676 V1 = V1.getOperand(0);
6677 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6678 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6679 Lane -= Idx * VT.getVectorNumElements() / 2;
6680 V1 = WidenVector(V1.getOperand(Idx), DAG);
6681 } else if (VT.getSizeInBits() == 64)
6682 V1 = WidenVector(V1, DAG);
6683
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006684 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006685 }
6686
6687 if (isREVMask(ShuffleMask, VT, 64))
6688 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6689 if (isREVMask(ShuffleMask, VT, 32))
6690 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6691 if (isREVMask(ShuffleMask, VT, 16))
6692 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6693
6694 bool ReverseEXT = false;
6695 unsigned Imm;
6696 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6697 if (ReverseEXT)
6698 std::swap(V1, V2);
6699 Imm *= getExtFactor(V1);
6700 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006701 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006702 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006703 Imm *= getExtFactor(V1);
6704 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006705 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006706 }
6707
6708 unsigned WhichResult;
6709 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6710 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6711 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6712 }
6713 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6714 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6715 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6716 }
6717 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6718 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6719 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6720 }
6721
6722 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6723 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6724 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6725 }
6726 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6727 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6728 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6729 }
6730 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6731 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6732 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6733 }
6734
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006735 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006736 return Concat;
6737
6738 bool DstIsLeft;
6739 int Anomaly;
6740 int NumInputElements = V1.getValueType().getVectorNumElements();
6741 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6742 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006743 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006744
6745 SDValue SrcVec = V1;
6746 int SrcLane = ShuffleMask[Anomaly];
6747 if (SrcLane >= NumInputElements) {
6748 SrcVec = V2;
6749 SrcLane -= VT.getVectorNumElements();
6750 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006751 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006752
6753 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006754
6755 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006756 ScalarVT = MVT::i32;
6757
6758 return DAG.getNode(
6759 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6760 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6761 DstLaneV);
6762 }
6763
6764 // If the shuffle is not directly supported and it has 4 elements, use
6765 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6766 unsigned NumElts = VT.getVectorNumElements();
6767 if (NumElts == 4) {
6768 unsigned PFIndexes[4];
6769 for (unsigned i = 0; i != 4; ++i) {
6770 if (ShuffleMask[i] < 0)
6771 PFIndexes[i] = 8;
6772 else
6773 PFIndexes[i] = ShuffleMask[i];
6774 }
6775
6776 // Compute the index in the perfect shuffle table.
6777 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6778 PFIndexes[2] * 9 + PFIndexes[3];
6779 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6780 unsigned Cost = (PFEntry >> 30);
6781
6782 if (Cost <= 4)
6783 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6784 }
6785
6786 return GenerateTBL(Op, ShuffleMask, DAG);
6787}
6788
6789static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6790 APInt &UndefBits) {
6791 EVT VT = BVN->getValueType(0);
6792 APInt SplatBits, SplatUndef;
6793 unsigned SplatBitSize;
6794 bool HasAnyUndefs;
6795 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6796 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6797
6798 for (unsigned i = 0; i < NumSplats; ++i) {
6799 CnstBits <<= SplatBitSize;
6800 UndefBits <<= SplatBitSize;
6801 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6802 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6803 }
6804
6805 return true;
6806 }
6807
6808 return false;
6809}
6810
Evandro Menezes72f39832018-02-20 20:31:45 +00006811// Try 64-bit splatted SIMD immediate.
6812static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6813 const APInt &Bits) {
6814 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6815 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6816 EVT VT = Op.getValueType();
6817 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6818
6819 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6820 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6821
6822 SDLoc dl(Op);
6823 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6824 DAG.getConstant(Value, dl, MVT::i32));
6825 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6826 }
6827 }
6828
6829 return SDValue();
6830}
6831
6832// Try 32-bit splatted SIMD immediate.
6833static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6834 const APInt &Bits,
6835 const SDValue *LHS = nullptr) {
6836 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6837 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6838 EVT VT = Op.getValueType();
6839 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6840 bool isAdvSIMDModImm = false;
6841 uint64_t Shift;
6842
6843 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6844 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6845 Shift = 0;
6846 }
6847 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6848 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6849 Shift = 8;
6850 }
6851 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6852 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6853 Shift = 16;
6854 }
6855 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6856 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6857 Shift = 24;
6858 }
6859
6860 if (isAdvSIMDModImm) {
6861 SDLoc dl(Op);
6862 SDValue Mov;
6863
6864 if (LHS)
6865 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6866 DAG.getConstant(Value, dl, MVT::i32),
6867 DAG.getConstant(Shift, dl, MVT::i32));
6868 else
6869 Mov = DAG.getNode(NewOp, dl, MovTy,
6870 DAG.getConstant(Value, dl, MVT::i32),
6871 DAG.getConstant(Shift, dl, MVT::i32));
6872
6873 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6874 }
6875 }
6876
6877 return SDValue();
6878}
6879
6880// Try 16-bit splatted SIMD immediate.
6881static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6882 const APInt &Bits,
6883 const SDValue *LHS = nullptr) {
6884 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6885 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6886 EVT VT = Op.getValueType();
6887 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6888 bool isAdvSIMDModImm = false;
6889 uint64_t Shift;
6890
6891 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6892 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6893 Shift = 0;
6894 }
6895 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6896 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6897 Shift = 8;
6898 }
6899
6900 if (isAdvSIMDModImm) {
6901 SDLoc dl(Op);
6902 SDValue Mov;
6903
6904 if (LHS)
6905 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006906 DAG.getConstant(Value, dl, MVT::i32),
6907 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006908 else
6909 Mov = DAG.getNode(NewOp, dl, MovTy,
6910 DAG.getConstant(Value, dl, MVT::i32),
6911 DAG.getConstant(Shift, dl, MVT::i32));
6912
6913 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6914 }
6915 }
6916
6917 return SDValue();
6918}
6919
6920// Try 32-bit splatted SIMD immediate with shifted ones.
6921static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6922 SelectionDAG &DAG, const APInt &Bits) {
6923 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6924 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6925 EVT VT = Op.getValueType();
6926 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6927 bool isAdvSIMDModImm = false;
6928 uint64_t Shift;
6929
6930 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6931 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6932 Shift = 264;
6933 }
6934 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6935 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6936 Shift = 272;
6937 }
6938
6939 if (isAdvSIMDModImm) {
6940 SDLoc dl(Op);
6941 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6942 DAG.getConstant(Value, dl, MVT::i32),
6943 DAG.getConstant(Shift, dl, MVT::i32));
6944 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6945 }
6946 }
6947
6948 return SDValue();
6949}
6950
6951// Try 8-bit splatted SIMD immediate.
6952static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6953 const APInt &Bits) {
6954 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6955 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6956 EVT VT = Op.getValueType();
6957 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6958
6959 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6960 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6961
6962 SDLoc dl(Op);
6963 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6964 DAG.getConstant(Value, dl, MVT::i32));
6965 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6966 }
6967 }
6968
6969 return SDValue();
6970}
6971
6972// Try FP splatted SIMD immediate.
6973static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6974 const APInt &Bits) {
6975 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6976 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6977 EVT VT = Op.getValueType();
6978 bool isWide = (VT.getSizeInBits() == 128);
6979 MVT MovTy;
6980 bool isAdvSIMDModImm = false;
6981
6982 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6983 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6984 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6985 }
6986 else if (isWide &&
6987 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6988 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6989 MovTy = MVT::v2f64;
6990 }
6991
6992 if (isAdvSIMDModImm) {
6993 SDLoc dl(Op);
6994 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6995 DAG.getConstant(Value, dl, MVT::i32));
6996 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6997 }
6998 }
6999
7000 return SDValue();
7001}
7002
Tim Northover3b0846e2014-05-24 12:50:23 +00007003// Specialized code to quickly find if PotentialBVec is a BuildVector that
7004// consists of only the same constant int value, returned in reference arg
7005// ConstVal
7006static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7007 uint64_t &ConstVal) {
7008 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7009 if (!Bvec)
7010 return false;
7011 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7012 if (!FirstElt)
7013 return false;
7014 EVT VT = Bvec->getValueType(0);
7015 unsigned NumElts = VT.getVectorNumElements();
7016 for (unsigned i = 1; i < NumElts; ++i)
7017 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7018 return false;
7019 ConstVal = FirstElt->getZExtValue();
7020 return true;
7021}
7022
7023static unsigned getIntrinsicID(const SDNode *N) {
7024 unsigned Opcode = N->getOpcode();
7025 switch (Opcode) {
7026 default:
7027 return Intrinsic::not_intrinsic;
7028 case ISD::INTRINSIC_WO_CHAIN: {
7029 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7030 if (IID < Intrinsic::num_intrinsics)
7031 return IID;
7032 return Intrinsic::not_intrinsic;
7033 }
7034 }
7035}
7036
7037// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7038// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7039// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7040// Also, logical shift right -> sri, with the same structure.
7041static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7042 EVT VT = N->getValueType(0);
7043
7044 if (!VT.isVector())
7045 return SDValue();
7046
7047 SDLoc DL(N);
7048
7049 // Is the first op an AND?
7050 const SDValue And = N->getOperand(0);
7051 if (And.getOpcode() != ISD::AND)
7052 return SDValue();
7053
7054 // Is the second op an shl or lshr?
7055 SDValue Shift = N->getOperand(1);
7056 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7057 // or AArch64ISD::VLSHR vector, #shift
7058 unsigned ShiftOpc = Shift.getOpcode();
7059 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7060 return SDValue();
7061 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7062
7063 // Is the shift amount constant?
7064 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7065 if (!C2node)
7066 return SDValue();
7067
7068 // Is the and mask vector all constant?
7069 uint64_t C1;
7070 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7071 return SDValue();
7072
7073 // Is C1 == ~C2, taking into account how much one can shift elements of a
7074 // particular size?
7075 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007076 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007077 if (C2 > ElemSizeInBits)
7078 return SDValue();
7079 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7080 if ((C1 & ElemMask) != (~C2 & ElemMask))
7081 return SDValue();
7082
7083 SDValue X = And.getOperand(0);
7084 SDValue Y = Shift.getOperand(0);
7085
7086 unsigned Intrin =
7087 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7088 SDValue ResultSLI =
7089 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007090 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7091 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007092
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007093 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7094 LLVM_DEBUG(N->dump(&DAG));
7095 LLVM_DEBUG(dbgs() << "into: \n");
7096 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007097
7098 ++NumShiftInserts;
7099 return ResultSLI;
7100}
7101
7102SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7103 SelectionDAG &DAG) const {
7104 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7105 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007106 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007107 return Res;
7108 }
7109
Tim Northover3b0846e2014-05-24 12:50:23 +00007110 EVT VT = Op.getValueType();
7111
Evandro Menezescd855f72018-03-05 17:02:47 +00007112 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007113 BuildVectorSDNode *BVN =
7114 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007115 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007116 // OR commutes, so try swapping the operands.
7117 LHS = Op.getOperand(1);
7118 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007119 }
7120 if (!BVN)
7121 return Op;
7122
Evandro Menezes72f39832018-02-20 20:31:45 +00007123 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007124 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007125 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7126 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007127
Evandro Menezes72f39832018-02-20 20:31:45 +00007128 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7129 DefBits, &LHS)) ||
7130 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7131 DefBits, &LHS)))
7132 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007133
7134 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7135 UndefBits, &LHS)) ||
7136 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7137 UndefBits, &LHS)))
7138 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007139 }
7140
Evandro Menezes72f39832018-02-20 20:31:45 +00007141 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007142 return Op;
7143}
7144
Kevin Qin4473c192014-07-07 02:45:40 +00007145// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7146// be truncated to fit element width.
7147static SDValue NormalizeBuildVector(SDValue Op,
7148 SelectionDAG &DAG) {
7149 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007150 SDLoc dl(Op);
7151 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007152 EVT EltTy= VT.getVectorElementType();
7153
7154 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7155 return Op;
7156
7157 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007158 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007159 // For integer vectors, type legalization would have promoted the
7160 // operands already. Otherwise, if Op is a floating-point splat
7161 // (with operands cast to integers), then the only possibilities
7162 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007163 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007164 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007165 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007166 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007167 } else if (Lane.getNode()->isUndef()) {
7168 Lane = DAG.getUNDEF(MVT::i32);
7169 } else {
7170 assert(Lane.getValueType() == MVT::i32 &&
7171 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007172 }
7173 Ops.push_back(Lane);
7174 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007175 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007176}
7177
Evandro Menezescd855f72018-03-05 17:02:47 +00007178static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007179 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007180
Evandro Menezes72f39832018-02-20 20:31:45 +00007181 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007182 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007183 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007184 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007185 SDValue NewOp;
7186 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7187 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7188 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7189 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7190 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7191 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7192 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007193
Evandro Menezes72f39832018-02-20 20:31:45 +00007194 DefBits = ~DefBits;
7195 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7196 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7197 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7198 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007199
Evandro Menezes72f39832018-02-20 20:31:45 +00007200 DefBits = UndefBits;
7201 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7202 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7203 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7204 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7205 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7206 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7207 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007208
Evandro Menezes72f39832018-02-20 20:31:45 +00007209 DefBits = ~UndefBits;
7210 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7211 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7212 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7213 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007214 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007215
Evandro Menezescd855f72018-03-05 17:02:47 +00007216 return SDValue();
7217}
7218
7219SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7220 SelectionDAG &DAG) const {
7221 EVT VT = Op.getValueType();
7222
7223 // Try to build a simple constant vector.
7224 Op = NormalizeBuildVector(Op, DAG);
7225 if (VT.isInteger()) {
7226 // Certain vector constants, used to express things like logical NOT and
7227 // arithmetic NEG, are passed through unmodified. This allows special
7228 // patterns for these operations to match, which will lower these constants
7229 // to whatever is proven necessary.
7230 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7231 if (BVN->isConstant())
7232 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7233 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7234 APInt Val(BitSize,
7235 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7236 if (Val.isNullValue() || Val.isAllOnesValue())
7237 return Op;
7238 }
7239 }
7240
7241 if (SDValue V = ConstantBuildVector(Op, DAG))
7242 return V;
7243
Tim Northover3b0846e2014-05-24 12:50:23 +00007244 // Scan through the operands to find some interesting properties we can
7245 // exploit:
7246 // 1) If only one value is used, we can use a DUP, or
7247 // 2) if only the low element is not undef, we can just insert that, or
7248 // 3) if only one constant value is used (w/ some non-constant lanes),
7249 // we can splat the constant value into the whole vector then fill
7250 // in the non-constant lanes.
7251 // 4) FIXME: If different constant values are used, but we can intelligently
7252 // select the values we'll be overwriting for the non-constant
7253 // lanes such that we can directly materialize the vector
7254 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007255 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007256 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007257 unsigned NumElts = VT.getVectorNumElements();
7258 bool isOnlyLowElement = true;
7259 bool usesOnlyOneValue = true;
7260 bool usesOnlyOneConstantValue = true;
7261 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007262 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007263 unsigned NumConstantLanes = 0;
7264 SDValue Value;
7265 SDValue ConstantValue;
7266 for (unsigned i = 0; i < NumElts; ++i) {
7267 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007268 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7269 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007270 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007271 continue;
7272 if (i > 0)
7273 isOnlyLowElement = false;
7274 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7275 isConstant = false;
7276
7277 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7278 ++NumConstantLanes;
7279 if (!ConstantValue.getNode())
7280 ConstantValue = V;
7281 else if (ConstantValue != V)
7282 usesOnlyOneConstantValue = false;
7283 }
7284
7285 if (!Value.getNode())
7286 Value = V;
7287 else if (V != Value)
7288 usesOnlyOneValue = false;
7289 }
7290
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007291 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007292 LLVM_DEBUG(
7293 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007294 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007295 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007296
John Brawnd6e0ebe2018-11-22 11:45:23 +00007297 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7298 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7299 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7300 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007301 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7302 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007303 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007304 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007305
Sebastian Popc33af712018-03-01 15:47:39 +00007306 if (AllLanesExtractElt) {
7307 SDNode *Vector = nullptr;
7308 bool Even = false;
7309 bool Odd = false;
7310 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7311 // the Odd pattern <1,3,5,...>.
7312 for (unsigned i = 0; i < NumElts; ++i) {
7313 SDValue V = Op.getOperand(i);
7314 const SDNode *N = V.getNode();
7315 if (!isa<ConstantSDNode>(N->getOperand(1)))
7316 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007317 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007318
7319 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007320 if (!Vector) {
7321 Vector = N0.getNode();
7322 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7323 // BUILD_VECTOR.
7324 if (VT.getVectorElementType() !=
7325 N0.getValueType().getVectorElementType())
7326 break;
7327 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007328 Odd = false;
7329 Even = false;
7330 break;
7331 }
7332
7333 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7334 // indices <1,3,5,...>.
7335 uint64_t Val = N->getConstantOperandVal(1);
7336 if (Val == 2 * i) {
7337 Even = true;
7338 continue;
7339 }
7340 if (Val - 1 == 2 * i) {
7341 Odd = true;
7342 continue;
7343 }
7344
7345 // Something does not match: abort.
7346 Odd = false;
7347 Even = false;
7348 break;
7349 }
7350 if (Even || Odd) {
7351 SDValue LHS =
7352 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7353 DAG.getConstant(0, dl, MVT::i64));
7354 SDValue RHS =
7355 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7356 DAG.getConstant(NumElts, dl, MVT::i64));
7357
7358 if (Even && !Odd)
7359 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7360 RHS);
7361 if (Odd && !Even)
7362 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7363 RHS);
7364 }
7365 }
7366
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007367 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007368 // i32 and try again.
7369 if (usesOnlyOneValue) {
7370 if (!isConstant) {
7371 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007372 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007373 LLVM_DEBUG(
7374 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007375 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007376 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007377
7378 // This is actually a DUPLANExx operation, which keeps everything vectory.
7379
Tim Northover3b0846e2014-05-24 12:50:23 +00007380 SDValue Lane = Value.getOperand(1);
7381 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007382 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007383 LLVM_DEBUG(
7384 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7385 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007386 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007387 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007388
7389 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7390 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7391 }
7392
7393 if (VT.getVectorElementType().isFloatingPoint()) {
7394 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007395 EVT EltTy = VT.getVectorElementType();
7396 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7397 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007398 LLVM_DEBUG(
7399 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7400 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007401 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007402 for (unsigned i = 0; i < NumElts; ++i)
7403 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7404 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007405 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007406 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7407 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007408 Val = LowerBUILD_VECTOR(Val, DAG);
7409 if (Val.getNode())
7410 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7411 }
7412 }
7413
7414 // If there was only one constant value used and for more than one lane,
7415 // start by splatting that value, then replace the non-constant lanes. This
7416 // is better than the default, which will perform a separate initialization
7417 // for each lane.
7418 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007419 // Firstly, try to materialize the splat constant.
7420 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7421 Val = ConstantBuildVector(Vec, DAG);
7422 if (!Val) {
7423 // Otherwise, materialize the constant and splat it.
7424 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7425 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7426 }
7427
Tim Northover3b0846e2014-05-24 12:50:23 +00007428 // Now insert the non-constant lanes.
7429 for (unsigned i = 0; i < NumElts; ++i) {
7430 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007431 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007432 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007433 // Note that type legalization likely mucked about with the VT of the
7434 // source operand, so we may have to convert it here before inserting.
7435 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007436 }
7437 return Val;
7438 }
7439
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007440 // This will generate a load from the constant pool.
7441 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007442 LLVM_DEBUG(
7443 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7444 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007445 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007446 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007447
7448 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7449 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007450 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007451 return shuffle;
7452 }
7453
7454 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7455 // know the default expansion would otherwise fall back on something even
7456 // worse. For a vector with one or two non-undef values, that's
7457 // scalar_to_vector for the elements followed by a shuffle (provided the
7458 // shuffle is valid for the target) and materialization element by element
7459 // on the stack followed by a load for everything else.
7460 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007461 LLVM_DEBUG(
7462 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7463 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007464
Tim Northover3b0846e2014-05-24 12:50:23 +00007465 SDValue Vec = DAG.getUNDEF(VT);
7466 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007467 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007468
7469 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007470 // a) Avoid a RMW dependency on the full vector register, and
7471 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007472 // value is already in an S or D register, and we're forced to emit an
7473 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007474 //
7475 // We also allow types like i8 and i16 which are illegal scalar but legal
7476 // vector element types. After type-legalization the inserted value is
7477 // extended (i32) and it is safe to cast them to the vector type by ignoring
7478 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7479 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007480 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007481 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007482 ++i;
7483 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007484 LLVM_DEBUG(if (i < NumElts) dbgs()
7485 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007486 for (; i < NumElts; ++i) {
7487 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007488 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007489 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007490 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007491 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7492 }
7493 return Vec;
7494 }
7495
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007496 LLVM_DEBUG(
7497 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7498 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007499 return SDValue();
7500}
7501
7502SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7503 SelectionDAG &DAG) const {
7504 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7505
Tim Northovere4b8e132014-07-15 10:00:26 +00007506 // Check for non-constant or out of range lane.
7507 EVT VT = Op.getOperand(0).getValueType();
7508 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7509 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007510 return SDValue();
7511
Tim Northover3b0846e2014-05-24 12:50:23 +00007512
7513 // Insertion/extraction are legal for V128 types.
7514 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007515 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7516 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007517 return Op;
7518
7519 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007520 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007521 return SDValue();
7522
7523 // For V64 types, we perform insertion by expanding the value
7524 // to a V128 type and perform the insertion on that.
7525 SDLoc DL(Op);
7526 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7527 EVT WideTy = WideVec.getValueType();
7528
7529 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7530 Op.getOperand(1), Op.getOperand(2));
7531 // Re-narrow the resultant vector.
7532 return NarrowVector(Node, DAG);
7533}
7534
7535SDValue
7536AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7537 SelectionDAG &DAG) const {
7538 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7539
Tim Northovere4b8e132014-07-15 10:00:26 +00007540 // Check for non-constant or out of range lane.
7541 EVT VT = Op.getOperand(0).getValueType();
7542 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7543 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007544 return SDValue();
7545
Tim Northover3b0846e2014-05-24 12:50:23 +00007546
7547 // Insertion/extraction are legal for V128 types.
7548 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007549 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7550 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007551 return Op;
7552
7553 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007554 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007555 return SDValue();
7556
7557 // For V64 types, we perform extraction by expanding the value
7558 // to a V128 type and perform the extraction on that.
7559 SDLoc DL(Op);
7560 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7561 EVT WideTy = WideVec.getValueType();
7562
7563 EVT ExtrTy = WideTy.getVectorElementType();
7564 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7565 ExtrTy = MVT::i32;
7566
7567 // For extractions, we just return the result directly.
7568 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7569 Op.getOperand(1));
7570}
7571
7572SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7573 SelectionDAG &DAG) const {
7574 EVT VT = Op.getOperand(0).getValueType();
7575 SDLoc dl(Op);
7576 // Just in case...
7577 if (!VT.isVector())
7578 return SDValue();
7579
7580 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7581 if (!Cst)
7582 return SDValue();
7583 unsigned Val = Cst->getZExtValue();
7584
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007585 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007586
7587 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7588 if (Val == 0)
7589 return Op;
7590
Tim Northover3b0846e2014-05-24 12:50:23 +00007591 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7592 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007593 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007594 return Op;
7595
7596 return SDValue();
7597}
7598
Zvi Rackover1b736822017-07-26 08:06:58 +00007599bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007600 if (VT.getVectorNumElements() == 4 &&
7601 (VT.is128BitVector() || VT.is64BitVector())) {
7602 unsigned PFIndexes[4];
7603 for (unsigned i = 0; i != 4; ++i) {
7604 if (M[i] < 0)
7605 PFIndexes[i] = 8;
7606 else
7607 PFIndexes[i] = M[i];
7608 }
7609
7610 // Compute the index in the perfect shuffle table.
7611 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7612 PFIndexes[2] * 9 + PFIndexes[3];
7613 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7614 unsigned Cost = (PFEntry >> 30);
7615
7616 if (Cost <= 4)
7617 return true;
7618 }
7619
7620 bool DummyBool;
7621 int DummyInt;
7622 unsigned DummyUnsigned;
7623
7624 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7625 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7626 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7627 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7628 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7629 isZIPMask(M, VT, DummyUnsigned) ||
7630 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7631 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7632 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7633 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7634 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7635}
7636
7637/// getVShiftImm - Check if this is a valid build_vector for the immediate
7638/// operand of a vector shift operation, where all the elements of the
7639/// build_vector must have the same constant integer value.
7640static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7641 // Ignore bit_converts.
7642 while (Op.getOpcode() == ISD::BITCAST)
7643 Op = Op.getOperand(0);
7644 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7645 APInt SplatBits, SplatUndef;
7646 unsigned SplatBitSize;
7647 bool HasAnyUndefs;
7648 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7649 HasAnyUndefs, ElementBits) ||
7650 SplatBitSize > ElementBits)
7651 return false;
7652 Cnt = SplatBits.getSExtValue();
7653 return true;
7654}
7655
7656/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7657/// operand of a vector shift left operation. That value must be in the range:
7658/// 0 <= Value < ElementBits for a left shift; or
7659/// 0 <= Value <= ElementBits for a long left shift.
7660static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7661 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007662 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007663 if (!getVShiftImm(Op, ElementBits, Cnt))
7664 return false;
7665 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7666}
7667
7668/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007669/// operand of a vector shift right operation. The value must be in the range:
7670/// 1 <= Value <= ElementBits for a right shift; or
7671static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007672 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007673 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007674 if (!getVShiftImm(Op, ElementBits, Cnt))
7675 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007676 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7677}
7678
7679SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7680 SelectionDAG &DAG) const {
7681 EVT VT = Op.getValueType();
7682 SDLoc DL(Op);
7683 int64_t Cnt;
7684
7685 if (!Op.getOperand(1).getValueType().isVector())
7686 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007687 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007688
7689 switch (Op.getOpcode()) {
7690 default:
7691 llvm_unreachable("unexpected shift opcode");
7692
7693 case ISD::SHL:
7694 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007695 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7696 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007698 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7699 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007700 Op.getOperand(0), Op.getOperand(1));
7701 case ISD::SRA:
7702 case ISD::SRL:
7703 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007704 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007705 unsigned Opc =
7706 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007707 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7708 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007709 }
7710
7711 // Right shift register. Note, there is not a shift right register
7712 // instruction, but the shift left register instruction takes a signed
7713 // value, where negative numbers specify a right shift.
7714 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7715 : Intrinsic::aarch64_neon_ushl;
7716 // negate the shift amount
7717 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7718 SDValue NegShiftLeft =
7719 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007720 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7721 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007722 return NegShiftLeft;
7723 }
7724
7725 return SDValue();
7726}
7727
7728static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7729 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007730 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007731 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007732 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7733 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007734
7735 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7736 APInt CnstBits(VT.getSizeInBits(), 0);
7737 APInt UndefBits(VT.getSizeInBits(), 0);
7738 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7739 bool IsZero = IsCnst && (CnstBits == 0);
7740
7741 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7742 switch (CC) {
7743 default:
7744 return SDValue();
7745 case AArch64CC::NE: {
7746 SDValue Fcmeq;
7747 if (IsZero)
7748 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7749 else
7750 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7751 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7752 }
7753 case AArch64CC::EQ:
7754 if (IsZero)
7755 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7756 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7757 case AArch64CC::GE:
7758 if (IsZero)
7759 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7760 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7761 case AArch64CC::GT:
7762 if (IsZero)
7763 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7764 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7765 case AArch64CC::LS:
7766 if (IsZero)
7767 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7768 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7769 case AArch64CC::LT:
7770 if (!NoNans)
7771 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007772 // If we ignore NaNs then we can use to the MI implementation.
7773 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007774 case AArch64CC::MI:
7775 if (IsZero)
7776 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7777 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7778 }
7779 }
7780
7781 switch (CC) {
7782 default:
7783 return SDValue();
7784 case AArch64CC::NE: {
7785 SDValue Cmeq;
7786 if (IsZero)
7787 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7788 else
7789 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7790 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7791 }
7792 case AArch64CC::EQ:
7793 if (IsZero)
7794 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7795 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7796 case AArch64CC::GE:
7797 if (IsZero)
7798 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7799 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7800 case AArch64CC::GT:
7801 if (IsZero)
7802 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7803 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7804 case AArch64CC::LE:
7805 if (IsZero)
7806 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7807 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7808 case AArch64CC::LS:
7809 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7810 case AArch64CC::LO:
7811 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7812 case AArch64CC::LT:
7813 if (IsZero)
7814 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7815 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7816 case AArch64CC::HI:
7817 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7818 case AArch64CC::HS:
7819 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7820 }
7821}
7822
7823SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7824 SelectionDAG &DAG) const {
7825 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7826 SDValue LHS = Op.getOperand(0);
7827 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007828 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007829 SDLoc dl(Op);
7830
7831 if (LHS.getValueType().getVectorElementType().isInteger()) {
7832 assert(LHS.getValueType() == RHS.getValueType());
7833 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007834 SDValue Cmp =
7835 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7836 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007837 }
7838
Carey Williamsda15b5b2018-01-22 14:16:11 +00007839 const bool FullFP16 =
7840 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7841
7842 // Make v4f16 (only) fcmp operations utilise vector instructions
7843 // v8f16 support will be a litle more complicated
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007844 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7845 if (LHS.getValueType().getVectorNumElements() == 4) {
Carey Williamsda15b5b2018-01-22 14:16:11 +00007846 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7847 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7848 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7849 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7850 CmpVT = MVT::v4i32;
7851 } else
7852 return SDValue();
7853 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007854
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007855 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7856 LHS.getValueType().getVectorElementType() != MVT::f128);
Tim Northover3b0846e2014-05-24 12:50:23 +00007857
7858 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7859 // clean. Some of them require two branches to implement.
7860 AArch64CC::CondCode CC1, CC2;
7861 bool ShouldInvert;
7862 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7863
7864 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7865 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007866 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007867 if (!Cmp.getNode())
7868 return SDValue();
7869
7870 if (CC2 != AArch64CC::AL) {
7871 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007872 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007873 if (!Cmp2.getNode())
7874 return SDValue();
7875
Tim Northover45aa89c2015-02-08 00:50:47 +00007876 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007877 }
7878
Tim Northover45aa89c2015-02-08 00:50:47 +00007879 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7880
Tim Northover3b0846e2014-05-24 12:50:23 +00007881 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007882 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007883
7884 return Cmp;
7885}
7886
Amara Emersonc9916d72017-05-16 21:29:22 +00007887static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7888 SelectionDAG &DAG) {
7889 SDValue VecOp = ScalarOp.getOperand(0);
7890 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7892 DAG.getConstant(0, DL, MVT::i64));
7893}
7894
7895SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7896 SelectionDAG &DAG) const {
7897 SDLoc dl(Op);
7898 switch (Op.getOpcode()) {
7899 case ISD::VECREDUCE_ADD:
7900 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7901 case ISD::VECREDUCE_SMAX:
7902 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7903 case ISD::VECREDUCE_SMIN:
7904 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7905 case ISD::VECREDUCE_UMAX:
7906 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7907 case ISD::VECREDUCE_UMIN:
7908 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7909 case ISD::VECREDUCE_FMAX: {
7910 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7911 return DAG.getNode(
7912 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7913 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7914 Op.getOperand(0));
7915 }
7916 case ISD::VECREDUCE_FMIN: {
7917 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7918 return DAG.getNode(
7919 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7920 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7921 Op.getOperand(0));
7922 }
7923 default:
7924 llvm_unreachable("Unhandled reduction");
7925 }
7926}
7927
Oliver Stannard42699172018-02-12 14:22:03 +00007928SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7929 SelectionDAG &DAG) const {
7930 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7931 if (!Subtarget.hasLSE())
7932 return SDValue();
7933
7934 // LSE has an atomic load-add instruction, but not a load-sub.
7935 SDLoc dl(Op);
7936 MVT VT = Op.getSimpleValueType();
7937 SDValue RHS = Op.getOperand(2);
7938 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7939 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7940 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7941 Op.getOperand(0), Op.getOperand(1), RHS,
7942 AN->getMemOperand());
7943}
7944
Oliver Stannard02f08c92018-02-12 17:03:11 +00007945SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7946 SelectionDAG &DAG) const {
7947 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7948 if (!Subtarget.hasLSE())
7949 return SDValue();
7950
7951 // LSE has an atomic load-clear instruction, but not a load-and.
7952 SDLoc dl(Op);
7953 MVT VT = Op.getSimpleValueType();
7954 SDValue RHS = Op.getOperand(2);
7955 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7956 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7957 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7958 Op.getOperand(0), Op.getOperand(1), RHS,
7959 AN->getMemOperand());
7960}
7961
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007962SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7963 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7964 SDLoc dl(Op);
7965 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7966 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7967
Tri Vo6c47c622018-09-22 22:17:50 +00007968 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7969 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7970 if (Subtarget->hasCustomCallingConv())
7971 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007972
7973 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7974 DAG.getConstant(4, dl, MVT::i64));
7975 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7976 Chain =
7977 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7978 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7979 DAG.getRegisterMask(Mask), Chain.getValue(1));
7980 // To match the actual intent better, we should read the output from X15 here
7981 // again (instead of potentially spilling it to the stack), but rereading Size
7982 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7983 // here.
7984
7985 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7986 DAG.getConstant(4, dl, MVT::i64));
7987 return Chain;
7988}
7989
7990SDValue
7991AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7992 SelectionDAG &DAG) const {
7993 assert(Subtarget->isTargetWindows() &&
7994 "Only Windows alloca probing supported");
7995 SDLoc dl(Op);
7996 // Get the inputs.
7997 SDNode *Node = Op.getNode();
7998 SDValue Chain = Op.getOperand(0);
7999 SDValue Size = Op.getOperand(1);
8000 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8001 EVT VT = Node->getValueType(0);
8002
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00008003 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8004 "no-stack-arg-probe")) {
8005 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8006 Chain = SP.getValue(1);
8007 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8008 if (Align)
8009 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8010 DAG.getConstant(-(uint64_t)Align, dl, VT));
8011 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8012 SDValue Ops[2] = {SP, Chain};
8013 return DAG.getMergeValues(Ops, dl);
8014 }
8015
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008016 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8017
8018 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8019
8020 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8021 Chain = SP.getValue(1);
8022 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00008023 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008024 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8025 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00008026 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008027
8028 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8029 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8030
8031 SDValue Ops[2] = {SP, Chain};
8032 return DAG.getMergeValues(Ops, dl);
8033}
8034
Tim Northover3b0846e2014-05-24 12:50:23 +00008035/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8036/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8037/// specified in the intrinsic calls.
8038bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8039 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00008040 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00008041 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008042 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00008043 switch (Intrinsic) {
8044 case Intrinsic::aarch64_neon_ld2:
8045 case Intrinsic::aarch64_neon_ld3:
8046 case Intrinsic::aarch64_neon_ld4:
8047 case Intrinsic::aarch64_neon_ld1x2:
8048 case Intrinsic::aarch64_neon_ld1x3:
8049 case Intrinsic::aarch64_neon_ld1x4:
8050 case Intrinsic::aarch64_neon_ld2lane:
8051 case Intrinsic::aarch64_neon_ld3lane:
8052 case Intrinsic::aarch64_neon_ld4lane:
8053 case Intrinsic::aarch64_neon_ld2r:
8054 case Intrinsic::aarch64_neon_ld3r:
8055 case Intrinsic::aarch64_neon_ld4r: {
8056 Info.opc = ISD::INTRINSIC_W_CHAIN;
8057 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008058 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008059 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8060 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8061 Info.offset = 0;
8062 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008063 // volatile loads with NEON intrinsics not supported
8064 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008065 return true;
8066 }
8067 case Intrinsic::aarch64_neon_st2:
8068 case Intrinsic::aarch64_neon_st3:
8069 case Intrinsic::aarch64_neon_st4:
8070 case Intrinsic::aarch64_neon_st1x2:
8071 case Intrinsic::aarch64_neon_st1x3:
8072 case Intrinsic::aarch64_neon_st1x4:
8073 case Intrinsic::aarch64_neon_st2lane:
8074 case Intrinsic::aarch64_neon_st3lane:
8075 case Intrinsic::aarch64_neon_st4lane: {
8076 Info.opc = ISD::INTRINSIC_VOID;
8077 // Conservatively set memVT to the entire set of vectors stored.
8078 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008079 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008080 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8081 if (!ArgTy->isVectorTy())
8082 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008083 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008084 }
8085 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8086 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8087 Info.offset = 0;
8088 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008089 // volatile stores with NEON intrinsics not supported
8090 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008091 return true;
8092 }
8093 case Intrinsic::aarch64_ldaxr:
8094 case Intrinsic::aarch64_ldxr: {
8095 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8096 Info.opc = ISD::INTRINSIC_W_CHAIN;
8097 Info.memVT = MVT::getVT(PtrTy->getElementType());
8098 Info.ptrVal = I.getArgOperand(0);
8099 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008100 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008101 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008102 return true;
8103 }
8104 case Intrinsic::aarch64_stlxr:
8105 case Intrinsic::aarch64_stxr: {
8106 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8107 Info.opc = ISD::INTRINSIC_W_CHAIN;
8108 Info.memVT = MVT::getVT(PtrTy->getElementType());
8109 Info.ptrVal = I.getArgOperand(1);
8110 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008111 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008112 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008113 return true;
8114 }
8115 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008116 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008117 Info.opc = ISD::INTRINSIC_W_CHAIN;
8118 Info.memVT = MVT::i128;
8119 Info.ptrVal = I.getArgOperand(0);
8120 Info.offset = 0;
8121 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008122 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008123 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008124 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008125 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008126 Info.opc = ISD::INTRINSIC_W_CHAIN;
8127 Info.memVT = MVT::i128;
8128 Info.ptrVal = I.getArgOperand(2);
8129 Info.offset = 0;
8130 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008131 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008132 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008133 default:
8134 break;
8135 }
8136
8137 return false;
8138}
8139
John Brawne3b44f92018-03-23 14:47:07 +00008140bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8141 ISD::LoadExtType ExtTy,
8142 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008143 // TODO: This may be worth removing. Check regression tests for diffs.
8144 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8145 return false;
8146
John Brawne3b44f92018-03-23 14:47:07 +00008147 // If we're reducing the load width in order to avoid having to use an extra
8148 // instruction to do extension then it's probably a good idea.
8149 if (ExtTy != ISD::NON_EXTLOAD)
8150 return true;
8151 // Don't reduce load width if it would prevent us from combining a shift into
8152 // the offset.
8153 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8154 assert(Mem);
8155 const SDValue &Base = Mem->getBasePtr();
8156 if (Base.getOpcode() == ISD::ADD &&
8157 Base.getOperand(1).getOpcode() == ISD::SHL &&
8158 Base.getOperand(1).hasOneUse() &&
8159 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8160 // The shift can be combined if it matches the size of the value being
8161 // loaded (and so reducing the width would make it not match).
8162 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8163 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8164 if (ShiftAmount == Log2_32(LoadBytes))
8165 return false;
8166 }
8167 // We have no reason to disallow reducing the load width, so allow it.
8168 return true;
8169}
8170
Tim Northover3b0846e2014-05-24 12:50:23 +00008171// Truncations from 64-bit GPR to 32-bit GPR is free.
8172bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8173 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8174 return false;
8175 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8176 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008177 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008178}
8179bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008180 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008181 return false;
8182 unsigned NumBits1 = VT1.getSizeInBits();
8183 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008184 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008185}
8186
Chad Rosier54390052015-02-23 19:15:16 +00008187/// Check if it is profitable to hoist instruction in then/else to if.
8188/// Not profitable if I and it's user can form a FMA instruction
8189/// because we prefer FMSUB/FMADD.
8190bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8191 if (I->getOpcode() != Instruction::FMul)
8192 return true;
8193
Davide Italiano3e9986f2017-04-18 00:29:54 +00008194 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008195 return true;
8196
8197 Instruction *User = I->user_back();
8198
8199 if (User &&
8200 !(User->getOpcode() == Instruction::FSub ||
8201 User->getOpcode() == Instruction::FAdd))
8202 return true;
8203
8204 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008205 const DataLayout &DL = I->getModule()->getDataLayout();
8206 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008207
Eric Christopher114fa1c2016-02-29 22:50:49 +00008208 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8209 isOperationLegalOrCustom(ISD::FMA, VT) &&
8210 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8211 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008212}
8213
Tim Northover3b0846e2014-05-24 12:50:23 +00008214// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8215// 64-bit GPR.
8216bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8217 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8218 return false;
8219 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8220 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008221 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008222}
8223bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008224 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008225 return false;
8226 unsigned NumBits1 = VT1.getSizeInBits();
8227 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008228 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008229}
8230
8231bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8232 EVT VT1 = Val.getValueType();
8233 if (isZExtFree(VT1, VT2)) {
8234 return true;
8235 }
8236
8237 if (Val.getOpcode() != ISD::LOAD)
8238 return false;
8239
8240 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008241 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8242 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8243 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008244}
8245
Quentin Colombet6843ac42015-03-31 20:52:32 +00008246bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8247 if (isa<FPExtInst>(Ext))
8248 return false;
8249
Haicheng Wu50692a22017-08-01 21:26:45 +00008250 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008251 if (Ext->getType()->isVectorTy())
8252 return false;
8253
8254 for (const Use &U : Ext->uses()) {
8255 // The extension is free if we can fold it with a left shift in an
8256 // addressing mode or an arithmetic operation: add, sub, and cmp.
8257
8258 // Is there a shift?
8259 const Instruction *Instr = cast<Instruction>(U.getUser());
8260
8261 // Is this a constant shift?
8262 switch (Instr->getOpcode()) {
8263 case Instruction::Shl:
8264 if (!isa<ConstantInt>(Instr->getOperand(1)))
8265 return false;
8266 break;
8267 case Instruction::GetElementPtr: {
8268 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008269 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008270 std::advance(GTI, U.getOperandNo()-1);
8271 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008272 // This extension will end up with a shift because of the scaling factor.
8273 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8274 // Get the shift amount based on the scaling factor:
8275 // log2(sizeof(IdxTy)) - log2(8).
8276 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008277 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008278 // Is the constant foldable in the shift of the addressing mode?
8279 // I.e., shift amount is between 1 and 4 inclusive.
8280 if (ShiftAmt == 0 || ShiftAmt > 4)
8281 return false;
8282 break;
8283 }
8284 case Instruction::Trunc:
8285 // Check if this is a noop.
8286 // trunc(sext ty1 to ty2) to ty1.
8287 if (Instr->getType() == Ext->getOperand(0)->getType())
8288 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008289 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008290 default:
8291 return false;
8292 }
8293
8294 // At this point we can use the bfm family, so this extension is free
8295 // for that use.
8296 }
8297 return true;
8298}
8299
Florian Hahn3b251962019-02-05 10:27:40 +00008300/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8301/// or upper half of the vector elements.
8302static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8303 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8304 auto *FullVT = cast<VectorType>(FullV->getType());
8305 auto *HalfVT = cast<VectorType>(HalfV->getType());
8306 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8307 };
8308
8309 auto extractHalf = [](Value *FullV, Value *HalfV) {
8310 auto *FullVT = cast<VectorType>(FullV->getType());
8311 auto *HalfVT = cast<VectorType>(HalfV->getType());
8312 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8313 };
8314
8315 Constant *M1, *M2;
8316 Value *S1Op1, *S2Op1;
8317 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8318 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8319 return false;
8320
8321 // Check that the operands are half as wide as the result and we extract
8322 // half of the elements of the input vectors.
8323 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8324 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8325 return false;
8326
8327 // Check the mask extracts either the lower or upper half of vector
8328 // elements.
8329 int M1Start = -1;
8330 int M2Start = -1;
8331 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8332 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8333 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8334 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8335 return false;
8336
8337 return true;
8338}
8339
8340/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8341/// of the vector elements.
8342static bool areExtractExts(Value *Ext1, Value *Ext2) {
8343 auto areExtDoubled = [](Instruction *Ext) {
8344 return Ext->getType()->getScalarSizeInBits() ==
8345 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8346 };
8347
8348 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8349 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8350 !areExtDoubled(cast<Instruction>(Ext1)) ||
8351 !areExtDoubled(cast<Instruction>(Ext2)))
8352 return false;
8353
8354 return true;
8355}
8356
8357/// Check if sinking \p I's operands to I's basic block is profitable, because
8358/// the operands can be folded into a target instruction, e.g.
8359/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8360bool AArch64TargetLowering::shouldSinkOperands(
8361 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8362 if (!I->getType()->isVectorTy())
8363 return false;
8364
8365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8366 switch (II->getIntrinsicID()) {
8367 case Intrinsic::aarch64_neon_umull:
8368 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8369 return false;
8370 Ops.push_back(&II->getOperandUse(0));
8371 Ops.push_back(&II->getOperandUse(1));
8372 return true;
8373 default:
8374 return false;
8375 }
8376 }
8377
8378 switch (I->getOpcode()) {
8379 case Instruction::Sub:
8380 case Instruction::Add: {
8381 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8382 return false;
8383
8384 // If the exts' operands extract either the lower or upper elements, we
8385 // can sink them too.
8386 auto Ext1 = cast<Instruction>(I->getOperand(0));
8387 auto Ext2 = cast<Instruction>(I->getOperand(1));
8388 if (areExtractShuffleVectors(Ext1, Ext2)) {
8389 Ops.push_back(&Ext1->getOperandUse(0));
8390 Ops.push_back(&Ext2->getOperandUse(0));
8391 }
8392
8393 Ops.push_back(&I->getOperandUse(0));
8394 Ops.push_back(&I->getOperandUse(1));
8395
8396 return true;
8397 }
8398 default:
8399 return false;
8400 }
8401 return false;
8402}
8403
Tim Northover3b0846e2014-05-24 12:50:23 +00008404bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8405 unsigned &RequiredAligment) const {
8406 if (!LoadedType.isSimple() ||
8407 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8408 return false;
8409 // Cyclone supports unaligned accesses.
8410 RequiredAligment = 0;
8411 unsigned NumBits = LoadedType.getSizeInBits();
8412 return NumBits == 32 || NumBits == 64;
8413}
8414
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008415/// A helper function for determining the number of interleaved accesses we
8416/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008417unsigned
8418AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8419 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008420 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8421}
8422
Geoff Berryb1e87142017-07-14 21:44:12 +00008423MachineMemOperand::Flags
8424AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8425 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8426 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8427 return MOStridedAccess;
8428 return MachineMemOperand::MONone;
8429}
8430
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008431bool AArch64TargetLowering::isLegalInterleavedAccessType(
8432 VectorType *VecTy, const DataLayout &DL) const {
8433
8434 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8435 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8436
8437 // Ensure the number of vector elements is greater than 1.
8438 if (VecTy->getNumElements() < 2)
8439 return false;
8440
8441 // Ensure the element type is legal.
8442 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8443 return false;
8444
8445 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8446 // 128 will be split into multiple interleaved accesses.
8447 return VecSize == 64 || VecSize % 128 == 0;
8448}
8449
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008450/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008451///
8452/// E.g. Lower an interleaved load (Factor = 2):
8453/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8454/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8455/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8456///
8457/// Into:
8458/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8459/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8460/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8461bool AArch64TargetLowering::lowerInterleavedLoad(
8462 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8463 ArrayRef<unsigned> Indices, unsigned Factor) const {
8464 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8465 "Invalid interleave factor");
8466 assert(!Shuffles.empty() && "Empty shufflevector input");
8467 assert(Shuffles.size() == Indices.size() &&
8468 "Unmatched number of shufflevectors and indices");
8469
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008470 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008471
8472 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008473
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008474 // Skip if we do not have NEON and skip illegal vector types. We can
8475 // "legalize" wide vector types into multiple interleaved accesses as long as
8476 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008477 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008478 return false;
8479
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008480 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8481
Hao Liu7ec8ee32015-06-26 02:32:07 +00008482 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8483 // load integer vectors first and then convert to pointer vectors.
8484 Type *EltTy = VecTy->getVectorElementType();
8485 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008486 VecTy =
8487 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008488
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008489 IRBuilder<> Builder(LI);
8490
8491 // The base address of the load.
8492 Value *BaseAddr = LI->getPointerOperand();
8493
8494 if (NumLoads > 1) {
8495 // If we're going to generate more than one load, reset the sub-vector type
8496 // to something legal.
8497 VecTy = VectorType::get(VecTy->getVectorElementType(),
8498 VecTy->getVectorNumElements() / NumLoads);
8499
8500 // We will compute the pointer operand of each load from the original base
8501 // address using GEPs. Cast the base address to a pointer to the scalar
8502 // element type.
8503 BaseAddr = Builder.CreateBitCast(
8504 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8505 LI->getPointerAddressSpace()));
8506 }
8507
Hao Liu7ec8ee32015-06-26 02:32:07 +00008508 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8509 Type *Tys[2] = {VecTy, PtrTy};
8510 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8511 Intrinsic::aarch64_neon_ld3,
8512 Intrinsic::aarch64_neon_ld4};
8513 Function *LdNFunc =
8514 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8515
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008516 // Holds sub-vectors extracted from the load intrinsic return values. The
8517 // sub-vectors are associated with the shufflevector instructions they will
8518 // replace.
8519 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008520
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008521 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008522
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008523 // If we're generating more than one load, compute the base address of
8524 // subsequent loads as an offset from the previous.
8525 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008526 BaseAddr =
8527 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8528 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008529
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008530 CallInst *LdN = Builder.CreateCall(
8531 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008532
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008533 // Extract and store the sub-vectors returned by the load intrinsic.
8534 for (unsigned i = 0; i < Shuffles.size(); i++) {
8535 ShuffleVectorInst *SVI = Shuffles[i];
8536 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008537
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008538 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8539
8540 // Convert the integer vector to pointer vector if the element is pointer.
8541 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008542 SubVec = Builder.CreateIntToPtr(
8543 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8544 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008545 SubVecs[SVI].push_back(SubVec);
8546 }
8547 }
8548
8549 // Replace uses of the shufflevector instructions with the sub-vectors
8550 // returned by the load intrinsic. If a shufflevector instruction is
8551 // associated with more than one sub-vector, those sub-vectors will be
8552 // concatenated into a single wide vector.
8553 for (ShuffleVectorInst *SVI : Shuffles) {
8554 auto &SubVec = SubVecs[SVI];
8555 auto *WideVec =
8556 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8557 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008558 }
8559
8560 return true;
8561}
8562
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008563/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008564///
8565/// E.g. Lower an interleaved store (Factor = 3):
8566/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008567/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008568/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8569///
8570/// Into:
8571/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8572/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8573/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8574/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8575///
8576/// Note that the new shufflevectors will be removed and we'll only generate one
8577/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008578///
8579/// Example for a more general valid mask (Factor 3). Lower:
8580/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8581/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8582/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8583///
8584/// Into:
8585/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8586/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8587/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8588/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008589bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8590 ShuffleVectorInst *SVI,
8591 unsigned Factor) const {
8592 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8593 "Invalid interleave factor");
8594
8595 VectorType *VecTy = SVI->getType();
8596 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8597 "Invalid interleaved store");
8598
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008599 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008600 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008601 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008602
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008603 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008604
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008605 // Skip if we do not have NEON and skip illegal vector types. We can
8606 // "legalize" wide vector types into multiple interleaved accesses as long as
8607 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008608 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008609 return false;
8610
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008611 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8612
Hao Liu7ec8ee32015-06-26 02:32:07 +00008613 Value *Op0 = SVI->getOperand(0);
8614 Value *Op1 = SVI->getOperand(1);
8615 IRBuilder<> Builder(SI);
8616
8617 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8618 // vectors to integer vectors.
8619 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008620 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008621 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008622
8623 // Convert to the corresponding integer vector.
8624 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8625 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8626 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8627
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008628 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008629 }
8630
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008631 // The base address of the store.
8632 Value *BaseAddr = SI->getPointerOperand();
8633
8634 if (NumStores > 1) {
8635 // If we're going to generate more than one store, reset the lane length
8636 // and sub-vector type to something legal.
8637 LaneLen /= NumStores;
8638 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8639
8640 // We will compute the pointer operand of each store from the original base
8641 // address using GEPs. Cast the base address to a pointer to the scalar
8642 // element type.
8643 BaseAddr = Builder.CreateBitCast(
8644 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8645 SI->getPointerAddressSpace()));
8646 }
8647
8648 auto Mask = SVI->getShuffleMask();
8649
Hao Liu7ec8ee32015-06-26 02:32:07 +00008650 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8651 Type *Tys[2] = {SubVecTy, PtrTy};
8652 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8653 Intrinsic::aarch64_neon_st3,
8654 Intrinsic::aarch64_neon_st4};
8655 Function *StNFunc =
8656 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8657
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008658 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008659
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008660 SmallVector<Value *, 5> Ops;
8661
8662 // Split the shufflevector operands into sub vectors for the new stN call.
8663 for (unsigned i = 0; i < Factor; i++) {
8664 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8665 if (Mask[IdxI] >= 0) {
8666 Ops.push_back(Builder.CreateShuffleVector(
8667 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8668 } else {
8669 unsigned StartMask = 0;
8670 for (unsigned j = 1; j < LaneLen; j++) {
8671 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8672 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8673 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8674 break;
8675 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008676 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008677 // Note: Filling undef gaps with random elements is ok, since
8678 // those elements were being written anyway (with undefs).
8679 // In the case of all undefs we're defaulting to using elems from 0
8680 // Note: StartMask cannot be negative, it's checked in
8681 // isReInterleaveMask
8682 Ops.push_back(Builder.CreateShuffleVector(
8683 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008684 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008685 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008686
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008687 // If we generating more than one store, we compute the base address of
8688 // subsequent stores as an offset from the previous.
8689 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008690 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8691 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008692
8693 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8694 Builder.CreateCall(StNFunc, Ops);
8695 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008696 return true;
8697}
8698
Tim Northover3b0846e2014-05-24 12:50:23 +00008699static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8700 unsigned AlignCheck) {
8701 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8702 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8703}
8704
Sjoerd Meijer180f1ae2019-04-30 08:38:12 +00008705EVT AArch64TargetLowering::getOptimalMemOpType(
8706 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8707 bool ZeroMemset, bool MemcpyStrSrc,
8708 const AttributeList &FuncAttributes) const {
8709 bool CanImplicitFloat =
8710 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
JF Bastien29200612018-09-06 16:03:32 +00008711 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8712 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8713 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8714 // taken one instruction to materialize the v2i64 zero and one store (with
8715 // restrictive addressing mode). Just do i64 stores.
8716 bool IsSmallMemset = IsMemset && Size < 32;
8717 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8718 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8719 return true;
8720 bool Fast;
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00008721 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8722 &Fast) &&
8723 Fast;
JF Bastien29200612018-09-06 16:03:32 +00008724 };
8725
8726 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8727 AlignmentIsAcceptable(MVT::v2i64, 16))
8728 return MVT::v2i64;
8729 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008730 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008731 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008732 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008733 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008734 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008735 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008736}
8737
8738// 12-bit optionally shifted immediates are legal for adds.
8739bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008740 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008741 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8742 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008743 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008744 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008745 // Same encoding for add/sub, just flip the sign.
8746 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008747 bool IsLegal = ((Immed >> 12) == 0 ||
8748 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008749 LLVM_DEBUG(dbgs() << "Is " << Immed
8750 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008751 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008752}
8753
8754// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8755// immediates is the same as for an add or a sub.
8756bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008757 return isLegalAddImmediate(Immed);
8758}
8759
8760/// isLegalAddressingMode - Return true if the addressing mode represented
8761/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008762bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8763 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008764 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008765 // AArch64 has five basic addressing modes:
8766 // reg
8767 // reg + 9-bit signed offset
8768 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8769 // reg1 + reg2
8770 // reg + SIZE_IN_BYTES * reg
8771
8772 // No global is ever allowed as a base.
8773 if (AM.BaseGV)
8774 return false;
8775
8776 // No reg+reg+imm addressing.
8777 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8778 return false;
8779
8780 // check reg + imm case:
8781 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8782 uint64_t NumBytes = 0;
8783 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008784 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008785 NumBytes = NumBits / 8;
8786 if (!isPowerOf2_64(NumBits))
8787 NumBytes = 0;
8788 }
8789
8790 if (!AM.Scale) {
8791 int64_t Offset = AM.BaseOffs;
8792
8793 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008794 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008795 return true;
8796
8797 // 12-bit unsigned offset
8798 unsigned shift = Log2_64(NumBytes);
8799 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8800 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8801 (Offset >> shift) << shift == Offset)
8802 return true;
8803 return false;
8804 }
8805
8806 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8807
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008808 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008809}
8810
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008811bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8812 // Consider splitting large offset of struct or array.
8813 return true;
8814}
8815
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008816int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8817 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008818 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008819 // Scaling factors are not free at all.
8820 // Operands | Rt Latency
8821 // -------------------------------------------
8822 // Rt, [Xn, Xm] | 4
8823 // -------------------------------------------
8824 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8825 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008826 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008827 // Scale represents reg2 * scale, thus account for 1 if
8828 // it is not equal to 0 or 1.
8829 return AM.Scale != 0 && AM.Scale != 1;
8830 return -1;
8831}
8832
8833bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8834 VT = VT.getScalarType();
8835
8836 if (!VT.isSimple())
8837 return false;
8838
8839 switch (VT.getSimpleVT().SimpleTy) {
8840 case MVT::f32:
8841 case MVT::f64:
8842 return true;
8843 default:
8844 break;
8845 }
8846
8847 return false;
8848}
8849
8850const MCPhysReg *
8851AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8852 // LR is a callee-save register, but we must treat it as clobbered by any call
8853 // site. Hence we include LR in the scratch registers, which are in turn added
8854 // as implicit-defs for stackmaps and patchpoints.
8855 static const MCPhysReg ScratchRegs[] = {
8856 AArch64::X16, AArch64::X17, AArch64::LR, 0
8857 };
8858 return ScratchRegs;
8859}
8860
8861bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008862AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8863 CombineLevel Level) const {
8864 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008865 EVT VT = N->getValueType(0);
8866 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8867 // it with shift to let it be lowered to UBFX.
8868 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8869 isa<ConstantSDNode>(N->getOperand(1))) {
8870 uint64_t TruncMask = N->getConstantOperandVal(1);
8871 if (isMask_64(TruncMask) &&
8872 N->getOperand(0).getOpcode() == ISD::SRL &&
8873 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8874 return false;
8875 }
8876 return true;
8877}
8878
8879bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8880 Type *Ty) const {
8881 assert(Ty->isIntegerTy());
8882
8883 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8884 if (BitSize == 0)
8885 return false;
8886
8887 int64_t Val = Imm.getSExtValue();
8888 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8889 return true;
8890
8891 if ((int64_t)Val < 0)
8892 Val = ~Val;
8893 if (BitSize == 32)
8894 Val &= (1LL << 32) - 1;
8895
8896 unsigned LZ = countLeadingZeros((uint64_t)Val);
8897 unsigned Shift = (63 - LZ) / 16;
8898 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008899 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008900}
8901
Sebastian Pop41073e82018-03-06 16:54:55 +00008902bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8903 unsigned Index) const {
8904 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8905 return false;
8906
8907 return (Index == 0 || Index == ResVT.getVectorNumElements());
8908}
8909
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008910/// Turn vector tests of the signbit in the form of:
8911/// xor (sra X, elt_size(X)-1), -1
8912/// into:
8913/// cmge X, X, #0
8914static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8915 const AArch64Subtarget *Subtarget) {
8916 EVT VT = N->getValueType(0);
8917 if (!Subtarget->hasNEON() || !VT.isVector())
8918 return SDValue();
8919
8920 // There must be a shift right algebraic before the xor, and the xor must be a
8921 // 'not' operation.
8922 SDValue Shift = N->getOperand(0);
8923 SDValue Ones = N->getOperand(1);
8924 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8925 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8926 return SDValue();
8927
8928 // The shift should be smearing the sign bit across each vector element.
8929 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8930 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8931 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8932 return SDValue();
8933
8934 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8935}
8936
Tim Northover3b0846e2014-05-24 12:50:23 +00008937// Generate SUBS and CSEL for integer abs.
8938static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8939 EVT VT = N->getValueType(0);
8940
8941 SDValue N0 = N->getOperand(0);
8942 SDValue N1 = N->getOperand(1);
8943 SDLoc DL(N);
8944
8945 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8946 // and change it to SUB and CSEL.
8947 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8948 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8949 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8950 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8951 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008952 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008953 N0.getOperand(0));
8954 // Generate SUBS & CSEL.
8955 SDValue Cmp =
8956 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008957 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008958 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008959 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008960 SDValue(Cmp.getNode(), 1));
8961 }
8962 return SDValue();
8963}
8964
Tim Northover3b0846e2014-05-24 12:50:23 +00008965static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8966 TargetLowering::DAGCombinerInfo &DCI,
8967 const AArch64Subtarget *Subtarget) {
8968 if (DCI.isBeforeLegalizeOps())
8969 return SDValue();
8970
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008971 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8972 return Cmp;
8973
Tim Northover3b0846e2014-05-24 12:50:23 +00008974 return performIntegerAbsCombine(N, DAG);
8975}
8976
Chad Rosier17020f92014-07-23 14:57:52 +00008977SDValue
8978AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8979 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008980 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008981 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008982 if (isIntDivCheap(N->getValueType(0), Attr))
8983 return SDValue(N,0); // Lower SDIV as SDIV
8984
Chad Rosier17020f92014-07-23 14:57:52 +00008985 // fold (sdiv X, pow2)
8986 EVT VT = N->getValueType(0);
8987 if ((VT != MVT::i32 && VT != MVT::i64) ||
8988 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8989 return SDValue();
8990
8991 SDLoc DL(N);
8992 SDValue N0 = N->getOperand(0);
8993 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008994 SDValue Zero = DAG.getConstant(0, DL, VT);
8995 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008996
8997 // Add (N0 < 0) ? Pow2 - 1 : 0;
8998 SDValue CCVal;
8999 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9000 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9001 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9002
Craig Toppera568a272018-07-30 21:04:34 +00009003 Created.push_back(Cmp.getNode());
9004 Created.push_back(Add.getNode());
9005 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00009006
9007 // Divide by pow2.
9008 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009009 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00009010
9011 // If we're dividing by a positive value, we're done. Otherwise, we must
9012 // negate the result.
9013 if (Divisor.isNonNegative())
9014 return SRA;
9015
Craig Toppera568a272018-07-30 21:04:34 +00009016 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009017 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00009018}
9019
Tim Northover3b0846e2014-05-24 12:50:23 +00009020static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9021 TargetLowering::DAGCombinerInfo &DCI,
9022 const AArch64Subtarget *Subtarget) {
9023 if (DCI.isBeforeLegalizeOps())
9024 return SDValue();
9025
Chad Rosier31ee8132016-11-11 17:07:37 +00009026 // The below optimizations require a constant RHS.
9027 if (!isa<ConstantSDNode>(N->getOperand(1)))
9028 return SDValue();
9029
9030 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9031 const APInt &ConstValue = C->getAPIntValue();
9032
Tim Northover3b0846e2014-05-24 12:50:23 +00009033 // Multiplication of a power of two plus/minus one can be done more
9034 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9035 // future CPUs have a cheaper MADD instruction, this may need to be
9036 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9037 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009038 // More aggressively, some multiplications N0 * C can be lowered to
9039 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9040 // e.g. 6=3*2=(2+1)*2.
9041 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9042 // which equals to (1+2)*16-(1+2).
9043 SDValue N0 = N->getOperand(0);
9044 // TrailingZeroes is used to test if the mul can be lowered to
9045 // shift+add+shift.
9046 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9047 if (TrailingZeroes) {
9048 // Conservatively do not lower to shift+add+shift if the mul might be
9049 // folded into smul or umul.
9050 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9051 isZeroExtended(N0.getNode(), DAG)))
9052 return SDValue();
9053 // Conservatively do not lower to shift+add+shift if the mul might be
9054 // folded into madd or msub.
9055 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9056 N->use_begin()->getOpcode() == ISD::SUB))
9057 return SDValue();
9058 }
9059 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9060 // and shift+add+shift.
9061 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9062
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009063 unsigned ShiftAmt, AddSubOpc;
9064 // Is the shifted value the LHS operand of the add/sub?
9065 bool ShiftValUseIsN0 = true;
9066 // Do we need to negate the result?
9067 bool NegateResult = false;
9068
Chad Rosier31ee8132016-11-11 17:07:37 +00009069 if (ConstValue.isNonNegative()) {
9070 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009071 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009072 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9073 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009074 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009075 if (SCVMinus1.isPowerOf2()) {
9076 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009077 AddSubOpc = ISD::ADD;
9078 } else if (CVPlus1.isPowerOf2()) {
9079 ShiftAmt = CVPlus1.logBase2();
9080 AddSubOpc = ISD::SUB;
9081 } else
9082 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009083 } else {
9084 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009085 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009086 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009087 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009088 if (CVNegPlus1.isPowerOf2()) {
9089 ShiftAmt = CVNegPlus1.logBase2();
9090 AddSubOpc = ISD::SUB;
9091 ShiftValUseIsN0 = false;
9092 } else if (CVNegMinus1.isPowerOf2()) {
9093 ShiftAmt = CVNegMinus1.logBase2();
9094 AddSubOpc = ISD::ADD;
9095 NegateResult = true;
9096 } else
9097 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009098 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009099
9100 SDLoc DL(N);
9101 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009102 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009103 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9104
9105 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9106 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9107 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009108 assert(!(NegateResult && TrailingZeroes) &&
9109 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009110 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009111 if (NegateResult)
9112 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9113 // Shift the result.
9114 if (TrailingZeroes)
9115 return DAG.getNode(ISD::SHL, DL, VT, Res,
9116 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9117 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009118}
9119
Jim Grosbachf7502c42014-07-18 00:40:52 +00009120static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9121 SelectionDAG &DAG) {
9122 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9123 // optimize away operation when it's from a constant.
9124 //
9125 // The general transformation is:
9126 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9127 // AND(VECTOR_CMP(x,y), constant2)
9128 // constant2 = UNARYOP(constant)
9129
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009130 // Early exit if this isn't a vector operation, the operand of the
9131 // unary operation isn't a bitwise AND, or if the sizes of the operations
9132 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009133 EVT VT = N->getValueType(0);
9134 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009135 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9136 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009137 return SDValue();
9138
Jim Grosbach724e4382014-07-23 20:41:43 +00009139 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009140 // make the transformation for non-constant splats as well, but it's unclear
9141 // that would be a benefit as it would not eliminate any operations, just
9142 // perform one more step in scalar code before moving to the vector unit.
9143 if (BuildVectorSDNode *BV =
9144 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009145 // Bail out if the vector isn't a constant.
9146 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009147 return SDValue();
9148
9149 // Everything checks out. Build up the new and improved node.
9150 SDLoc DL(N);
9151 EVT IntVT = BV->getValueType(0);
9152 // Create a new constant of the appropriate type for the transformed
9153 // DAG.
9154 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9155 // The AND node needs bitcasts to/from an integer vector type around it.
9156 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9157 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9158 N->getOperand(0)->getOperand(0), MaskConst);
9159 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9160 return Res;
9161 }
9162
9163 return SDValue();
9164}
9165
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009166static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9167 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009168 // First try to optimize away the conversion when it's conditionally from
9169 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009170 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009171 return Res;
9172
Tim Northover3b0846e2014-05-24 12:50:23 +00009173 EVT VT = N->getValueType(0);
9174 if (VT != MVT::f32 && VT != MVT::f64)
9175 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009176
Tim Northover3b0846e2014-05-24 12:50:23 +00009177 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009178 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009179 return SDValue();
9180
9181 // If the result of an integer load is only used by an integer-to-float
9182 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009183 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009184 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009185 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009186 // Do not change the width of a volatile load.
9187 !cast<LoadSDNode>(N0)->isVolatile()) {
9188 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9189 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009190 LN0->getPointerInfo(), LN0->getAlignment(),
9191 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009192
9193 // Make sure successors of the original load stay after it by updating them
9194 // to use the new Chain.
9195 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9196
9197 unsigned Opcode =
9198 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9199 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9200 }
9201
9202 return SDValue();
9203}
9204
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009205/// Fold a floating-point multiply by power of two into floating-point to
9206/// fixed-point conversion.
9207static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009208 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009209 const AArch64Subtarget *Subtarget) {
9210 if (!Subtarget->hasNEON())
9211 return SDValue();
9212
Sam Parkera0bd6f82019-06-03 08:49:17 +00009213 if (!N->getValueType(0).isSimple())
9214 return SDValue();
9215
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009216 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009217 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9218 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009219 return SDValue();
9220
9221 SDValue ConstVec = Op->getOperand(1);
9222 if (!isa<BuildVectorSDNode>(ConstVec))
9223 return SDValue();
9224
9225 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9226 uint32_t FloatBits = FloatTy.getSizeInBits();
9227 if (FloatBits != 32 && FloatBits != 64)
9228 return SDValue();
9229
9230 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9231 uint32_t IntBits = IntTy.getSizeInBits();
9232 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9233 return SDValue();
9234
9235 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9236 if (IntBits > FloatBits)
9237 return SDValue();
9238
9239 BitVector UndefElements;
9240 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9241 int32_t Bits = IntBits == 64 ? 64 : 32;
9242 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9243 if (C == -1 || C == 0 || C > Bits)
9244 return SDValue();
9245
9246 MVT ResTy;
9247 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9248 switch (NumLanes) {
9249 default:
9250 return SDValue();
9251 case 2:
9252 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9253 break;
9254 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009255 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009256 break;
9257 }
9258
Silviu Barangafa00ba32016-08-08 13:13:57 +00009259 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9260 return SDValue();
9261
9262 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9263 "Illegal vector type after legalization");
9264
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009265 SDLoc DL(N);
9266 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9267 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9268 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9269 SDValue FixConv =
9270 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9271 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9272 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9273 // We can handle smaller integers by generating an extra trunc.
9274 if (IntBits < FloatBits)
9275 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9276
9277 return FixConv;
9278}
9279
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009280/// Fold a floating-point divide by power of two into fixed-point to
9281/// floating-point conversion.
9282static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009283 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009284 const AArch64Subtarget *Subtarget) {
9285 if (!Subtarget->hasNEON())
9286 return SDValue();
9287
9288 SDValue Op = N->getOperand(0);
9289 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009290 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9291 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009292 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9293 return SDValue();
9294
9295 SDValue ConstVec = N->getOperand(1);
9296 if (!isa<BuildVectorSDNode>(ConstVec))
9297 return SDValue();
9298
9299 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9300 int32_t IntBits = IntTy.getSizeInBits();
9301 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9302 return SDValue();
9303
9304 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9305 int32_t FloatBits = FloatTy.getSizeInBits();
9306 if (FloatBits != 32 && FloatBits != 64)
9307 return SDValue();
9308
9309 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9310 if (IntBits > FloatBits)
9311 return SDValue();
9312
9313 BitVector UndefElements;
9314 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9315 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9316 if (C == -1 || C == 0 || C > FloatBits)
9317 return SDValue();
9318
9319 MVT ResTy;
9320 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9321 switch (NumLanes) {
9322 default:
9323 return SDValue();
9324 case 2:
9325 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9326 break;
9327 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009328 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009329 break;
9330 }
9331
Tim Northover85cf5642016-08-26 18:52:31 +00009332 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9333 return SDValue();
9334
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009335 SDLoc DL(N);
9336 SDValue ConvInput = Op.getOperand(0);
9337 bool IsSigned = Opc == ISD::SINT_TO_FP;
9338 if (IntBits < FloatBits)
9339 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9340 ResTy, ConvInput);
9341
9342 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9343 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9344 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9345 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9346 DAG.getConstant(C, DL, MVT::i32));
9347}
9348
Tim Northover3b0846e2014-05-24 12:50:23 +00009349/// An EXTR instruction is made up of two shifts, ORed together. This helper
9350/// searches for and classifies those shifts.
9351static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9352 bool &FromHi) {
9353 if (N.getOpcode() == ISD::SHL)
9354 FromHi = false;
9355 else if (N.getOpcode() == ISD::SRL)
9356 FromHi = true;
9357 else
9358 return false;
9359
9360 if (!isa<ConstantSDNode>(N.getOperand(1)))
9361 return false;
9362
9363 ShiftAmount = N->getConstantOperandVal(1);
9364 Src = N->getOperand(0);
9365 return true;
9366}
9367
9368/// EXTR instruction extracts a contiguous chunk of bits from two existing
9369/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009370/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9371/// with an EXTR. Can't quite be done in TableGen because the two immediates
9372/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009373static SDValue tryCombineToEXTR(SDNode *N,
9374 TargetLowering::DAGCombinerInfo &DCI) {
9375 SelectionDAG &DAG = DCI.DAG;
9376 SDLoc DL(N);
9377 EVT VT = N->getValueType(0);
9378
9379 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9380
9381 if (VT != MVT::i32 && VT != MVT::i64)
9382 return SDValue();
9383
9384 SDValue LHS;
9385 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009386 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009387 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9388 return SDValue();
9389
9390 SDValue RHS;
9391 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009392 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009393 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9394 return SDValue();
9395
9396 // If they're both trying to come from the high part of the register, they're
9397 // not really an EXTR.
9398 if (LHSFromHi == RHSFromHi)
9399 return SDValue();
9400
9401 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9402 return SDValue();
9403
9404 if (LHSFromHi) {
9405 std::swap(LHS, RHS);
9406 std::swap(ShiftLHS, ShiftRHS);
9407 }
9408
9409 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009410 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009411}
9412
9413static SDValue tryCombineToBSL(SDNode *N,
9414 TargetLowering::DAGCombinerInfo &DCI) {
9415 EVT VT = N->getValueType(0);
9416 SelectionDAG &DAG = DCI.DAG;
9417 SDLoc DL(N);
9418
9419 if (!VT.isVector())
9420 return SDValue();
9421
9422 SDValue N0 = N->getOperand(0);
9423 if (N0.getOpcode() != ISD::AND)
9424 return SDValue();
9425
9426 SDValue N1 = N->getOperand(1);
9427 if (N1.getOpcode() != ISD::AND)
9428 return SDValue();
9429
9430 // We only have to look for constant vectors here since the general, variable
9431 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009432 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009433 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9434 for (int i = 1; i >= 0; --i)
9435 for (int j = 1; j >= 0; --j) {
9436 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9437 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9438 if (!BVN0 || !BVN1)
9439 continue;
9440
9441 bool FoundMatch = true;
9442 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9443 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9444 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9445 if (!CN0 || !CN1 ||
9446 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9447 FoundMatch = false;
9448 break;
9449 }
9450 }
9451
9452 if (FoundMatch)
9453 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9454 N0->getOperand(1 - i), N1->getOperand(1 - j));
9455 }
9456
9457 return SDValue();
9458}
9459
9460static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9461 const AArch64Subtarget *Subtarget) {
9462 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009463 SelectionDAG &DAG = DCI.DAG;
9464 EVT VT = N->getValueType(0);
9465
9466 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9467 return SDValue();
9468
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009469 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009470 return Res;
9471
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009472 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009473 return Res;
9474
9475 return SDValue();
9476}
9477
Nikita Popov1a261442019-03-15 21:04:34 +00009478static SDValue performANDCombine(SDNode *N,
9479 TargetLowering::DAGCombinerInfo &DCI) {
9480 SelectionDAG &DAG = DCI.DAG;
9481 SDValue LHS = N->getOperand(0);
9482 EVT VT = N->getValueType(0);
9483 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9484 return SDValue();
9485
9486 BuildVectorSDNode *BVN =
9487 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9488 if (!BVN)
9489 return SDValue();
9490
9491 // AND does not accept an immediate, so check if we can use a BIC immediate
9492 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9493 // pattern in isel, because some immediates may be lowered to the preferred
9494 // (and x, (movi imm)) form, even though an mvni representation also exists.
9495 APInt DefBits(VT.getSizeInBits(), 0);
9496 APInt UndefBits(VT.getSizeInBits(), 0);
9497 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9498 SDValue NewOp;
9499
9500 DefBits = ~DefBits;
9501 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9502 DefBits, &LHS)) ||
9503 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9504 DefBits, &LHS)))
9505 return NewOp;
9506
9507 UndefBits = ~UndefBits;
9508 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9509 UndefBits, &LHS)) ||
9510 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9511 UndefBits, &LHS)))
9512 return NewOp;
9513 }
9514
9515 return SDValue();
9516}
9517
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009518static SDValue performSRLCombine(SDNode *N,
9519 TargetLowering::DAGCombinerInfo &DCI) {
9520 SelectionDAG &DAG = DCI.DAG;
9521 EVT VT = N->getValueType(0);
9522 if (VT != MVT::i32 && VT != MVT::i64)
9523 return SDValue();
9524
9525 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9526 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9527 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9528 SDValue N0 = N->getOperand(0);
9529 if (N0.getOpcode() == ISD::BSWAP) {
9530 SDLoc DL(N);
9531 SDValue N1 = N->getOperand(1);
9532 SDValue N00 = N0.getOperand(0);
9533 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9534 uint64_t ShiftAmt = C->getZExtValue();
9535 if (VT == MVT::i32 && ShiftAmt == 16 &&
9536 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9537 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9538 if (VT == MVT::i64 && ShiftAmt == 32 &&
9539 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9540 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9541 }
9542 }
9543 return SDValue();
9544}
9545
Tim Northover3b0846e2014-05-24 12:50:23 +00009546static SDValue performBitcastCombine(SDNode *N,
9547 TargetLowering::DAGCombinerInfo &DCI,
9548 SelectionDAG &DAG) {
9549 // Wait 'til after everything is legalized to try this. That way we have
9550 // legal vector types and such.
9551 if (DCI.isBeforeLegalizeOps())
9552 return SDValue();
9553
9554 // Remove extraneous bitcasts around an extract_subvector.
9555 // For example,
9556 // (v4i16 (bitconvert
9557 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9558 // becomes
9559 // (extract_subvector ((v8i16 ...), (i64 4)))
9560
9561 // Only interested in 64-bit vectors as the ultimate result.
9562 EVT VT = N->getValueType(0);
9563 if (!VT.isVector())
9564 return SDValue();
9565 if (VT.getSimpleVT().getSizeInBits() != 64)
9566 return SDValue();
9567 // Is the operand an extract_subvector starting at the beginning or halfway
9568 // point of the vector? A low half may also come through as an
9569 // EXTRACT_SUBREG, so look for that, too.
9570 SDValue Op0 = N->getOperand(0);
9571 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9572 !(Op0->isMachineOpcode() &&
9573 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9574 return SDValue();
9575 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9576 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9577 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9578 return SDValue();
9579 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9580 if (idx != AArch64::dsub)
9581 return SDValue();
9582 // The dsub reference is equivalent to a lane zero subvector reference.
9583 idx = 0;
9584 }
9585 // Look through the bitcast of the input to the extract.
9586 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9587 return SDValue();
9588 SDValue Source = Op0->getOperand(0)->getOperand(0);
9589 // If the source type has twice the number of elements as our destination
9590 // type, we know this is an extract of the high or low half of the vector.
9591 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009592 if (!SVT.isVector() ||
9593 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009594 return SDValue();
9595
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009596 LLVM_DEBUG(
9597 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009598
9599 // Create the simplified form to just extract the low or high half of the
9600 // vector directly rather than bothering with the bitcasts.
9601 SDLoc dl(N);
9602 unsigned NumElements = VT.getVectorNumElements();
9603 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009604 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009605 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9606 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009607 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009608 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9609 Source, SubReg),
9610 0);
9611 }
9612}
9613
9614static SDValue performConcatVectorsCombine(SDNode *N,
9615 TargetLowering::DAGCombinerInfo &DCI,
9616 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009617 SDLoc dl(N);
9618 EVT VT = N->getValueType(0);
9619 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9620
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009621 // Optimize concat_vectors of truncated vectors, where the intermediate
9622 // type is illegal, to avoid said illegality, e.g.,
9623 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9624 // (v2i16 (truncate (v2i64)))))
9625 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009626 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9627 // (v4i32 (bitcast (v2i64))),
9628 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009629 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9630 // on both input and result type, so we might generate worse code.
9631 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9632 if (N->getNumOperands() == 2 &&
9633 N0->getOpcode() == ISD::TRUNCATE &&
9634 N1->getOpcode() == ISD::TRUNCATE) {
9635 SDValue N00 = N0->getOperand(0);
9636 SDValue N10 = N1->getOperand(0);
9637 EVT N00VT = N00.getValueType();
9638
9639 if (N00VT == N10.getValueType() &&
9640 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9641 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009642 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9643 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9644 for (size_t i = 0; i < Mask.size(); ++i)
9645 Mask[i] = i * 2;
9646 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9647 DAG.getVectorShuffle(
9648 MidVT, dl,
9649 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9650 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009651 }
9652 }
9653
Tim Northover3b0846e2014-05-24 12:50:23 +00009654 // Wait 'til after everything is legalized to try this. That way we have
9655 // legal vector types and such.
9656 if (DCI.isBeforeLegalizeOps())
9657 return SDValue();
9658
Tim Northover3b0846e2014-05-24 12:50:23 +00009659 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9660 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9661 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009662 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009663 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009664 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009665 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009666 }
9667
9668 // Canonicalise concat_vectors so that the right-hand vector has as few
9669 // bit-casts as possible before its real operation. The primary matching
9670 // destination for these operations will be the narrowing "2" instructions,
9671 // which depend on the operation being performed on this right-hand vector.
9672 // For example,
9673 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9674 // becomes
9675 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9676
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009677 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009678 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009679 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009680 MVT RHSTy = RHS.getValueType().getSimpleVT();
9681 // If the RHS is not a vector, this is not the pattern we're looking for.
9682 if (!RHSTy.isVector())
9683 return SDValue();
9684
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009685 LLVM_DEBUG(
9686 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009687
9688 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9689 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009690 return DAG.getNode(ISD::BITCAST, dl, VT,
9691 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9692 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9693 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009694}
9695
9696static SDValue tryCombineFixedPointConvert(SDNode *N,
9697 TargetLowering::DAGCombinerInfo &DCI,
9698 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009699 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009700 // legal vector types and such.
9701 if (DCI.isBeforeLegalizeOps())
9702 return SDValue();
9703 // Transform a scalar conversion of a value from a lane extract into a
9704 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9705 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9706 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9707 //
9708 // The second form interacts better with instruction selection and the
9709 // register allocator to avoid cross-class register copies that aren't
9710 // coalescable due to a lane reference.
9711
9712 // Check the operand and see if it originates from a lane extract.
9713 SDValue Op1 = N->getOperand(1);
9714 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9715 // Yep, no additional predication needed. Perform the transform.
9716 SDValue IID = N->getOperand(0);
9717 SDValue Shift = N->getOperand(2);
9718 SDValue Vec = Op1.getOperand(0);
9719 SDValue Lane = Op1.getOperand(1);
9720 EVT ResTy = N->getValueType(0);
9721 EVT VecResTy;
9722 SDLoc DL(N);
9723
9724 // The vector width should be 128 bits by the time we get here, even
9725 // if it started as 64 bits (the extract_vector handling will have
9726 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009727 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009728 "unexpected vector size on extract_vector_elt!");
9729 if (Vec.getValueType() == MVT::v4i32)
9730 VecResTy = MVT::v4f32;
9731 else if (Vec.getValueType() == MVT::v2i64)
9732 VecResTy = MVT::v2f64;
9733 else
Craig Topper2a30d782014-06-18 05:05:13 +00009734 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009735
9736 SDValue Convert =
9737 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9738 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9739 }
9740 return SDValue();
9741}
9742
9743// AArch64 high-vector "long" operations are formed by performing the non-high
9744// version on an extract_subvector of each operand which gets the high half:
9745//
9746// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9747//
9748// However, there are cases which don't have an extract_high explicitly, but
9749// have another operation that can be made compatible with one for free. For
9750// example:
9751//
9752// (dupv64 scalar) --> (extract_high (dup128 scalar))
9753//
9754// This routine does the actual conversion of such DUPs, once outer routines
9755// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009756// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9757// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009758static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009759 switch (N.getOpcode()) {
9760 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009761 case AArch64ISD::DUPLANE8:
9762 case AArch64ISD::DUPLANE16:
9763 case AArch64ISD::DUPLANE32:
9764 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009765 case AArch64ISD::MOVI:
9766 case AArch64ISD::MOVIshift:
9767 case AArch64ISD::MOVIedit:
9768 case AArch64ISD::MOVImsl:
9769 case AArch64ISD::MVNIshift:
9770 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009771 break;
9772 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009773 // FMOV could be supported, but isn't very useful, as it would only occur
9774 // if you passed a bitcast' floating point immediate to an eligible long
9775 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009776 return SDValue();
9777 }
9778
9779 MVT NarrowTy = N.getSimpleValueType();
9780 if (!NarrowTy.is64BitVector())
9781 return SDValue();
9782
9783 MVT ElementTy = NarrowTy.getVectorElementType();
9784 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009785 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009786
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009787 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009788 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9789 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009790 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009791}
9792
Eli Friedman29c06092019-02-08 00:23:35 +00009793static bool isEssentiallyExtractHighSubvector(SDValue N) {
9794 if (N.getOpcode() == ISD::BITCAST)
9795 N = N.getOperand(0);
9796 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9797 return false;
9798 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9799 N.getOperand(0).getValueType().getVectorNumElements() / 2;
Tim Northover3b0846e2014-05-24 12:50:23 +00009800}
9801
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009802/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009803struct GenericSetCCInfo {
9804 const SDValue *Opnd0;
9805 const SDValue *Opnd1;
9806 ISD::CondCode CC;
9807};
9808
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009809/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009810struct AArch64SetCCInfo {
9811 const SDValue *Cmp;
9812 AArch64CC::CondCode CC;
9813};
9814
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009815/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009816union SetCCInfo {
9817 GenericSetCCInfo Generic;
9818 AArch64SetCCInfo AArch64;
9819};
9820
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009821/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009822/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9823/// GenericSetCCInfo.
9824struct SetCCInfoAndKind {
9825 SetCCInfo Info;
9826 bool IsAArch64;
9827};
9828
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009829/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009830/// an
9831/// AArch64 lowered one.
9832/// \p SetCCInfo is filled accordingly.
9833/// \post SetCCInfo is meanginfull only when this function returns true.
9834/// \return True when Op is a kind of SET_CC operation.
9835static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9836 // If this is a setcc, this is straight forward.
9837 if (Op.getOpcode() == ISD::SETCC) {
9838 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9839 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9840 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9841 SetCCInfo.IsAArch64 = false;
9842 return true;
9843 }
9844 // Otherwise, check if this is a matching csel instruction.
9845 // In other words:
9846 // - csel 1, 0, cc
9847 // - csel 0, 1, !cc
9848 if (Op.getOpcode() != AArch64ISD::CSEL)
9849 return false;
9850 // Set the information about the operands.
9851 // TODO: we want the operands of the Cmp not the csel
9852 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9853 SetCCInfo.IsAArch64 = true;
9854 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9855 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9856
9857 // Check that the operands matches the constraints:
9858 // (1) Both operands must be constants.
9859 // (2) One must be 1 and the other must be 0.
9860 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9861 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9862
9863 // Check (1).
9864 if (!TValue || !FValue)
9865 return false;
9866
9867 // Check (2).
9868 if (!TValue->isOne()) {
9869 // Update the comparison when we are interested in !cc.
9870 std::swap(TValue, FValue);
9871 SetCCInfo.Info.AArch64.CC =
9872 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9873 }
9874 return TValue->isOne() && FValue->isNullValue();
9875}
9876
9877// Returns true if Op is setcc or zext of setcc.
9878static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9879 if (isSetCC(Op, Info))
9880 return true;
9881 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9882 isSetCC(Op->getOperand(0), Info));
9883}
9884
9885// The folding we want to perform is:
9886// (add x, [zext] (setcc cc ...) )
9887// -->
9888// (csel x, (add x, 1), !cc ...)
9889//
9890// The latter will get matched to a CSINC instruction.
9891static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9892 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9893 SDValue LHS = Op->getOperand(0);
9894 SDValue RHS = Op->getOperand(1);
9895 SetCCInfoAndKind InfoAndKind;
9896
9897 // If neither operand is a SET_CC, give up.
9898 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9899 std::swap(LHS, RHS);
9900 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9901 return SDValue();
9902 }
9903
9904 // FIXME: This could be generatized to work for FP comparisons.
9905 EVT CmpVT = InfoAndKind.IsAArch64
9906 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9907 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9908 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9909 return SDValue();
9910
9911 SDValue CCVal;
9912 SDValue Cmp;
9913 SDLoc dl(Op);
9914 if (InfoAndKind.IsAArch64) {
9915 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009916 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9917 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009918 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9919 } else
9920 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9921 *InfoAndKind.Info.Generic.Opnd1,
9922 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9923 CCVal, DAG, dl);
9924
9925 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009926 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009927 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9928}
9929
9930// The basic add/sub long vector instructions have variants with "2" on the end
9931// which act on the high-half of their inputs. They are normally matched by
9932// patterns like:
9933//
9934// (add (zeroext (extract_high LHS)),
9935// (zeroext (extract_high RHS)))
9936// -> uaddl2 vD, vN, vM
9937//
9938// However, if one of the extracts is something like a duplicate, this
9939// instruction can still be used profitably. This function puts the DAG into a
9940// more appropriate form for those patterns to trigger.
9941static SDValue performAddSubLongCombine(SDNode *N,
9942 TargetLowering::DAGCombinerInfo &DCI,
9943 SelectionDAG &DAG) {
9944 if (DCI.isBeforeLegalizeOps())
9945 return SDValue();
9946
9947 MVT VT = N->getSimpleValueType(0);
9948 if (!VT.is128BitVector()) {
9949 if (N->getOpcode() == ISD::ADD)
9950 return performSetccAddFolding(N, DAG);
9951 return SDValue();
9952 }
9953
9954 // Make sure both branches are extended in the same way.
9955 SDValue LHS = N->getOperand(0);
9956 SDValue RHS = N->getOperand(1);
9957 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9958 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9959 LHS.getOpcode() != RHS.getOpcode())
9960 return SDValue();
9961
9962 unsigned ExtType = LHS.getOpcode();
9963
9964 // It's not worth doing if at least one of the inputs isn't already an
9965 // extract, but we don't know which it'll be so we have to try both.
Eli Friedman29c06092019-02-08 00:23:35 +00009966 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009967 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9968 if (!RHS.getNode())
9969 return SDValue();
9970
9971 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
Eli Friedman29c06092019-02-08 00:23:35 +00009972 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009973 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9974 if (!LHS.getNode())
9975 return SDValue();
9976
9977 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9978 }
9979
9980 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9981}
9982
9983// Massage DAGs which we can use the high-half "long" operations on into
9984// something isel will recognize better. E.g.
9985//
9986// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9987// (aarch64_neon_umull (extract_high (v2i64 vec)))
9988// (extract_high (v2i64 (dup128 scalar)))))
9989//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009990static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009991 TargetLowering::DAGCombinerInfo &DCI,
9992 SelectionDAG &DAG) {
9993 if (DCI.isBeforeLegalizeOps())
9994 return SDValue();
9995
Hal Finkelcd8664c2015-12-11 23:11:52 +00009996 SDValue LHS = N->getOperand(1);
9997 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009998 assert(LHS.getValueType().is64BitVector() &&
9999 RHS.getValueType().is64BitVector() &&
10000 "unexpected shape for long operation");
10001
10002 // Either node could be a DUP, but it's not worth doing both of them (you'd
10003 // just as well use the non-high version) so look for a corresponding extract
10004 // operation on the other "wing".
Eli Friedman29c06092019-02-08 00:23:35 +000010005 if (isEssentiallyExtractHighSubvector(LHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010006 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10007 if (!RHS.getNode())
10008 return SDValue();
Eli Friedman29c06092019-02-08 00:23:35 +000010009 } else if (isEssentiallyExtractHighSubvector(RHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010010 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10011 if (!LHS.getNode())
10012 return SDValue();
10013 }
10014
Hal Finkelcd8664c2015-12-11 23:11:52 +000010015 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10016 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +000010017}
10018
10019static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10020 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10021 unsigned ElemBits = ElemTy.getSizeInBits();
10022
10023 int64_t ShiftAmount;
10024 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10025 APInt SplatValue, SplatUndef;
10026 unsigned SplatBitSize;
10027 bool HasAnyUndefs;
10028 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10029 HasAnyUndefs, ElemBits) ||
10030 SplatBitSize != ElemBits)
10031 return SDValue();
10032
10033 ShiftAmount = SplatValue.getSExtValue();
10034 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10035 ShiftAmount = CVN->getSExtValue();
10036 } else
10037 return SDValue();
10038
10039 unsigned Opcode;
10040 bool IsRightShift;
10041 switch (IID) {
10042 default:
10043 llvm_unreachable("Unknown shift intrinsic");
10044 case Intrinsic::aarch64_neon_sqshl:
10045 Opcode = AArch64ISD::SQSHL_I;
10046 IsRightShift = false;
10047 break;
10048 case Intrinsic::aarch64_neon_uqshl:
10049 Opcode = AArch64ISD::UQSHL_I;
10050 IsRightShift = false;
10051 break;
10052 case Intrinsic::aarch64_neon_srshl:
10053 Opcode = AArch64ISD::SRSHR_I;
10054 IsRightShift = true;
10055 break;
10056 case Intrinsic::aarch64_neon_urshl:
10057 Opcode = AArch64ISD::URSHR_I;
10058 IsRightShift = true;
10059 break;
10060 case Intrinsic::aarch64_neon_sqshlu:
10061 Opcode = AArch64ISD::SQSHLU_I;
10062 IsRightShift = false;
10063 break;
10064 }
10065
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010066 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10067 SDLoc dl(N);
10068 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10069 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10070 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10071 SDLoc dl(N);
10072 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10073 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10074 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010075
10076 return SDValue();
10077}
10078
10079// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10080// the intrinsics must be legal and take an i32, this means there's almost
10081// certainly going to be a zext in the DAG which we can eliminate.
10082static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10083 SDValue AndN = N->getOperand(2);
10084 if (AndN.getOpcode() != ISD::AND)
10085 return SDValue();
10086
10087 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10088 if (!CMask || CMask->getZExtValue() != Mask)
10089 return SDValue();
10090
10091 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10092 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10093}
10094
Ahmed Bougachafab58922015-03-10 20:45:38 +000010095static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10096 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010097 SDLoc dl(N);
10098 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10099 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +000010100 N->getOperand(1).getSimpleValueType(),
10101 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010102 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +000010103}
10104
Tim Northover3b0846e2014-05-24 12:50:23 +000010105static SDValue performIntrinsicCombine(SDNode *N,
10106 TargetLowering::DAGCombinerInfo &DCI,
10107 const AArch64Subtarget *Subtarget) {
10108 SelectionDAG &DAG = DCI.DAG;
10109 unsigned IID = getIntrinsicID(N);
10110 switch (IID) {
10111 default:
10112 break;
10113 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10114 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10115 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010116 case Intrinsic::aarch64_neon_saddv:
10117 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10118 case Intrinsic::aarch64_neon_uaddv:
10119 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10120 case Intrinsic::aarch64_neon_sminv:
10121 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10122 case Intrinsic::aarch64_neon_uminv:
10123 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10124 case Intrinsic::aarch64_neon_smaxv:
10125 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10126 case Intrinsic::aarch64_neon_umaxv:
10127 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010128 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010129 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010130 N->getOperand(1), N->getOperand(2));
10131 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010132 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010133 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010134 case Intrinsic::aarch64_neon_fmaxnm:
10135 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10136 N->getOperand(1), N->getOperand(2));
10137 case Intrinsic::aarch64_neon_fminnm:
10138 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10139 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010140 case Intrinsic::aarch64_neon_smull:
10141 case Intrinsic::aarch64_neon_umull:
10142 case Intrinsic::aarch64_neon_pmull:
10143 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010144 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010145 case Intrinsic::aarch64_neon_sqshl:
10146 case Intrinsic::aarch64_neon_uqshl:
10147 case Intrinsic::aarch64_neon_sqshlu:
10148 case Intrinsic::aarch64_neon_srshl:
10149 case Intrinsic::aarch64_neon_urshl:
10150 return tryCombineShiftImm(IID, N, DAG);
10151 case Intrinsic::aarch64_crc32b:
10152 case Intrinsic::aarch64_crc32cb:
10153 return tryCombineCRC32(0xff, N, DAG);
10154 case Intrinsic::aarch64_crc32h:
10155 case Intrinsic::aarch64_crc32ch:
10156 return tryCombineCRC32(0xffff, N, DAG);
10157 }
10158 return SDValue();
10159}
10160
10161static SDValue performExtendCombine(SDNode *N,
10162 TargetLowering::DAGCombinerInfo &DCI,
10163 SelectionDAG &DAG) {
10164 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10165 // we can convert that DUP into another extract_high (of a bigger DUP), which
10166 // helps the backend to decide that an sabdl2 would be useful, saving a real
10167 // extract_high operation.
10168 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010169 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010170 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010171 unsigned IID = getIntrinsicID(ABDNode);
10172 if (IID == Intrinsic::aarch64_neon_sabd ||
10173 IID == Intrinsic::aarch64_neon_uabd) {
10174 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10175 if (!NewABD.getNode())
10176 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010177
Hal Finkelcd8664c2015-12-11 23:11:52 +000010178 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10179 NewABD);
10180 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010181 }
10182
10183 // This is effectively a custom type legalization for AArch64.
10184 //
10185 // Type legalization will split an extend of a small, legal, type to a larger
10186 // illegal type by first splitting the destination type, often creating
10187 // illegal source types, which then get legalized in isel-confusing ways,
10188 // leading to really terrible codegen. E.g.,
10189 // %result = v8i32 sext v8i8 %value
10190 // becomes
10191 // %losrc = extract_subreg %value, ...
10192 // %hisrc = extract_subreg %value, ...
10193 // %lo = v4i32 sext v4i8 %losrc
10194 // %hi = v4i32 sext v4i8 %hisrc
10195 // Things go rapidly downhill from there.
10196 //
10197 // For AArch64, the [sz]ext vector instructions can only go up one element
10198 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10199 // take two instructions.
10200 //
10201 // This implies that the most efficient way to do the extend from v8i8
10202 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10203 // the normal splitting to happen for the v8i16->v8i32.
10204
10205 // This is pre-legalization to catch some cases where the default
10206 // type legalization will create ill-tempered code.
10207 if (!DCI.isBeforeLegalizeOps())
10208 return SDValue();
10209
10210 // We're only interested in cleaning things up for non-legal vector types
10211 // here. If both the source and destination are legal, things will just
10212 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010213 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010214 EVT ResVT = N->getValueType(0);
10215 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10216 return SDValue();
10217 // If the vector type isn't a simple VT, it's beyond the scope of what
10218 // we're worried about here. Let legalization do its thing and hope for
10219 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010220 SDValue Src = N->getOperand(0);
10221 EVT SrcVT = Src->getValueType(0);
10222 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010223 return SDValue();
10224
Tim Northover3b0846e2014-05-24 12:50:23 +000010225 // If the source VT is a 64-bit vector, we can play games and get the
10226 // better results we want.
10227 if (SrcVT.getSizeInBits() != 64)
10228 return SDValue();
10229
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010230 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010231 unsigned ElementCount = SrcVT.getVectorNumElements();
10232 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10233 SDLoc DL(N);
10234 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10235
10236 // Now split the rest of the operation into two halves, each with a 64
10237 // bit source.
10238 EVT LoVT, HiVT;
10239 SDValue Lo, Hi;
10240 unsigned NumElements = ResVT.getVectorNumElements();
10241 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10242 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10243 ResVT.getVectorElementType(), NumElements / 2);
10244
10245 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10246 LoVT.getVectorNumElements());
10247 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010248 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010249 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010250 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010251 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10252 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10253
10254 // Now combine the parts back together so we still have a single result
10255 // like the combiner expects.
10256 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10257}
10258
Geoff Berry8301c642016-11-16 19:35:19 +000010259static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10260 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010261 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010262 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010263 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010264
10265 // Create scalar stores. This is at least as good as the code sequence for a
10266 // split unaligned store which is a dup.s, ext.b, and two stores.
10267 // Most of the time the three stores should be replaced by store pair
10268 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010269 SDLoc DL(&St);
10270 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010271 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010272
John Brawn3a9c8422017-02-06 18:07:20 +000010273 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010274 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010275 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010276 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010277
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010278 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010279 if (BasePtr->getOpcode() == ISD::ADD &&
10280 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10281 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10282 BasePtr = BasePtr->getOperand(0);
10283 }
10284
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010285 unsigned Offset = EltOffset;
10286 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010287 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010288 SDValue OffsetPtr =
10289 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10290 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010291 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010292 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010293 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010294 Offset += EltOffset;
10295 }
10296 return NewST1;
10297}
10298
Geoff Berry526c5052016-11-14 19:39:04 +000010299/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10300/// load store optimizer pass will merge them to store pair stores. This should
10301/// be better than a movi to create the vector zero followed by a vector store
10302/// if the zero constant is not re-used, since one instructions and one register
10303/// live range will be removed.
10304///
10305/// For example, the final generated code should be:
10306///
10307/// stp xzr, xzr, [x0]
10308///
10309/// instead of:
10310///
10311/// movi v0.2d, #0
10312/// str q0, [x0]
10313///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010314static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10315 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010316 EVT VT = StVal.getValueType();
10317
Geoff Berry8301c642016-11-16 19:35:19 +000010318 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10319 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010320 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010321 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10322 VT.getVectorElementType().getSizeInBits() == 64) ||
10323 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10324 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010325 return SDValue();
10326
10327 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10328 return SDValue();
10329
10330 // If the zero constant has more than one use then the vector store could be
10331 // better since the constant mov will be amortized and stp q instructions
10332 // should be able to be formed.
10333 if (!StVal.hasOneUse())
10334 return SDValue();
10335
Tim Northover964eea72019-01-08 13:30:27 +000010336 // If the store is truncating then it's going down to i16 or smaller, which
10337 // means it can be implemented in a single store anyway.
10338 if (St.isTruncatingStore())
10339 return SDValue();
10340
Geoff Berry526c5052016-11-14 19:39:04 +000010341 // If the immediate offset of the address operand is too large for the stp
10342 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010343 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10344 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010345 if (Offset < -512 || Offset > 504)
10346 return SDValue();
10347 }
10348
10349 for (int I = 0; I < NumVecElts; ++I) {
10350 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010351 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010352 return SDValue();
10353 }
Geoff Berry8301c642016-11-16 19:35:19 +000010354
Geoff Berrybb23df92017-09-21 21:10:06 +000010355 // Use a CopyFromReg WZR/XZR here to prevent
10356 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10357 SDLoc DL(&St);
10358 unsigned ZeroReg;
10359 EVT ZeroVT;
10360 if (VT.getVectorElementType().getSizeInBits() == 32) {
10361 ZeroReg = AArch64::WZR;
10362 ZeroVT = MVT::i32;
10363 } else {
10364 ZeroReg = AArch64::XZR;
10365 ZeroVT = MVT::i64;
10366 }
10367 SDValue SplatVal =
10368 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010369 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010370}
10371
Tim Northover3b0846e2014-05-24 12:50:23 +000010372/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10373/// value. The load store optimizer pass will merge them to store pair stores.
10374/// This has better performance than a splat of the scalar followed by a split
10375/// vector store. Even if the stores are not merged it is four stores vs a dup,
10376/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010377static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10378 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010379 EVT VT = StVal.getValueType();
10380
10381 // Don't replace floating point stores, they possibly won't be transformed to
10382 // stp because of the store pair suppress pass.
10383 if (VT.isFloatingPoint())
10384 return SDValue();
10385
Tim Northover3b0846e2014-05-24 12:50:23 +000010386 // We can express a splat as store pair(s) for 2 or 4 elements.
10387 unsigned NumVecElts = VT.getVectorNumElements();
10388 if (NumVecElts != 4 && NumVecElts != 2)
10389 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010390
Tim Northover964eea72019-01-08 13:30:27 +000010391 // If the store is truncating then it's going down to i16 or smaller, which
10392 // means it can be implemented in a single store anyway.
10393 if (St.isTruncatingStore())
10394 return SDValue();
10395
Tim Northover3b0846e2014-05-24 12:50:23 +000010396 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010397 // Make sure that each of the relevant vector element locations are inserted
10398 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10399 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10400 SDValue SplatVal;
10401 for (unsigned I = 0; I < NumVecElts; ++I) {
10402 // Check for insert vector elements.
10403 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010404 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010405
10406 // Check that same value is inserted at each vector element.
10407 if (I == 0)
10408 SplatVal = StVal.getOperand(1);
10409 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010410 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010411
10412 // Check insert element index.
10413 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10414 if (!CIndex)
10415 return SDValue();
10416 uint64_t IndexVal = CIndex->getZExtValue();
10417 if (IndexVal >= NumVecElts)
10418 return SDValue();
10419 IndexNotInserted.reset(IndexVal);
10420
10421 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010422 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010423 // Check that all vector element locations were inserted to.
10424 if (IndexNotInserted.any())
10425 return SDValue();
10426
Geoff Berry8301c642016-11-16 19:35:19 +000010427 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010428}
10429
Geoff Berry8301c642016-11-16 19:35:19 +000010430static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10431 SelectionDAG &DAG,
10432 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010433
10434 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010435 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010436 return SDValue();
10437
Geoff Berry526c5052016-11-14 19:39:04 +000010438 SDValue StVal = S->getValue();
10439 EVT VT = StVal.getValueType();
10440 if (!VT.isVector())
10441 return SDValue();
10442
10443 // If we get a splat of zeros, convert this vector store to a store of
10444 // scalars. They will be merged into store pairs of xzr thereby removing one
10445 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010446 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010447 return ReplacedZeroSplat;
10448
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010449 // FIXME: The logic for deciding if an unaligned store should be split should
10450 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10451 // a call to that function here.
10452
Matthias Braun651cff42016-06-02 18:03:53 +000010453 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010454 return SDValue();
10455
Sanjay Patel924879a2015-08-04 15:49:57 +000010456 // Don't split at -Oz.
Evandro Menezes85bd3972019-04-04 22:40:06 +000010457 if (DAG.getMachineFunction().getFunction().hasMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010458 return SDValue();
10459
Tim Northover3b0846e2014-05-24 12:50:23 +000010460 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10461 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010462 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010463 return SDValue();
10464
10465 // Split unaligned 16B stores. They are terrible for performance.
10466 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10467 // extensions can use this to mark that it does not want splitting to happen
10468 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10469 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10470 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10471 S->getAlignment() <= 2)
10472 return SDValue();
10473
10474 // If we get a splat of a scalar convert this vector store to a store of
10475 // scalars. They will be merged into store pairs thereby removing two
10476 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010477 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010478 return ReplacedSplat;
10479
10480 SDLoc DL(S);
10481 unsigned NumElts = VT.getVectorNumElements() / 2;
10482 // Split VT into two.
10483 EVT HalfVT =
10484 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10485 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010486 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010487 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010488 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010489 SDValue BasePtr = S->getBasePtr();
10490 SDValue NewST1 =
10491 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010492 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010493 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010494 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010495 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010496 S->getPointerInfo(), S->getAlignment(),
10497 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010498}
10499
10500/// Target-specific DAG combine function for post-increment LD1 (lane) and
10501/// post-increment LD1R.
10502static SDValue performPostLD1Combine(SDNode *N,
10503 TargetLowering::DAGCombinerInfo &DCI,
10504 bool IsLaneOp) {
10505 if (DCI.isBeforeLegalizeOps())
10506 return SDValue();
10507
10508 SelectionDAG &DAG = DCI.DAG;
10509 EVT VT = N->getValueType(0);
10510
10511 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10512 SDNode *LD = N->getOperand(LoadIdx).getNode();
10513 // If it is not LOAD, can not do such combine.
10514 if (LD->getOpcode() != ISD::LOAD)
10515 return SDValue();
10516
Geoff Berry60460262018-05-11 16:25:06 +000010517 // The vector lane must be a constant in the LD1LANE opcode.
10518 SDValue Lane;
10519 if (IsLaneOp) {
10520 Lane = N->getOperand(2);
10521 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10522 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10523 return SDValue();
10524 }
10525
Tim Northover3b0846e2014-05-24 12:50:23 +000010526 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10527 EVT MemVT = LoadSDN->getMemoryVT();
10528 // Check if memory operand is the same type as the vector element.
10529 if (MemVT != VT.getVectorElementType())
10530 return SDValue();
10531
10532 // Check if there are other uses. If so, do not combine as it will introduce
10533 // an extra load.
10534 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10535 ++UI) {
10536 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10537 continue;
10538 if (*UI != N)
10539 return SDValue();
10540 }
10541
10542 SDValue Addr = LD->getOperand(1);
10543 SDValue Vector = N->getOperand(0);
10544 // Search for a use of the address operand that is an increment.
10545 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10546 Addr.getNode()->use_end(); UI != UE; ++UI) {
10547 SDNode *User = *UI;
10548 if (User->getOpcode() != ISD::ADD
10549 || UI.getUse().getResNo() != Addr.getResNo())
10550 continue;
10551
Tim Northover3b0846e2014-05-24 12:50:23 +000010552 // If the increment is a constant, it must match the memory ref size.
10553 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10554 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10555 uint32_t IncVal = CInc->getZExtValue();
10556 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10557 if (IncVal != NumBytes)
10558 continue;
10559 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10560 }
10561
Nirav Davee40e2bb2018-09-25 15:30:22 +000010562 // To avoid cycle construction make sure that neither the load nor the add
10563 // are predecessors to each other or the Vector.
10564 SmallPtrSet<const SDNode *, 32> Visited;
10565 SmallVector<const SDNode *, 16> Worklist;
10566 Visited.insert(N);
10567 Worklist.push_back(User);
10568 Worklist.push_back(LD);
10569 Worklist.push_back(Vector.getNode());
10570 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10571 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010572 continue;
10573
Tim Northover3b0846e2014-05-24 12:50:23 +000010574 SmallVector<SDValue, 8> Ops;
10575 Ops.push_back(LD->getOperand(0)); // Chain
10576 if (IsLaneOp) {
10577 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010578 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010579 }
10580 Ops.push_back(Addr);
10581 Ops.push_back(Inc);
10582
10583 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010584 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010585 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10586 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10587 MemVT,
10588 LoadSDN->getMemOperand());
10589
10590 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010591 SDValue NewResults[] = {
10592 SDValue(LD, 0), // The result of load
10593 SDValue(UpdN.getNode(), 2) // Chain
10594 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010595 DCI.CombineTo(LD, NewResults);
10596 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10597 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10598
10599 break;
10600 }
10601 return SDValue();
10602}
10603
Joel Jones7466ccf2017-07-10 22:11:50 +000010604/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010605/// address translation.
10606static bool performTBISimplification(SDValue Addr,
10607 TargetLowering::DAGCombinerInfo &DCI,
10608 SelectionDAG &DAG) {
10609 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010610 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010611 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10612 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010613 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010614 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010615 DCI.CommitTargetLoweringOpt(TLO);
10616 return true;
10617 }
10618 return false;
10619}
10620
10621static SDValue performSTORECombine(SDNode *N,
10622 TargetLowering::DAGCombinerInfo &DCI,
10623 SelectionDAG &DAG,
10624 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010625 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010626 return Split;
10627
10628 if (Subtarget->supportsAddressTopByteIgnored() &&
10629 performTBISimplification(N->getOperand(2), DCI, DAG))
10630 return SDValue(N, 0);
10631
10632 return SDValue();
10633}
10634
Chad Rosier6c36eff2015-09-03 18:13:57 +000010635
Tim Northover3b0846e2014-05-24 12:50:23 +000010636/// Target-specific DAG combine function for NEON load/store intrinsics
10637/// to merge base address updates.
10638static SDValue performNEONPostLDSTCombine(SDNode *N,
10639 TargetLowering::DAGCombinerInfo &DCI,
10640 SelectionDAG &DAG) {
10641 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10642 return SDValue();
10643
10644 unsigned AddrOpIdx = N->getNumOperands() - 1;
10645 SDValue Addr = N->getOperand(AddrOpIdx);
10646
10647 // Search for a use of the address operand that is an increment.
10648 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10649 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10650 SDNode *User = *UI;
10651 if (User->getOpcode() != ISD::ADD ||
10652 UI.getUse().getResNo() != Addr.getResNo())
10653 continue;
10654
10655 // Check that the add is independent of the load/store. Otherwise, folding
10656 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010657 SmallPtrSet<const SDNode *, 32> Visited;
10658 SmallVector<const SDNode *, 16> Worklist;
10659 Visited.insert(Addr.getNode());
10660 Worklist.push_back(N);
10661 Worklist.push_back(User);
10662 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10663 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010664 continue;
10665
10666 // Find the new opcode for the updating load/store.
10667 bool IsStore = false;
10668 bool IsLaneOp = false;
10669 bool IsDupOp = false;
10670 unsigned NewOpc = 0;
10671 unsigned NumVecs = 0;
10672 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10673 switch (IntNo) {
10674 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10675 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10676 NumVecs = 2; break;
10677 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10678 NumVecs = 3; break;
10679 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10680 NumVecs = 4; break;
10681 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10682 NumVecs = 2; IsStore = true; break;
10683 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10684 NumVecs = 3; IsStore = true; break;
10685 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10686 NumVecs = 4; IsStore = true; break;
10687 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10688 NumVecs = 2; break;
10689 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10690 NumVecs = 3; break;
10691 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10692 NumVecs = 4; break;
10693 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10694 NumVecs = 2; IsStore = true; break;
10695 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10696 NumVecs = 3; IsStore = true; break;
10697 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10698 NumVecs = 4; IsStore = true; break;
10699 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10700 NumVecs = 2; IsDupOp = true; break;
10701 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10702 NumVecs = 3; IsDupOp = true; break;
10703 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10704 NumVecs = 4; IsDupOp = true; break;
10705 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10706 NumVecs = 2; IsLaneOp = true; break;
10707 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10708 NumVecs = 3; IsLaneOp = true; break;
10709 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10710 NumVecs = 4; IsLaneOp = true; break;
10711 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10712 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10713 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10714 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10715 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10716 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10717 }
10718
10719 EVT VecTy;
10720 if (IsStore)
10721 VecTy = N->getOperand(2).getValueType();
10722 else
10723 VecTy = N->getValueType(0);
10724
10725 // If the increment is a constant, it must match the memory ref size.
10726 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10727 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10728 uint32_t IncVal = CInc->getZExtValue();
10729 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10730 if (IsLaneOp || IsDupOp)
10731 NumBytes /= VecTy.getVectorNumElements();
10732 if (IncVal != NumBytes)
10733 continue;
10734 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10735 }
10736 SmallVector<SDValue, 8> Ops;
10737 Ops.push_back(N->getOperand(0)); // Incoming chain
10738 // Load lane and store have vector list as input.
10739 if (IsLaneOp || IsStore)
10740 for (unsigned i = 2; i < AddrOpIdx; ++i)
10741 Ops.push_back(N->getOperand(i));
10742 Ops.push_back(Addr); // Base register
10743 Ops.push_back(Inc);
10744
10745 // Return Types.
10746 EVT Tys[6];
10747 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10748 unsigned n;
10749 for (n = 0; n < NumResultVecs; ++n)
10750 Tys[n] = VecTy;
10751 Tys[n++] = MVT::i64; // Type of write back register
10752 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010753 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010754
10755 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10756 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10757 MemInt->getMemoryVT(),
10758 MemInt->getMemOperand());
10759
10760 // Update the uses.
10761 std::vector<SDValue> NewResults;
10762 for (unsigned i = 0; i < NumResultVecs; ++i) {
10763 NewResults.push_back(SDValue(UpdN.getNode(), i));
10764 }
10765 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10766 DCI.CombineTo(N, NewResults);
10767 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10768
10769 break;
10770 }
10771 return SDValue();
10772}
10773
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010774// Checks to see if the value is the prescribed width and returns information
10775// about its extension mode.
10776static
10777bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10778 ExtType = ISD::NON_EXTLOAD;
10779 switch(V.getNode()->getOpcode()) {
10780 default:
10781 return false;
10782 case ISD::LOAD: {
10783 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10784 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10785 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10786 ExtType = LoadNode->getExtensionType();
10787 return true;
10788 }
10789 return false;
10790 }
10791 case ISD::AssertSext: {
10792 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10793 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10794 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10795 ExtType = ISD::SEXTLOAD;
10796 return true;
10797 }
10798 return false;
10799 }
10800 case ISD::AssertZext: {
10801 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10802 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10803 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10804 ExtType = ISD::ZEXTLOAD;
10805 return true;
10806 }
10807 return false;
10808 }
10809 case ISD::Constant:
10810 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010811 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10812 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010813 }
10814 }
10815
10816 return true;
10817}
10818
10819// This function does a whole lot of voodoo to determine if the tests are
10820// equivalent without and with a mask. Essentially what happens is that given a
10821// DAG resembling:
10822//
10823// +-------------+ +-------------+ +-------------+ +-------------+
10824// | Input | | AddConstant | | CompConstant| | CC |
10825// +-------------+ +-------------+ +-------------+ +-------------+
10826// | | | |
10827// V V | +----------+
10828// +-------------+ +----+ | |
10829// | ADD | |0xff| | |
10830// +-------------+ +----+ | |
10831// | | | |
10832// V V | |
10833// +-------------+ | |
10834// | AND | | |
10835// +-------------+ | |
10836// | | |
10837// +-----+ | |
10838// | | |
10839// V V V
10840// +-------------+
10841// | CMP |
10842// +-------------+
10843//
10844// The AND node may be safely removed for some combinations of inputs. In
10845// particular we need to take into account the extension type of the Input,
10846// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10847// width of the input (this can work for any width inputs, the above graph is
10848// specific to 8 bits.
10849//
10850// The specific equations were worked out by generating output tables for each
10851// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10852// problem was simplified by working with 4 bit inputs, which means we only
10853// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10854// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10855// patterns present in both extensions (0,7). For every distinct set of
10856// AddConstant and CompConstants bit patterns we can consider the masked and
10857// unmasked versions to be equivalent if the result of this function is true for
10858// all 16 distinct bit patterns of for the current extension type of Input (w0).
10859//
10860// sub w8, w0, w1
10861// and w10, w8, #0x0f
10862// cmp w8, w2
10863// cset w9, AArch64CC
10864// cmp w10, w2
10865// cset w11, AArch64CC
10866// cmp w9, w11
10867// cset w0, eq
10868// ret
10869//
10870// Since the above function shows when the outputs are equivalent it defines
10871// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10872// would be expensive to run during compiles. The equations below were written
10873// in a test harness that confirmed they gave equivalent outputs to the above
10874// for all inputs function, so they can be used determine if the removal is
10875// legal instead.
10876//
10877// isEquivalentMaskless() is the code for testing if the AND can be removed
10878// factored out of the DAG recognition as the DAG can take several forms.
10879
David Majnemere61e4bf2016-06-21 05:10:24 +000010880static bool isEquivalentMaskless(unsigned CC, unsigned width,
10881 ISD::LoadExtType ExtType, int AddConstant,
10882 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010883 // By being careful about our equations and only writing the in term
10884 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10885 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010886 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010887
10888 // For the purposes of these comparisons sign extending the type is
10889 // equivalent to zero extending the add and displacing it by half the integer
10890 // width. Provided we are careful and make sure our equations are valid over
10891 // the whole range we can just adjust the input and avoid writing equations
10892 // for sign extended inputs.
10893 if (ExtType == ISD::SEXTLOAD)
10894 AddConstant -= (1 << (width-1));
10895
10896 switch(CC) {
10897 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010898 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010899 if ((AddConstant == 0) ||
10900 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10901 (AddConstant >= 0 && CompConstant < 0) ||
10902 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10903 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010904 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010905 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010906 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010907 if ((AddConstant == 0) ||
10908 (AddConstant >= 0 && CompConstant <= 0) ||
10909 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10910 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010911 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010912 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010913 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010914 if ((AddConstant >= 0 && CompConstant < 0) ||
10915 (AddConstant <= 0 && CompConstant >= -1 &&
10916 CompConstant < AddConstant + MaxUInt))
10917 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010918 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010919 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010920 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010921 if ((AddConstant == 0) ||
10922 (AddConstant > 0 && CompConstant <= 0) ||
10923 (AddConstant < 0 && CompConstant <= AddConstant))
10924 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010925 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010926 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010927 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010928 if ((AddConstant >= 0 && CompConstant <= 0) ||
10929 (AddConstant <= 0 && CompConstant >= 0 &&
10930 CompConstant <= AddConstant + MaxUInt))
10931 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010932 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010933 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010934 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010935 if ((AddConstant > 0 && CompConstant < 0) ||
10936 (AddConstant < 0 && CompConstant >= 0 &&
10937 CompConstant < AddConstant + MaxUInt) ||
10938 (AddConstant >= 0 && CompConstant >= 0 &&
10939 CompConstant >= AddConstant) ||
10940 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010941 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010942 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010943 case AArch64CC::VS:
10944 case AArch64CC::VC:
10945 case AArch64CC::AL:
10946 case AArch64CC::NV:
10947 return true;
10948 case AArch64CC::Invalid:
10949 break;
10950 }
10951
10952 return false;
10953}
10954
10955static
10956SDValue performCONDCombine(SDNode *N,
10957 TargetLowering::DAGCombinerInfo &DCI,
10958 SelectionDAG &DAG, unsigned CCIndex,
10959 unsigned CmpIndex) {
10960 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10961 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10962 unsigned CondOpcode = SubsNode->getOpcode();
10963
10964 if (CondOpcode != AArch64ISD::SUBS)
10965 return SDValue();
10966
10967 // There is a SUBS feeding this condition. Is it fed by a mask we can
10968 // use?
10969
10970 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10971 unsigned MaskBits = 0;
10972
10973 if (AndNode->getOpcode() != ISD::AND)
10974 return SDValue();
10975
10976 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10977 uint32_t CNV = CN->getZExtValue();
10978 if (CNV == 255)
10979 MaskBits = 8;
10980 else if (CNV == 65535)
10981 MaskBits = 16;
10982 }
10983
10984 if (!MaskBits)
10985 return SDValue();
10986
10987 SDValue AddValue = AndNode->getOperand(0);
10988
10989 if (AddValue.getOpcode() != ISD::ADD)
10990 return SDValue();
10991
10992 // The basic dag structure is correct, grab the inputs and validate them.
10993
10994 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10995 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10996 SDValue SubsInputValue = SubsNode->getOperand(1);
10997
10998 // The mask is present and the provenance of all the values is a smaller type,
10999 // lets see if the mask is superfluous.
11000
11001 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11002 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11003 return SDValue();
11004
11005 ISD::LoadExtType ExtType;
11006
11007 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11008 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11009 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11010 return SDValue();
11011
11012 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11013 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11014 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11015 return SDValue();
11016
11017 // The AND is not necessary, remove it.
11018
11019 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11020 SubsNode->getValueType(1));
11021 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11022
11023 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11024 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11025
11026 return SDValue(N, 0);
11027}
11028
Tim Northover3b0846e2014-05-24 12:50:23 +000011029// Optimize compare with zero and branch.
11030static SDValue performBRCONDCombine(SDNode *N,
11031 TargetLowering::DAGCombinerInfo &DCI,
11032 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000011033 MachineFunction &MF = DAG.getMachineFunction();
11034 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11035 // will not be produced, as they are conditional branch instructions that do
11036 // not set flags.
11037 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11038 return SDValue();
11039
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000011040 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011041 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000011042 SDValue Chain = N->getOperand(0);
11043 SDValue Dest = N->getOperand(1);
11044 SDValue CCVal = N->getOperand(2);
11045 SDValue Cmp = N->getOperand(3);
11046
11047 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11048 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11049 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11050 return SDValue();
11051
11052 unsigned CmpOpc = Cmp.getOpcode();
11053 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11054 return SDValue();
11055
11056 // Only attempt folding if there is only one use of the flag and no use of the
11057 // value.
11058 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11059 return SDValue();
11060
11061 SDValue LHS = Cmp.getOperand(0);
11062 SDValue RHS = Cmp.getOperand(1);
11063
11064 assert(LHS.getValueType() == RHS.getValueType() &&
11065 "Expected the value type to be the same for both operands!");
11066 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11067 return SDValue();
11068
Artyom Skrobov314ee042015-11-25 19:41:11 +000011069 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011070 std::swap(LHS, RHS);
11071
Artyom Skrobov314ee042015-11-25 19:41:11 +000011072 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011073 return SDValue();
11074
11075 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11076 LHS.getOpcode() == ISD::SRL)
11077 return SDValue();
11078
11079 // Fold the compare into the branch instruction.
11080 SDValue BR;
11081 if (CC == AArch64CC::EQ)
11082 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11083 else
11084 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11085
11086 // Do not add new nodes to DAG combiner worklist.
11087 DCI.CombineTo(N, BR, false);
11088
11089 return SDValue();
11090}
11091
Geoff Berry9e934b02016-01-04 18:55:47 +000011092// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11093// as well as whether the test should be inverted. This code is required to
11094// catch these cases (as opposed to standard dag combines) because
11095// AArch64ISD::TBZ is matched during legalization.
11096static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11097 SelectionDAG &DAG) {
11098
11099 if (!Op->hasOneUse())
11100 return Op;
11101
11102 // We don't handle undef/constant-fold cases below, as they should have
11103 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11104 // etc.)
11105
11106 // (tbz (trunc x), b) -> (tbz x, b)
11107 // This case is just here to enable more of the below cases to be caught.
11108 if (Op->getOpcode() == ISD::TRUNCATE &&
11109 Bit < Op->getValueType(0).getSizeInBits()) {
11110 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11111 }
11112
Craig Topper35fe0792019-04-10 17:27:29 +000011113 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11114 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11115 Bit < Op->getOperand(0).getValueSizeInBits()) {
11116 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11117 }
11118
Geoff Berry9e934b02016-01-04 18:55:47 +000011119 if (Op->getNumOperands() != 2)
11120 return Op;
11121
11122 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11123 if (!C)
11124 return Op;
11125
11126 switch (Op->getOpcode()) {
11127 default:
11128 return Op;
11129
11130 // (tbz (and x, m), b) -> (tbz x, b)
11131 case ISD::AND:
11132 if ((C->getZExtValue() >> Bit) & 1)
11133 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11134 return Op;
11135
11136 // (tbz (shl x, c), b) -> (tbz x, b-c)
11137 case ISD::SHL:
11138 if (C->getZExtValue() <= Bit &&
11139 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11140 Bit = Bit - C->getZExtValue();
11141 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11142 }
11143 return Op;
11144
11145 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11146 case ISD::SRA:
11147 Bit = Bit + C->getZExtValue();
11148 if (Bit >= Op->getValueType(0).getSizeInBits())
11149 Bit = Op->getValueType(0).getSizeInBits() - 1;
11150 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11151
11152 // (tbz (srl x, c), b) -> (tbz x, b+c)
11153 case ISD::SRL:
11154 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11155 Bit = Bit + C->getZExtValue();
11156 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11157 }
11158 return Op;
11159
11160 // (tbz (xor x, -1), b) -> (tbnz x, b)
11161 case ISD::XOR:
11162 if ((C->getZExtValue() >> Bit) & 1)
11163 Invert = !Invert;
11164 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11165 }
11166}
11167
11168// Optimize test single bit zero/non-zero and branch.
11169static SDValue performTBZCombine(SDNode *N,
11170 TargetLowering::DAGCombinerInfo &DCI,
11171 SelectionDAG &DAG) {
11172 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11173 bool Invert = false;
11174 SDValue TestSrc = N->getOperand(1);
11175 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11176
11177 if (TestSrc == NewTestSrc)
11178 return SDValue();
11179
11180 unsigned NewOpc = N->getOpcode();
11181 if (Invert) {
11182 if (NewOpc == AArch64ISD::TBZ)
11183 NewOpc = AArch64ISD::TBNZ;
11184 else {
11185 assert(NewOpc == AArch64ISD::TBNZ);
11186 NewOpc = AArch64ISD::TBZ;
11187 }
11188 }
11189
11190 SDLoc DL(N);
11191 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11192 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11193}
11194
Tim Northover3b0846e2014-05-24 12:50:23 +000011195// vselect (v1i1 setcc) ->
11196// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11197// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11198// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11199// such VSELECT.
11200static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11201 SDValue N0 = N->getOperand(0);
11202 EVT CCVT = N0.getValueType();
11203
11204 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11205 CCVT.getVectorElementType() != MVT::i1)
11206 return SDValue();
11207
11208 EVT ResVT = N->getValueType(0);
11209 EVT CmpVT = N0.getOperand(0).getValueType();
11210 // Only combine when the result type is of the same size as the compared
11211 // operands.
11212 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11213 return SDValue();
11214
11215 SDValue IfTrue = N->getOperand(1);
11216 SDValue IfFalse = N->getOperand(2);
11217 SDValue SetCC =
11218 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11219 N0.getOperand(0), N0.getOperand(1),
11220 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11221 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11222 IfTrue, IfFalse);
11223}
11224
11225/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11226/// the compare-mask instructions rather than going via NZCV, even if LHS and
11227/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11228/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011229static SDValue performSelectCombine(SDNode *N,
11230 TargetLowering::DAGCombinerInfo &DCI) {
11231 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011232 SDValue N0 = N->getOperand(0);
11233 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011234
Ahmed Bougachac004c602015-04-27 21:43:12 +000011235 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011236 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011237
Ahmed Bougachac004c602015-04-27 21:43:12 +000011238 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11239 // scalar SetCCResultType. We also don't expect vectors, because we assume
11240 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11241 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11242 "Scalar-SETCC feeding SELECT has unexpected result type!");
11243
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011244 // If NumMaskElts == 0, the comparison is larger than select result. The
11245 // largest real NEON comparison is 64-bits per lane, which means the result is
11246 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011247 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011248
11249 // Don't try to do this optimization when the setcc itself has i1 operands.
11250 // There are no legal vectors of i1, so this would be pointless.
11251 if (SrcVT == MVT::i1)
11252 return SDValue();
11253
Tim Northover3c0915e2014-08-29 15:34:58 +000011254 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011255 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011256 return SDValue();
11257
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011258 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011259 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11260
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011261 // Also bail out if the vector CCVT isn't the same size as ResVT.
11262 // This can happen if the SETCC operand size doesn't divide the ResVT size
11263 // (e.g., f64 vs v3f32).
11264 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11265 return SDValue();
11266
Ahmed Bougachac004c602015-04-27 21:43:12 +000011267 // Make sure we didn't create illegal types, if we're not supposed to.
11268 assert(DCI.isBeforeLegalize() ||
11269 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11270
Tim Northover3b0846e2014-05-24 12:50:23 +000011271 // First perform a vector comparison, where lane 0 is the one we're interested
11272 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011273 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011274 SDValue LHS =
11275 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11276 SDValue RHS =
11277 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11278 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11279
11280 // Now duplicate the comparison mask we want across all other lanes.
11281 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011282 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011283 Mask = DAG.getNode(ISD::BITCAST, DL,
11284 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011285
11286 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11287}
11288
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011289/// Get rid of unnecessary NVCASTs (that don't change the type).
11290static SDValue performNVCASTCombine(SDNode *N) {
11291 if (N->getValueType(0) == N->getOperand(0).getValueType())
11292 return N->getOperand(0);
11293
11294 return SDValue();
11295}
11296
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011297// If all users of the globaladdr are of the form (globaladdr + constant), find
11298// the smallest constant, fold it into the globaladdr's offset and rewrite the
11299// globaladdr as (globaladdr + constant) - constant.
11300static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11301 const AArch64Subtarget *Subtarget,
11302 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011303 auto *GN = cast<GlobalAddressSDNode>(N);
11304 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11305 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011306 return SDValue();
11307
11308 uint64_t MinOffset = -1ull;
11309 for (SDNode *N : GN->uses()) {
11310 if (N->getOpcode() != ISD::ADD)
11311 return SDValue();
11312 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11313 if (!C)
11314 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11315 if (!C)
11316 return SDValue();
11317 MinOffset = std::min(MinOffset, C->getZExtValue());
11318 }
11319 uint64_t Offset = MinOffset + GN->getOffset();
11320
11321 // Require that the new offset is larger than the existing one. Otherwise, we
11322 // can end up oscillating between two possible DAGs, for example,
11323 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11324 if (Offset <= uint64_t(GN->getOffset()))
11325 return SDValue();
11326
11327 // Check whether folding this offset is legal. It must not go out of bounds of
11328 // the referenced object to avoid violating the code model, and must be
11329 // smaller than 2^21 because this is the largest offset expressible in all
11330 // object formats.
11331 //
11332 // This check also prevents us from folding negative offsets, which will end
11333 // up being treated in the same way as large positive ones. They could also
11334 // cause code model violations, and aren't really common enough to matter.
11335 if (Offset >= (1 << 21))
11336 return SDValue();
11337
11338 const GlobalValue *GV = GN->getGlobal();
11339 Type *T = GV->getValueType();
11340 if (!T->isSized() ||
11341 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11342 return SDValue();
11343
11344 SDLoc DL(GN);
11345 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11346 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11347 DAG.getConstant(MinOffset, DL, MVT::i64));
11348}
11349
Tim Northover3b0846e2014-05-24 12:50:23 +000011350SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11351 DAGCombinerInfo &DCI) const {
11352 SelectionDAG &DAG = DCI.DAG;
11353 switch (N->getOpcode()) {
11354 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011355 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011356 break;
11357 case ISD::ADD:
11358 case ISD::SUB:
11359 return performAddSubLongCombine(N, DCI, DAG);
11360 case ISD::XOR:
11361 return performXorCombine(N, DAG, DCI, Subtarget);
11362 case ISD::MUL:
11363 return performMulCombine(N, DAG, DCI, Subtarget);
11364 case ISD::SINT_TO_FP:
11365 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011366 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011367 case ISD::FP_TO_SINT:
11368 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011369 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011370 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011371 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011372 case ISD::OR:
11373 return performORCombine(N, DCI, Subtarget);
Nikita Popov1a261442019-03-15 21:04:34 +000011374 case ISD::AND:
11375 return performANDCombine(N, DCI);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011376 case ISD::SRL:
11377 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011378 case ISD::INTRINSIC_WO_CHAIN:
11379 return performIntrinsicCombine(N, DCI, Subtarget);
11380 case ISD::ANY_EXTEND:
11381 case ISD::ZERO_EXTEND:
11382 case ISD::SIGN_EXTEND:
11383 return performExtendCombine(N, DCI, DAG);
11384 case ISD::BITCAST:
11385 return performBitcastCombine(N, DCI, DAG);
11386 case ISD::CONCAT_VECTORS:
11387 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011388 case ISD::SELECT:
11389 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011390 case ISD::VSELECT:
11391 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011392 case ISD::LOAD:
11393 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11394 return SDValue(N, 0);
11395 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011396 case ISD::STORE:
11397 return performSTORECombine(N, DCI, DAG, Subtarget);
11398 case AArch64ISD::BRCOND:
11399 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011400 case AArch64ISD::TBNZ:
11401 case AArch64ISD::TBZ:
11402 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011403 case AArch64ISD::CSEL:
11404 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011405 case AArch64ISD::DUP:
11406 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011407 case AArch64ISD::NVCAST:
11408 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011409 case ISD::INSERT_VECTOR_ELT:
11410 return performPostLD1Combine(N, DCI, true);
11411 case ISD::INTRINSIC_VOID:
11412 case ISD::INTRINSIC_W_CHAIN:
11413 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11414 case Intrinsic::aarch64_neon_ld2:
11415 case Intrinsic::aarch64_neon_ld3:
11416 case Intrinsic::aarch64_neon_ld4:
11417 case Intrinsic::aarch64_neon_ld1x2:
11418 case Intrinsic::aarch64_neon_ld1x3:
11419 case Intrinsic::aarch64_neon_ld1x4:
11420 case Intrinsic::aarch64_neon_ld2lane:
11421 case Intrinsic::aarch64_neon_ld3lane:
11422 case Intrinsic::aarch64_neon_ld4lane:
11423 case Intrinsic::aarch64_neon_ld2r:
11424 case Intrinsic::aarch64_neon_ld3r:
11425 case Intrinsic::aarch64_neon_ld4r:
11426 case Intrinsic::aarch64_neon_st2:
11427 case Intrinsic::aarch64_neon_st3:
11428 case Intrinsic::aarch64_neon_st4:
11429 case Intrinsic::aarch64_neon_st1x2:
11430 case Intrinsic::aarch64_neon_st1x3:
11431 case Intrinsic::aarch64_neon_st1x4:
11432 case Intrinsic::aarch64_neon_st2lane:
11433 case Intrinsic::aarch64_neon_st3lane:
11434 case Intrinsic::aarch64_neon_st4lane:
11435 return performNEONPostLDSTCombine(N, DCI, DAG);
11436 default:
11437 break;
11438 }
Reid Klecknereb568942018-11-01 18:02:27 +000011439 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011440 case ISD::GlobalAddress:
11441 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011442 }
11443 return SDValue();
11444}
11445
11446// Check if the return value is used as only a return value, as otherwise
11447// we can't perform a tail-call. In particular, we need to check for
11448// target ISD nodes that are returns and any other "odd" constructs
11449// that the generic analysis code won't necessarily catch.
11450bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11451 SDValue &Chain) const {
11452 if (N->getNumValues() != 1)
11453 return false;
11454 if (!N->hasNUsesOfValue(1, 0))
11455 return false;
11456
11457 SDValue TCChain = Chain;
11458 SDNode *Copy = *N->use_begin();
11459 if (Copy->getOpcode() == ISD::CopyToReg) {
11460 // If the copy has a glue operand, we conservatively assume it isn't safe to
11461 // perform a tail call.
11462 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11463 MVT::Glue)
11464 return false;
11465 TCChain = Copy->getOperand(0);
11466 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11467 return false;
11468
11469 bool HasRet = false;
11470 for (SDNode *Node : Copy->uses()) {
11471 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11472 return false;
11473 HasRet = true;
11474 }
11475
11476 if (!HasRet)
11477 return false;
11478
11479 Chain = TCChain;
11480 return true;
11481}
11482
11483// Return whether the an instruction can potentially be optimized to a tail
11484// call. This will cause the optimizers to attempt to move, or duplicate,
11485// return instructions to help enable tail call optimizations for this
11486// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011487bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011488 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011489}
11490
11491bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11492 SDValue &Offset,
11493 ISD::MemIndexedMode &AM,
11494 bool &IsInc,
11495 SelectionDAG &DAG) const {
11496 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11497 return false;
11498
11499 Base = Op->getOperand(0);
11500 // All of the indexed addressing mode instructions take a signed
11501 // 9 bit immediate offset.
11502 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011503 int64_t RHSC = RHS->getSExtValue();
11504 if (Op->getOpcode() == ISD::SUB)
11505 RHSC = -(uint64_t)RHSC;
11506 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011507 return false;
11508 IsInc = (Op->getOpcode() == ISD::ADD);
11509 Offset = Op->getOperand(1);
11510 return true;
11511 }
11512 return false;
11513}
11514
11515bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11516 SDValue &Offset,
11517 ISD::MemIndexedMode &AM,
11518 SelectionDAG &DAG) const {
11519 EVT VT;
11520 SDValue Ptr;
11521 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11522 VT = LD->getMemoryVT();
11523 Ptr = LD->getBasePtr();
11524 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11525 VT = ST->getMemoryVT();
11526 Ptr = ST->getBasePtr();
11527 } else
11528 return false;
11529
11530 bool IsInc;
11531 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11532 return false;
11533 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11534 return true;
11535}
11536
11537bool AArch64TargetLowering::getPostIndexedAddressParts(
11538 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11539 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11540 EVT VT;
11541 SDValue Ptr;
11542 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11543 VT = LD->getMemoryVT();
11544 Ptr = LD->getBasePtr();
11545 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11546 VT = ST->getMemoryVT();
11547 Ptr = ST->getBasePtr();
11548 } else
11549 return false;
11550
11551 bool IsInc;
11552 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11553 return false;
11554 // Post-indexing updates the base, so it's not a valid transform
11555 // if that's not the same as the load's pointer.
11556 if (Ptr != Base)
11557 return false;
11558 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11559 return true;
11560}
11561
Tim Northoverf8bfe212014-07-18 13:07:05 +000011562static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11563 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011564 SDLoc DL(N);
11565 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011566
11567 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11568 return;
11569
Tim Northoverf8bfe212014-07-18 13:07:05 +000011570 Op = SDValue(
11571 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11572 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011573 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011574 0);
11575 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11576 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11577}
11578
Charlie Turner434d4592015-10-16 15:38:25 +000011579static void ReplaceReductionResults(SDNode *N,
11580 SmallVectorImpl<SDValue> &Results,
11581 SelectionDAG &DAG, unsigned InterOp,
11582 unsigned AcrossOp) {
11583 EVT LoVT, HiVT;
11584 SDValue Lo, Hi;
11585 SDLoc dl(N);
11586 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11587 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11588 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11589 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11590 Results.push_back(SplitVal);
11591}
11592
Tim Northover2f32e7f2016-08-04 19:32:28 +000011593static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11594 SDLoc DL(N);
11595 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11596 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11597 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11598 DAG.getConstant(64, DL, MVT::i64)));
11599 return std::make_pair(Lo, Hi);
11600}
11601
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011602// Create an even/odd pair of X registers holding integer value V.
11603static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11604 SDLoc dl(V.getNode());
11605 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11606 SDValue VHi = DAG.getAnyExtOrTrunc(
11607 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11608 dl, MVT::i64);
11609 if (DAG.getDataLayout().isBigEndian())
11610 std::swap (VLo, VHi);
11611 SDValue RegClass =
11612 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11613 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11614 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11615 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11616 return SDValue(
11617 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11618}
11619
Tim Northovercdf15292016-04-14 17:03:29 +000011620static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011621 SmallVectorImpl<SDValue> &Results,
11622 SelectionDAG &DAG,
11623 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011624 assert(N->getValueType(0) == MVT::i128 &&
11625 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011626
11627 if (Subtarget->hasLSE()) {
11628 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11629 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11630 SDValue Ops[] = {
11631 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11632 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11633 N->getOperand(1), // Ptr
11634 N->getOperand(0), // Chain in
11635 };
11636
Chandler Carruth66654b72018-08-14 23:30:32 +000011637 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011638
11639 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011640 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011641 case AtomicOrdering::Monotonic:
11642 Opcode = AArch64::CASPX;
11643 break;
11644 case AtomicOrdering::Acquire:
11645 Opcode = AArch64::CASPAX;
11646 break;
11647 case AtomicOrdering::Release:
11648 Opcode = AArch64::CASPLX;
11649 break;
11650 case AtomicOrdering::AcquireRelease:
11651 case AtomicOrdering::SequentiallyConsistent:
11652 Opcode = AArch64::CASPALX;
11653 break;
11654 default:
11655 llvm_unreachable("Unexpected ordering!");
11656 }
11657
11658 MachineSDNode *CmpSwap = DAG.getMachineNode(
11659 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011660 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011661
11662 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11663 if (DAG.getDataLayout().isBigEndian())
11664 std::swap(SubReg1, SubReg2);
11665 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11666 SDValue(CmpSwap, 0)));
11667 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11668 SDValue(CmpSwap, 0)));
11669 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11670 return;
11671 }
11672
Tim Northover2f32e7f2016-08-04 19:32:28 +000011673 auto Desired = splitInt128(N->getOperand(2), DAG);
11674 auto New = splitInt128(N->getOperand(3), DAG);
11675 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11676 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011677 SDNode *CmpSwap = DAG.getMachineNode(
11678 AArch64::CMP_SWAP_128, SDLoc(N),
11679 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11680
Chandler Carruth66654b72018-08-14 23:30:32 +000011681 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11682 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011683
11684 Results.push_back(SDValue(CmpSwap, 0));
11685 Results.push_back(SDValue(CmpSwap, 1));
11686 Results.push_back(SDValue(CmpSwap, 3));
11687}
11688
Tim Northover3b0846e2014-05-24 12:50:23 +000011689void AArch64TargetLowering::ReplaceNodeResults(
11690 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11691 switch (N->getOpcode()) {
11692 default:
11693 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011694 case ISD::BITCAST:
11695 ReplaceBITCASTResults(N, Results, DAG);
11696 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011697 case ISD::VECREDUCE_ADD:
11698 case ISD::VECREDUCE_SMAX:
11699 case ISD::VECREDUCE_SMIN:
11700 case ISD::VECREDUCE_UMAX:
11701 case ISD::VECREDUCE_UMIN:
11702 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11703 return;
11704
Charlie Turner434d4592015-10-16 15:38:25 +000011705 case AArch64ISD::SADDV:
11706 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11707 return;
11708 case AArch64ISD::UADDV:
11709 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11710 return;
11711 case AArch64ISD::SMINV:
11712 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11713 return;
11714 case AArch64ISD::UMINV:
11715 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11716 return;
11717 case AArch64ISD::SMAXV:
11718 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11719 return;
11720 case AArch64ISD::UMAXV:
11721 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11722 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011723 case ISD::FP_TO_UINT:
11724 case ISD::FP_TO_SINT:
11725 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11726 // Let normal code take care of it by not adding anything to Results.
11727 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011728 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011729 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011730 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011731 }
11732}
11733
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011734bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011735 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11736 return TargetLowering::useLoadStackGuardNode();
11737 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011738}
11739
Sanjay Patel1dd15592015-07-28 23:05:48 +000011740unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011741 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11742 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011743 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011744}
11745
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011746TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011747AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011748 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11749 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011750 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11751 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011752 return TypeWidenVector;
11753
11754 return TargetLoweringBase::getPreferredVectorAction(VT);
11755}
11756
Robin Morisseted3d48f2014-09-03 21:29:59 +000011757// Loads and stores less than 128-bits are already atomic; ones above that
11758// are doomed anyway, so defer to the default libcall and blame the OS when
11759// things go wrong.
11760bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11761 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11762 return Size == 128;
11763}
11764
11765// Loads and stores less than 128-bits are already atomic; ones above that
11766// are doomed anyway, so defer to the default libcall and blame the OS when
11767// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011768TargetLowering::AtomicExpansionKind
11769AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011770 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011771 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011772}
11773
11774// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011775TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011776AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011777 if (AI->isFloatingPointOperation())
11778 return AtomicExpansionKind::CmpXChg;
11779
Robin Morisseted3d48f2014-09-03 21:29:59 +000011780 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011781 if (Size > 128) return AtomicExpansionKind::None;
11782 // Nand not supported in LSE.
11783 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011784 // Leave 128 bits to LLSC.
11785 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011786}
11787
Alex Bradbury79518b02018-09-19 14:51:42 +000011788TargetLowering::AtomicExpansionKind
11789AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011790 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011791 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011792 if (Subtarget->hasLSE())
11793 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011794 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11795 // implement cmpxchg without spilling. If the address being exchanged is also
11796 // on the stack and close enough to the spill slot, this can lead to a
11797 // situation where the monitor always gets cleared and the atomic operation
11798 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011799 if (getTargetMachine().getOptLevel() == 0)
11800 return AtomicExpansionKind::None;
11801 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011802}
11803
Tim Northover3b0846e2014-05-24 12:50:23 +000011804Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11805 AtomicOrdering Ord) const {
11806 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11807 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011808 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011809
11810 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11811 // intrinsic must return {i64, i64} and we have to recombine them into a
11812 // single i128 here.
11813 if (ValTy->getPrimitiveSizeInBits() == 128) {
11814 Intrinsic::ID Int =
11815 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011816 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011817
11818 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11819 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11820
11821 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11822 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11823 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11824 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11825 return Builder.CreateOr(
11826 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11827 }
11828
11829 Type *Tys[] = { Addr->getType() };
11830 Intrinsic::ID Int =
11831 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011832 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011833
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011834 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11835
11836 const DataLayout &DL = M->getDataLayout();
11837 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11838 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11839
11840 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011841}
11842
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011843void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11844 IRBuilder<> &Builder) const {
11845 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011846 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011847}
11848
Tim Northover3b0846e2014-05-24 12:50:23 +000011849Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11850 Value *Val, Value *Addr,
11851 AtomicOrdering Ord) const {
11852 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011853 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011854
11855 // Since the intrinsics must have legal type, the i128 intrinsics take two
11856 // parameters: "i64, i64". We must marshal Val into the appropriate form
11857 // before the call.
11858 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11859 Intrinsic::ID Int =
11860 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11861 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11862 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11863
11864 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11865 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11866 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011867 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011868 }
11869
11870 Intrinsic::ID Int =
11871 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11872 Type *Tys[] = { Addr->getType() };
11873 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11874
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011875 const DataLayout &DL = M->getDataLayout();
11876 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11877 Val = Builder.CreateBitCast(Val, IntValTy);
11878
David Blaikieff6409d2015-05-18 22:13:54 +000011879 return Builder.CreateCall(Stxr,
11880 {Builder.CreateZExtOrBitCast(
11881 Val, Stxr->getFunctionType()->getParamType(0)),
11882 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011883}
Tim Northover3c55cca2014-11-27 21:02:42 +000011884
11885bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11886 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11887 return Ty->isArrayTy();
11888}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011889
11890bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11891 EVT) const {
11892 return false;
11893}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011894
Petr Hoseka7d59162017-02-24 03:10:10 +000011895static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011896 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11897 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011898 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011899 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000011900 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11901 Offset),
11902 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011903}
11904
Petr Hoseka7d59162017-02-24 03:10:10 +000011905Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11906 // Android provides a fixed TLS slot for the stack cookie. See the definition
11907 // of TLS_SLOT_STACK_GUARD in
11908 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11909 if (Subtarget->isTargetAndroid())
11910 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011911
Petr Hoseka7d59162017-02-24 03:10:10 +000011912 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011913 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011914 if (Subtarget->isTargetFuchsia())
11915 return UseTlsOffset(IRB, -0x10);
11916
11917 return TargetLowering::getIRStackGuard(IRB);
11918}
11919
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011920void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11921 // MSVC CRT provides functionalities for stack protection.
11922 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11923 // MSVC CRT has a global variable holding security cookie.
11924 M.getOrInsertGlobal("__security_cookie",
11925 Type::getInt8PtrTy(M.getContext()));
11926
11927 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000011928 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11929 "__security_check_cookie", Type::getVoidTy(M.getContext()),
11930 Type::getInt8PtrTy(M.getContext()));
11931 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
11932 F->setCallingConv(CallingConv::Win64);
11933 F->addAttribute(1, Attribute::AttrKind::InReg);
11934 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011935 return;
11936 }
11937 TargetLowering::insertSSPDeclarations(M);
11938}
11939
11940Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11941 // MSVC CRT has a global variable holding security cookie.
11942 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11943 return M.getGlobalVariable("__security_cookie");
11944 return TargetLowering::getSDagStackGuard(M);
11945}
11946
James Y Knight7976eb52019-02-01 20:43:25 +000011947Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011948 // MSVC CRT has a function to validate security cookie.
11949 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11950 return M.getFunction("__security_check_cookie");
11951 return TargetLowering::getSSPStackGuardCheck(M);
11952}
11953
Petr Hoseka7d59162017-02-24 03:10:10 +000011954Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011955 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11956 // definition of TLS_SLOT_SAFESTACK in
11957 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011958 if (Subtarget->isTargetAndroid())
11959 return UseTlsOffset(IRB, 0x48);
11960
11961 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011962 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011963 if (Subtarget->isTargetFuchsia())
11964 return UseTlsOffset(IRB, -0x8);
11965
11966 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011967}
Manman Rencbe4f942015-12-16 21:04:19 +000011968
Geoff Berry5d534b62017-02-21 18:53:14 +000011969bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11970 const Instruction &AndI) const {
11971 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11972 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11973 // may be beneficial to sink in other cases, but we would have to check that
11974 // the cmp would not get folded into the br to form a cbz for these to be
11975 // beneficial.
11976 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11977 if (!Mask)
11978 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011979 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011980}
11981
Manman Rencbe4f942015-12-16 21:04:19 +000011982void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11983 // Update IsSplitCSR in AArch64unctionInfo.
11984 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11985 AFI->setIsSplitCSR(true);
11986}
11987
11988void AArch64TargetLowering::insertCopiesSplitCSR(
11989 MachineBasicBlock *Entry,
11990 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11991 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11992 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11993 if (!IStart)
11994 return;
11995
11996 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11997 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011998 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011999 for (const MCPhysReg *I = IStart; *I; ++I) {
12000 const TargetRegisterClass *RC = nullptr;
12001 if (AArch64::GPR64RegClass.contains(*I))
12002 RC = &AArch64::GPR64RegClass;
12003 else if (AArch64::FPR64RegClass.contains(*I))
12004 RC = &AArch64::FPR64RegClass;
12005 else
12006 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12007
12008 unsigned NewVR = MRI->createVirtualRegister(RC);
12009 // Create copy from CSR to a virtual register.
12010 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12011 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12012 // nounwind. If we want to generalize this later, we may need to emit
12013 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000012014 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000012015 Attribute::NoUnwind) &&
12016 "Function should be nounwind in insertCopiesSplitCSR!");
12017 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000012018 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000012019 .addReg(*I);
12020
Manman Ren4632e8e2016-01-15 20:13:28 +000012021 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000012022 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000012023 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12024 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000012025 .addReg(NewVR);
12026 }
12027}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012028
Reid Klecknerb5180542017-03-21 16:57:19 +000012029bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012030 // Integer division on AArch64 is expensive. However, when aggressively
12031 // optimizing for code size, we prefer to use a div instruction, as it is
12032 // usually smaller than the alternative sequence.
12033 // The exception to this is vector division. Since AArch64 doesn't have vector
12034 // integer division, leaving the division as-is is a loss even in terms of
12035 // size, because it will have to be scalarized, while the alternative code
12036 // sequence can be performed in vector form.
12037 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000012038 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012039 return OptSize && !VT.isVector();
12040}
Tim Northoverf19d4672017-02-08 17:57:20 +000012041
Joel Jones07150922018-01-25 21:55:39 +000012042bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12043 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12044}
12045
Tim Northoverf19d4672017-02-08 17:57:20 +000012046unsigned
12047AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000012048 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000012049 return getPointerTy(DL).getSizeInBits();
12050
12051 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12052}
Matthias Braun5c290dc2018-01-19 03:16:36 +000012053
12054void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12055 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12056 TargetLoweringBase::finalizeLowering(MF);
12057}
Eli Friedmanad1151c2018-11-09 23:33:30 +000012058
12059// Unlike X86, we let frame lowering assign offsets to all catch objects.
12060bool AArch64TargetLowering::needsFixedCatchObjects() const {
12061 return false;
12062}