blob: 658cc5b6b2ec7fd558f015a85f1d21b4e84a2c64 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AArch64TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +000013#include "AArch64ExpandImm.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000018#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000020#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000021#include "Utils/AArch64BaseInfo.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/STLExtras.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000026#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000027#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000028#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000032#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000033#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000035#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000036#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000039#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000041#include "llvm/CodeGen/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000044#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000046#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000047#include "llvm/IR/Attributes.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000052#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000054#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000055#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000056#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
Florian Hahn3b251962019-02-05 10:27:40 +000058#include "llvm/IR/IntrinsicInst.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000059#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000060#include "llvm/IR/Module.h"
61#include "llvm/IR/OperandTraits.h"
Florian Hahn3b251962019-02-05 10:27:40 +000062#include "llvm/IR/PatternMatch.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000063#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000064#include "llvm/IR/Use.h"
65#include "llvm/IR/Value.h"
66#include "llvm/MC/MCRegisterInfo.h"
67#include "llvm/Support/Casting.h"
68#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000069#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000070#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000071#include "llvm/Support/Debug.h"
72#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000073#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000074#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000075#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000076#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000077#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000078#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000079#include <algorithm>
80#include <bitset>
81#include <cassert>
82#include <cctype>
83#include <cstdint>
84#include <cstdlib>
85#include <iterator>
86#include <limits>
87#include <tuple>
88#include <utility>
89#include <vector>
90
Tim Northover3b0846e2014-05-24 12:50:23 +000091using namespace llvm;
Florian Hahn3b251962019-02-05 10:27:40 +000092using namespace llvm::PatternMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +000093
94#define DEBUG_TYPE "aarch64-lower"
95
96STATISTIC(NumTailCalls, "Number of tail calls");
97STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000098STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000099
Tim Northover3b0846e2014-05-24 12:50:23 +0000100static cl::opt<bool>
101EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +0000102 cl::desc("Allow AArch64 SLI/SRI formation"),
103 cl::init(false));
104
105// FIXME: The necessary dtprel relocations don't seem to be supported
106// well in the GNU bfd and gold linkers at the moment. Therefore, by
107// default, for now, fall back to GeneralDynamic code generation.
108cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109 "aarch64-elf-ldtls-generation", cl::Hidden,
110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000112
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000113static cl::opt<bool>
114EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
115 cl::desc("Enable AArch64 logical imm instruction "
116 "optimization"),
117 cl::init(true));
118
Matthias Braunaf7d7702015-07-16 20:02:37 +0000119/// Value type used for condition codes.
120static const MVT MVT_CC = MVT::i32;
121
Eric Christopher905f12d2015-01-29 00:19:42 +0000122AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
123 const AArch64Subtarget &STI)
124 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126 // we have to make something up. Arbitrarily, choose ZeroOrOne.
127 setBooleanContents(ZeroOrOneBooleanContent);
128 // When comparing vectors the result sets the different elements in the
129 // vector to all-one or all-zero.
130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
131
132 // Set up the register classes.
133 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
134 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
135
136 if (Subtarget->hasFPARMv8()) {
137 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
138 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
139 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
140 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
141 }
142
143 if (Subtarget->hasNEON()) {
144 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
145 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
146 // Someone set us up the NEON.
147 addDRTypeForNEON(MVT::v2f32);
148 addDRTypeForNEON(MVT::v8i8);
149 addDRTypeForNEON(MVT::v4i16);
150 addDRTypeForNEON(MVT::v2i32);
151 addDRTypeForNEON(MVT::v1i64);
152 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000153 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000154
155 addQRTypeForNEON(MVT::v4f32);
156 addQRTypeForNEON(MVT::v2f64);
157 addQRTypeForNEON(MVT::v16i8);
158 addQRTypeForNEON(MVT::v8i16);
159 addQRTypeForNEON(MVT::v4i32);
160 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000161 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000162 }
163
164 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000165 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000166
167 // Provide all sorts of operation actions
168 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
169 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
170 setOperationAction(ISD::SETCC, MVT::i32, Custom);
171 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000172 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000173 setOperationAction(ISD::SETCC, MVT::f32, Custom);
174 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000175 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
176 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000177 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
178 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
179 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000180 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000181 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
182 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
183 setOperationAction(ISD::SELECT, MVT::i32, Custom);
184 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000185 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 setOperationAction(ISD::SELECT, MVT::f32, Custom);
187 setOperationAction(ISD::SELECT, MVT::f64, Custom);
188 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
189 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000190 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
192 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000193 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
195
196 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
197 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
198 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
199
200 setOperationAction(ISD::FREM, MVT::f32, Expand);
201 setOperationAction(ISD::FREM, MVT::f64, Expand);
202 setOperationAction(ISD::FREM, MVT::f80, Expand);
203
Amara Emersone27d5012018-04-10 19:01:58 +0000204 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
205
Tim Northover3b0846e2014-05-24 12:50:23 +0000206 // Custom lowering hooks are needed for XOR
207 // to fold it into CSINC/CSINV.
208 setOperationAction(ISD::XOR, MVT::i32, Custom);
209 setOperationAction(ISD::XOR, MVT::i64, Custom);
210
211 // Virtually no operation on f128 is legal, but LLVM can't expand them when
212 // there's a valid register class, so we need custom operations in most cases.
213 setOperationAction(ISD::FABS, MVT::f128, Expand);
214 setOperationAction(ISD::FADD, MVT::f128, Custom);
215 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
216 setOperationAction(ISD::FCOS, MVT::f128, Expand);
217 setOperationAction(ISD::FDIV, MVT::f128, Custom);
218 setOperationAction(ISD::FMA, MVT::f128, Expand);
219 setOperationAction(ISD::FMUL, MVT::f128, Custom);
220 setOperationAction(ISD::FNEG, MVT::f128, Expand);
221 setOperationAction(ISD::FPOW, MVT::f128, Expand);
222 setOperationAction(ISD::FREM, MVT::f128, Expand);
223 setOperationAction(ISD::FRINT, MVT::f128, Expand);
224 setOperationAction(ISD::FSIN, MVT::f128, Expand);
225 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
226 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
227 setOperationAction(ISD::FSUB, MVT::f128, Custom);
228 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
229 setOperationAction(ISD::SETCC, MVT::f128, Custom);
230 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
231 setOperationAction(ISD::SELECT, MVT::f128, Custom);
232 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
233 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
234
235 // Lowering for many of the conversions is actually specified by the non-f128
236 // type. The LowerXXX function will be trivial when f128 isn't involved.
237 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
238 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
239 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
240 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
241 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
242 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
243 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
244 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
245 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
246 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
247 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
248 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
249 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
250 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
251
252 // Variable arguments.
253 setOperationAction(ISD::VASTART, MVT::Other, Custom);
254 setOperationAction(ISD::VAARG, MVT::Other, Custom);
255 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
256 setOperationAction(ISD::VAEND, MVT::Other, Expand);
257
258 // Variable-sized objects.
259 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
260 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000261
262 if (Subtarget->isTargetWindows())
263 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
264 else
265 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000266
Tim Northover3b0846e2014-05-24 12:50:23 +0000267 // Constant pool entries
268 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
269
270 // BlockAddress
271 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
272
273 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
274 setOperationAction(ISD::ADDC, MVT::i32, Custom);
275 setOperationAction(ISD::ADDE, MVT::i32, Custom);
276 setOperationAction(ISD::SUBC, MVT::i32, Custom);
277 setOperationAction(ISD::SUBE, MVT::i32, Custom);
278 setOperationAction(ISD::ADDC, MVT::i64, Custom);
279 setOperationAction(ISD::ADDE, MVT::i64, Custom);
280 setOperationAction(ISD::SUBC, MVT::i64, Custom);
281 setOperationAction(ISD::SUBE, MVT::i64, Custom);
282
283 // AArch64 lacks both left-rotate and popcount instructions.
284 setOperationAction(ISD::ROTL, MVT::i32, Expand);
285 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000286 for (MVT VT : MVT::vector_valuetypes()) {
287 setOperationAction(ISD::ROTL, VT, Expand);
288 setOperationAction(ISD::ROTR, VT, Expand);
289 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000290
291 // AArch64 doesn't have {U|S}MUL_LOHI.
292 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
293 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
294
Tim Northover3b0846e2014-05-24 12:50:23 +0000295 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
296 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
297
298 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
299 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000300 for (MVT VT : MVT::vector_valuetypes()) {
301 setOperationAction(ISD::SDIVREM, VT, Expand);
302 setOperationAction(ISD::UDIVREM, VT, Expand);
303 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000304 setOperationAction(ISD::SREM, MVT::i32, Expand);
305 setOperationAction(ISD::SREM, MVT::i64, Expand);
306 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
307 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
308 setOperationAction(ISD::UREM, MVT::i32, Expand);
309 setOperationAction(ISD::UREM, MVT::i64, Expand);
310
311 // Custom lower Add/Sub/Mul with overflow.
312 setOperationAction(ISD::SADDO, MVT::i32, Custom);
313 setOperationAction(ISD::SADDO, MVT::i64, Custom);
314 setOperationAction(ISD::UADDO, MVT::i32, Custom);
315 setOperationAction(ISD::UADDO, MVT::i64, Custom);
316 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
317 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
318 setOperationAction(ISD::USUBO, MVT::i32, Custom);
319 setOperationAction(ISD::USUBO, MVT::i64, Custom);
320 setOperationAction(ISD::SMULO, MVT::i32, Custom);
321 setOperationAction(ISD::SMULO, MVT::i64, Custom);
322 setOperationAction(ISD::UMULO, MVT::i32, Custom);
323 setOperationAction(ISD::UMULO, MVT::i64, Custom);
324
325 setOperationAction(ISD::FSIN, MVT::f32, Expand);
326 setOperationAction(ISD::FSIN, MVT::f64, Expand);
327 setOperationAction(ISD::FCOS, MVT::f32, Expand);
328 setOperationAction(ISD::FCOS, MVT::f64, Expand);
329 setOperationAction(ISD::FPOW, MVT::f32, Expand);
330 setOperationAction(ISD::FPOW, MVT::f64, Expand);
331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000333 if (Subtarget->hasFullFP16())
334 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
335 else
336 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000337
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000338 setOperationAction(ISD::FREM, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000339 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
340 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000341 setOperationAction(ISD::FPOW, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000342 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
343 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000344 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000345 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
346 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000347 setOperationAction(ISD::FCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000348 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
349 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000350 setOperationAction(ISD::FSIN, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000351 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
352 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000353 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000354 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
355 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000356 setOperationAction(ISD::FEXP, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000357 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
358 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000359 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000360 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
361 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000362 setOperationAction(ISD::FLOG, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000363 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
364 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000365 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000366 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
367 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000368 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000369 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
370 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000371
372 if (!Subtarget->hasFullFP16()) {
373 setOperationAction(ISD::SELECT, MVT::f16, Promote);
374 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
375 setOperationAction(ISD::SETCC, MVT::f16, Promote);
376 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
377 setOperationAction(ISD::FADD, MVT::f16, Promote);
378 setOperationAction(ISD::FSUB, MVT::f16, Promote);
379 setOperationAction(ISD::FMUL, MVT::f16, Promote);
380 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000381 setOperationAction(ISD::FMA, MVT::f16, Promote);
382 setOperationAction(ISD::FNEG, MVT::f16, Promote);
383 setOperationAction(ISD::FABS, MVT::f16, Promote);
384 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
385 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000386 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
387 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
388 setOperationAction(ISD::FRINT, MVT::f16, Promote);
389 setOperationAction(ISD::FROUND, MVT::f16, Promote);
390 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
391 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
392 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000393 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
394 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000395
396 // promote v4f16 to v4f32 when that is known to be safe.
397 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
398 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
399 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
400 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
401 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
402 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
403 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
404 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
405 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
406 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
407 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
408 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
409
410 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
411 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
412 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
413 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
414 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
415 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
416 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
417 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
418 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
419 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
420 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
421 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
422 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
423 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
424 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000425
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000426 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
427 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
428 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
429 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
430 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
431 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
432 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
433 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
434 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
435 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
436 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
437 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
438 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
439 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
440 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
441 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
442 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
443 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
444 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
445 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
446 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000447
Tim Northover3b0846e2014-05-24 12:50:23 +0000448 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000449 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 setOperationAction(ISD::FFLOOR, Ty, Legal);
451 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
452 setOperationAction(ISD::FCEIL, Ty, Legal);
453 setOperationAction(ISD::FRINT, Ty, Legal);
454 setOperationAction(ISD::FTRUNC, Ty, Legal);
455 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000456 setOperationAction(ISD::FMINNUM, Ty, Legal);
457 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000458 setOperationAction(ISD::FMINIMUM, Ty, Legal);
459 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Adhemerval Zanella2d28db62019-05-16 13:30:18 +0000460 setOperationAction(ISD::LROUND, Ty, Legal);
461 setOperationAction(ISD::LLROUND, Ty, Legal);
Adhemerval Zanella34d8daa2019-05-28 21:04:29 +0000462 setOperationAction(ISD::LRINT, Ty, Legal);
463 setOperationAction(ISD::LLRINT, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000464 }
465
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000466 if (Subtarget->hasFullFP16()) {
467 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
468 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
469 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
470 setOperationAction(ISD::FRINT, MVT::f16, Legal);
471 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
472 setOperationAction(ISD::FROUND, MVT::f16, Legal);
473 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
474 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000475 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
476 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000477 }
478
Tim Northover3b0846e2014-05-24 12:50:23 +0000479 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
480
Tim Northover70666e72018-06-20 12:09:01 +0000481 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
482
Tim Northovercdf15292016-04-14 17:03:29 +0000483 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000484 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000488
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000489 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
490 // This requires the Performance Monitors extension.
491 if (Subtarget->hasPerfMon())
492 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
493
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000494 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
495 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
496 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000497 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
498 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
499 } else {
500 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
501 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
502 }
503
Juergen Ributzka23266502014-12-10 19:43:32 +0000504 // Make floating-point constants legal for the large code model, so they don't
505 // become loads from the constant pool.
506 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
507 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
508 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
509 }
510
Tim Northover3b0846e2014-05-24 12:50:23 +0000511 // AArch64 does not have floating-point extending loads, i1 sign-extending
512 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000513 for (MVT VT : MVT::fp_valuetypes()) {
514 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
515 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
516 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
517 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
518 }
519 for (MVT VT : MVT::integer_valuetypes())
520 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
521
Tim Northover3b0846e2014-05-24 12:50:23 +0000522 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
523 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
524 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
525 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
526 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
527 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
528 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000529
530 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
531 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
532
Tim Northover3b0846e2014-05-24 12:50:23 +0000533 // Indexed loads and stores are supported.
534 for (unsigned im = (unsigned)ISD::PRE_INC;
535 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
536 setIndexedLoadAction(im, MVT::i8, Legal);
537 setIndexedLoadAction(im, MVT::i16, Legal);
538 setIndexedLoadAction(im, MVT::i32, Legal);
539 setIndexedLoadAction(im, MVT::i64, Legal);
540 setIndexedLoadAction(im, MVT::f64, Legal);
541 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000542 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000543 setIndexedStoreAction(im, MVT::i8, Legal);
544 setIndexedStoreAction(im, MVT::i16, Legal);
545 setIndexedStoreAction(im, MVT::i32, Legal);
546 setIndexedStoreAction(im, MVT::i64, Legal);
547 setIndexedStoreAction(im, MVT::f64, Legal);
548 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000549 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000550 }
551
552 // Trap.
553 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Tom Tan7ecb5142019-06-21 23:38:05 +0000554 if (Subtarget->isTargetWindows())
555 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000556
557 // We combine OR nodes for bitfield operations.
558 setTargetDAGCombine(ISD::OR);
Nikita Popov1a261442019-03-15 21:04:34 +0000559 // Try to create BICs for vector ANDs.
560 setTargetDAGCombine(ISD::AND);
Tim Northover3b0846e2014-05-24 12:50:23 +0000561
562 // Vector add and sub nodes may conceal a high-half opportunity.
563 // Also, try to fold ADD into CSINC/CSINV..
564 setTargetDAGCombine(ISD::ADD);
565 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000566 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000567 setTargetDAGCombine(ISD::XOR);
568 setTargetDAGCombine(ISD::SINT_TO_FP);
569 setTargetDAGCombine(ISD::UINT_TO_FP);
570
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000571 setTargetDAGCombine(ISD::FP_TO_SINT);
572 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000573 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000574
Tim Northover3b0846e2014-05-24 12:50:23 +0000575 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
576
577 setTargetDAGCombine(ISD::ANY_EXTEND);
578 setTargetDAGCombine(ISD::ZERO_EXTEND);
579 setTargetDAGCombine(ISD::SIGN_EXTEND);
580 setTargetDAGCombine(ISD::BITCAST);
581 setTargetDAGCombine(ISD::CONCAT_VECTORS);
582 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000583 if (Subtarget->supportsAddressTopByteIgnored())
584 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000585
586 setTargetDAGCombine(ISD::MUL);
587
588 setTargetDAGCombine(ISD::SELECT);
589 setTargetDAGCombine(ISD::VSELECT);
590
591 setTargetDAGCombine(ISD::INTRINSIC_VOID);
592 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
594
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000595 setTargetDAGCombine(ISD::GlobalAddress);
596
Evandro Menezesf8425342018-05-29 15:58:50 +0000597 // In case of strict alignment, avoid an excessive number of byte wide stores.
598 MaxStoresPerMemsetOptSize = 8;
599 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
600 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000601
Evandro Menezesf8425342018-05-29 15:58:50 +0000602 MaxGluedStoresPerMemcpy = 4;
603 MaxStoresPerMemcpyOptSize = 4;
604 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
605 ? MaxStoresPerMemcpyOptSize : 16;
606
607 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000608
609 setStackPointerRegisterToSaveRestore(AArch64::SP);
610
611 setSchedulingPreference(Sched::Hybrid);
612
Quentin Colombet6843ac42015-03-31 20:52:32 +0000613 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000614
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000615 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000616 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000617 // Set preferred alignments.
618 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
619 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000620
Evandro Menezese45de8a2016-09-26 15:32:33 +0000621 // Only change the limit for entries in a jump table if specified by
Evandro Menezes0f797b82019-03-29 17:28:11 +0000622 // the sub target, but not at the command line.
Evandro Menezese45de8a2016-09-26 15:32:33 +0000623 unsigned MaxJT = STI.getMaximumJumpTableSize();
Evandro Menezes0f797b82019-03-29 17:28:11 +0000624 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
Evandro Menezese45de8a2016-09-26 15:32:33 +0000625 setMaximumJumpTableSize(MaxJT);
626
Tim Northover3b0846e2014-05-24 12:50:23 +0000627 setHasExtractBitsInsn(true);
628
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000629 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
630
Tim Northover3b0846e2014-05-24 12:50:23 +0000631 if (Subtarget->hasNEON()) {
632 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
633 // silliness like this:
634 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
635 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
636 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
637 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
638 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
639 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
640 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
641 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
642 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
643 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
644 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
645 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
646 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
647 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
648 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
649 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
650 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
651 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
652 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
653 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
654 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
655 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
656 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
657 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
658 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
659
660 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
661 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
662 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
663 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
664 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
665
666 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
667
668 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
669 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000670 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
671 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000672 // i8 vector elements also need promotion to i32 for v8i8
Craig Toppera4f99972018-01-01 19:21:35 +0000673 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
674 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000675 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
676 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
677 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
678 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
679 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000680 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
681 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
682 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
683 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000684
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000685 if (Subtarget->hasFullFP16()) {
686 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
687 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
688 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
689 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
690 } else {
691 // when AArch64 doesn't have fullfp16 support, promote the input
692 // to i32 first.
693 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
694 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
695 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
696 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
697 }
698
Craig Topperc5551bf2016-04-26 05:26:51 +0000699 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
700 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
701
Tim Northover3b0846e2014-05-24 12:50:23 +0000702 // AArch64 doesn't have MUL.2d:
703 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000704 // Custom handling for some quad-vector types to detect MULL.
705 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
706 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
707 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
708
Amara Emersonc9916d72017-05-16 21:29:22 +0000709 // Vector reductions
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000710 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
711 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000712 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
713 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
714 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
715 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
716 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
717 }
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000718 for (MVT VT : { MVT::v4f16, MVT::v2f32,
719 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000720 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
721 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
722 }
723
Tim Northover3b0846e2014-05-24 12:50:23 +0000724 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
725 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
726 // Likewise, narrowing and extending vector loads/stores aren't handled
727 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000728 for (MVT VT : MVT::vector_valuetypes()) {
729 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000730
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000731 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000732 setOperationAction(ISD::MULHS, VT, Legal);
733 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000734 } else {
735 setOperationAction(ISD::MULHS, VT, Expand);
736 setOperationAction(ISD::MULHU, VT, Expand);
737 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000738 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000739 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000740
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000741 setOperationAction(ISD::BSWAP, VT, Expand);
Nikita Popova3be17e2019-02-12 18:55:53 +0000742 setOperationAction(ISD::CTTZ, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000743
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000744 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000745 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000746 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
747 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
748 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
749 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000750 }
751
752 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000753 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000754 setOperationAction(ISD::FFLOOR, Ty, Legal);
755 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
756 setOperationAction(ISD::FCEIL, Ty, Legal);
757 setOperationAction(ISD::FRINT, Ty, Legal);
758 setOperationAction(ISD::FTRUNC, Ty, Legal);
759 setOperationAction(ISD::FROUND, Ty, Legal);
760 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000761
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +0000762 if (Subtarget->hasFullFP16()) {
763 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
764 setOperationAction(ISD::FFLOOR, Ty, Legal);
765 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
766 setOperationAction(ISD::FCEIL, Ty, Legal);
767 setOperationAction(ISD::FRINT, Ty, Legal);
768 setOperationAction(ISD::FTRUNC, Ty, Legal);
769 setOperationAction(ISD::FROUND, Ty, Legal);
770 }
771 }
772
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000773 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000774 }
James Molloyf089ab72014-08-06 10:42:18 +0000775
Matthias Braun651cff42016-06-02 18:03:53 +0000776 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000777}
778
Craig Topper18e69f42016-04-15 06:20:21 +0000779void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000780 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000781
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000782 if (VT.isFloatingPoint()) {
783 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
784 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
785 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000786 }
787
788 // Mark vector float intrinsics as expand.
789 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000790 setOperationAction(ISD::FSIN, VT, Expand);
791 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000792 setOperationAction(ISD::FPOW, VT, Expand);
793 setOperationAction(ISD::FLOG, VT, Expand);
794 setOperationAction(ISD::FLOG2, VT, Expand);
795 setOperationAction(ISD::FLOG10, VT, Expand);
796 setOperationAction(ISD::FEXP, VT, Expand);
797 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000798
799 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000800 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000801 }
802
Craig Topper18e69f42016-04-15 06:20:21 +0000803 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
804 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
805 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
806 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
807 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
808 setOperationAction(ISD::SRA, VT, Custom);
809 setOperationAction(ISD::SRL, VT, Custom);
810 setOperationAction(ISD::SHL, VT, Custom);
Craig Topper18e69f42016-04-15 06:20:21 +0000811 setOperationAction(ISD::OR, VT, Custom);
812 setOperationAction(ISD::SETCC, VT, Custom);
813 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000814
Craig Topper18e69f42016-04-15 06:20:21 +0000815 setOperationAction(ISD::SELECT, VT, Expand);
816 setOperationAction(ISD::SELECT_CC, VT, Expand);
817 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000818 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000819 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000820
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000821 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000822 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000823 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000824
Craig Topper18e69f42016-04-15 06:20:21 +0000825 setOperationAction(ISD::UDIV, VT, Expand);
826 setOperationAction(ISD::SDIV, VT, Expand);
827 setOperationAction(ISD::UREM, VT, Expand);
828 setOperationAction(ISD::SREM, VT, Expand);
829 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000830
Craig Topper18e69f42016-04-15 06:20:21 +0000831 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
832 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000833
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000834 if (!VT.isFloatingPoint())
835 setOperationAction(ISD::ABS, VT, Legal);
836
Hal Finkelcd8664c2015-12-11 23:11:52 +0000837 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000838 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000839 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000840 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000841
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000842 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
843 if (VT.isFloatingPoint() &&
844 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000845 for (unsigned Opcode :
846 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000847 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000848
Tim Northover3b0846e2014-05-24 12:50:23 +0000849 if (Subtarget->isLittleEndian()) {
850 for (unsigned im = (unsigned)ISD::PRE_INC;
851 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000852 setIndexedLoadAction(im, VT, Legal);
853 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000854 }
855 }
856}
857
858void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
859 addRegisterClass(VT, &AArch64::FPR64RegClass);
860 addTypeForNEON(VT, MVT::v2i32);
861}
862
863void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
864 addRegisterClass(VT, &AArch64::FPR128RegClass);
865 addTypeForNEON(VT, MVT::v4i32);
866}
867
Mehdi Amini44ede332015-07-09 02:09:04 +0000868EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
869 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000870 if (!VT.isVector())
871 return MVT::i32;
872 return VT.changeVectorElementTypeToInteger();
873}
874
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000875static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
876 const APInt &Demanded,
877 TargetLowering::TargetLoweringOpt &TLO,
878 unsigned NewOpc) {
879 uint64_t OldImm = Imm, NewImm, Enc;
880 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
881
882 // Return if the immediate is already all zeros, all ones, a bimm32 or a
883 // bimm64.
884 if (Imm == 0 || Imm == Mask ||
885 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
886 return false;
887
888 unsigned EltSize = Size;
889 uint64_t DemandedBits = Demanded.getZExtValue();
890
891 // Clear bits that are not demanded.
892 Imm &= DemandedBits;
893
894 while (true) {
895 // The goal here is to set the non-demanded bits in a way that minimizes
896 // the number of switching between 0 and 1. In order to achieve this goal,
897 // we set the non-demanded bits to the value of the preceding demanded bits.
898 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
899 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
900 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
901 // The final result is 0b11000011.
902 uint64_t NonDemandedBits = ~DemandedBits;
903 uint64_t InvertedImm = ~Imm & DemandedBits;
904 uint64_t RotatedImm =
905 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
906 NonDemandedBits;
907 uint64_t Sum = RotatedImm + NonDemandedBits;
908 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
909 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
910 NewImm = (Imm | Ones) & Mask;
911
912 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
913 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
914 // we halve the element size and continue the search.
915 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
916 break;
917
918 // We cannot shrink the element size any further if it is 2-bits.
919 if (EltSize == 2)
920 return false;
921
922 EltSize /= 2;
923 Mask >>= EltSize;
924 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
925
926 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
927 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
928 return false;
929
930 // Merge the upper and lower halves of Imm and DemandedBits.
931 Imm |= Hi;
932 DemandedBits |= DemandedBitsHi;
933 }
934
935 ++NumOptimizedImms;
936
937 // Replicate the element across the register width.
938 while (EltSize < Size) {
939 NewImm |= NewImm << EltSize;
940 EltSize *= 2;
941 }
942
943 (void)OldImm;
944 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
945 "demanded bits should never be altered");
946 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
947
948 // Create the new constant immediate node.
949 EVT VT = Op.getValueType();
950 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000951 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000952
953 // If the new constant immediate is all-zeros or all-ones, let the target
954 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000955 if (NewImm == 0 || NewImm == OrigMask) {
956 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
957 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000958 // Otherwise, create a machine node so that target independent DAG combine
959 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000960 } else {
961 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
962 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
963 New = SDValue(
964 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
965 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000966
967 return TLO.CombineTo(Op, New);
968}
969
970bool AArch64TargetLowering::targetShrinkDemandedConstant(
971 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
972 // Delay this optimization to as late as possible.
973 if (!TLO.LegalOps)
974 return false;
975
976 if (!EnableOptimizeLogicalImm)
977 return false;
978
979 EVT VT = Op.getValueType();
980 if (VT.isVector())
981 return false;
982
983 unsigned Size = VT.getSizeInBits();
984 assert((Size == 32 || Size == 64) &&
985 "i32 or i64 is expected after legalization.");
986
987 // Exit early if we demand all bits.
988 if (Demanded.countPopulation() == Size)
989 return false;
990
991 unsigned NewOpc;
992 switch (Op.getOpcode()) {
993 default:
994 return false;
995 case ISD::AND:
996 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
997 break;
998 case ISD::OR:
999 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1000 break;
1001 case ISD::XOR:
1002 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1003 break;
1004 }
1005 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1006 if (!C)
1007 return false;
1008 uint64_t Imm = C->getZExtValue();
1009 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1010}
1011
Tim Northover3b0846e2014-05-24 12:50:23 +00001012/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +00001013/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +00001014void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +00001015 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +00001016 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001017 switch (Op.getOpcode()) {
1018 default:
1019 break;
1020 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001021 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +00001022 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1023 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +00001024 Known.Zero &= Known2.Zero;
1025 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001026 break;
1027 }
1028 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001029 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001030 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1031 switch (IntID) {
1032 default: return;
1033 case Intrinsic::aarch64_ldaxr:
1034 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001035 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001037 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001038 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001039 return;
1040 }
1041 }
1042 break;
1043 }
1044 case ISD::INTRINSIC_WO_CHAIN:
1045 case ISD::INTRINSIC_VOID: {
1046 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1047 switch (IntNo) {
1048 default:
1049 break;
1050 case Intrinsic::aarch64_neon_umaxv:
1051 case Intrinsic::aarch64_neon_uminv: {
1052 // Figure out the datatype of the vector operand. The UMINV instruction
1053 // will zero extend the result, so we can mark as known zero all the
1054 // bits larger than the element datatype. 32-bit or larget doesn't need
1055 // this as those are legal types and will be handled by isel directly.
1056 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001057 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001058 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1059 assert(BitWidth >= 8 && "Unexpected width!");
1060 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001061 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001062 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1063 assert(BitWidth >= 16 && "Unexpected width!");
1064 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001065 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001066 }
1067 break;
1068 } break;
1069 }
1070 }
1071 }
1072}
1073
Mehdi Aminieaabc512015-07-09 15:12:23 +00001074MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1075 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001076 return MVT::i64;
1077}
1078
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00001079bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1080 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1081 bool *Fast) const {
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001082 if (Subtarget->requiresStrictAlign())
1083 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001084
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001085 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001086 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1087 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001088 // See comments in performSTORECombine() for more details about
1089 // these conditions.
1090
1091 // Code that uses clang vector extensions can mark that it
1092 // wants unaligned accesses to be treated as fast by
1093 // underspecifying alignment to be 1 or 2.
1094 Align <= 2 ||
1095
1096 // Disregard v2i64. Memcpy lowering produces those and splitting
1097 // them regresses performance on micro-benchmarks and olden/bh.
1098 VT == MVT::v2i64;
1099 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001100 return true;
1101}
1102
Amara Emerson13af1ed2019-07-24 22:17:31 +00001103// Same as above but handling LLTs instead.
1104bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1105 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1106 bool *Fast) const {
1107 if (Subtarget->requiresStrictAlign())
1108 return false;
1109
1110 if (Fast) {
1111 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1112 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1113 Ty.getSizeInBytes() != 16 ||
1114 // See comments in performSTORECombine() for more details about
1115 // these conditions.
1116
1117 // Code that uses clang vector extensions can mark that it
1118 // wants unaligned accesses to be treated as fast by
1119 // underspecifying alignment to be 1 or 2.
1120 Align <= 2 ||
1121
1122 // Disregard v2i64. Memcpy lowering produces those and splitting
1123 // them regresses performance on micro-benchmarks and olden/bh.
1124 Ty == LLT::vector(2, 64);
1125 }
1126 return true;
1127}
1128
Tim Northover3b0846e2014-05-24 12:50:23 +00001129FastISel *
1130AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1131 const TargetLibraryInfo *libInfo) const {
1132 return AArch64::createFastISel(funcInfo, libInfo);
1133}
1134
1135const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001136 switch ((AArch64ISD::NodeType)Opcode) {
1137 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001138 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1139 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001140 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001141 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1142 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1143 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1144 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1145 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1146 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1147 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1148 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1149 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1150 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001151 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001152 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1153 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1154 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1155 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1156 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1157 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1158 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001159 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1160 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1161 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001162 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001163 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1164 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1165 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1166 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1167 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1168 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1169 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1170 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1171 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1172 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1173 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1174 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1175 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1176 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1177 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1178 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1179 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1180 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1181 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1182 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1183 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1184 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1185 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1186 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1187 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1188 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1189 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1190 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1191 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1192 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1193 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1194 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1195 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1196 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1197 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1198 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1199 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1200 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1201 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1202 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1203 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1204 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1205 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1206 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1207 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1208 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1209 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1210 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001211 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1212 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1213 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1214 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1215 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1216 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001217 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1218 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1219 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1220 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1221 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1222 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1223 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001224 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001225 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1226 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001227 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001228 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1229 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1230 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1231 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1232 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1233 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1234 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1235 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1236 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1237 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1238 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1239 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1240 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1241 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1242 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1243 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1244 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1245 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1246 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1247 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1248 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1249 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1250 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1251 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1252 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1253 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1254 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1255 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1256 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001257 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1258 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001259 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001260 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1261 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1262 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Evgeniy Stepanovd752f5e2019-07-17 19:24:02 +00001263 case AArch64ISD::STG: return "AArch64ISD::STG";
1264 case AArch64ISD::STZG: return "AArch64ISD::STZG";
1265 case AArch64ISD::ST2G: return "AArch64ISD::ST2G";
1266 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G";
Tim Northover3b0846e2014-05-24 12:50:23 +00001267 }
Matthias Braund04893f2015-05-07 21:33:59 +00001268 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001269}
1270
1271MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001272AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001273 MachineBasicBlock *MBB) const {
1274 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1275 // phi node:
1276
1277 // OrigBB:
1278 // [... previous instrs leading to comparison ...]
1279 // b.ne TrueBB
1280 // b EndBB
1281 // TrueBB:
1282 // ; Fallthrough
1283 // EndBB:
1284 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1285
Tim Northover3b0846e2014-05-24 12:50:23 +00001286 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001287 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001288 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001289 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001290 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001291
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001292 unsigned DestReg = MI.getOperand(0).getReg();
1293 unsigned IfTrueReg = MI.getOperand(1).getReg();
1294 unsigned IfFalseReg = MI.getOperand(2).getReg();
1295 unsigned CondCode = MI.getOperand(3).getImm();
1296 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001297
1298 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1299 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1300 MF->insert(It, TrueBB);
1301 MF->insert(It, EndBB);
1302
1303 // Transfer rest of current basic-block to EndBB
1304 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1305 MBB->end());
1306 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1307
1308 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1309 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1310 MBB->addSuccessor(TrueBB);
1311 MBB->addSuccessor(EndBB);
1312
1313 // TrueBB falls through to the end.
1314 TrueBB->addSuccessor(EndBB);
1315
1316 if (!NZCVKilled) {
1317 TrueBB->addLiveIn(AArch64::NZCV);
1318 EndBB->addLiveIn(AArch64::NZCV);
1319 }
1320
1321 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1322 .addReg(IfTrueReg)
1323 .addMBB(TrueBB)
1324 .addReg(IfFalseReg)
1325 .addMBB(MBB);
1326
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001327 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001328 return EndBB;
1329}
1330
Eli Friedmanad1151c2018-11-09 23:33:30 +00001331MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1332 MachineInstr &MI, MachineBasicBlock *BB) const {
1333 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1334 BB->getParent()->getFunction().getPersonalityFn())) &&
1335 "SEH does not use catchret!");
1336 return BB;
1337}
1338
1339MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1340 MachineInstr &MI, MachineBasicBlock *BB) const {
1341 MI.eraseFromParent();
1342 return BB;
1343}
1344
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001345MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1346 MachineInstr &MI, MachineBasicBlock *BB) const {
1347 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001348 default:
1349#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001350 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001351#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001352 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001353
1354 case AArch64::F128CSEL:
1355 return EmitF128CSEL(MI, BB);
1356
1357 case TargetOpcode::STACKMAP:
1358 case TargetOpcode::PATCHPOINT:
1359 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001360
1361 case AArch64::CATCHRET:
1362 return EmitLoweredCatchRet(MI, BB);
1363 case AArch64::CATCHPAD:
1364 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001365 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001366}
1367
1368//===----------------------------------------------------------------------===//
1369// AArch64 Lowering private implementation.
1370//===----------------------------------------------------------------------===//
1371
1372//===----------------------------------------------------------------------===//
1373// Lowering Code
1374//===----------------------------------------------------------------------===//
1375
1376/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1377/// CC
1378static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1379 switch (CC) {
1380 default:
1381 llvm_unreachable("Unknown condition code!");
1382 case ISD::SETNE:
1383 return AArch64CC::NE;
1384 case ISD::SETEQ:
1385 return AArch64CC::EQ;
1386 case ISD::SETGT:
1387 return AArch64CC::GT;
1388 case ISD::SETGE:
1389 return AArch64CC::GE;
1390 case ISD::SETLT:
1391 return AArch64CC::LT;
1392 case ISD::SETLE:
1393 return AArch64CC::LE;
1394 case ISD::SETUGT:
1395 return AArch64CC::HI;
1396 case ISD::SETUGE:
1397 return AArch64CC::HS;
1398 case ISD::SETULT:
1399 return AArch64CC::LO;
1400 case ISD::SETULE:
1401 return AArch64CC::LS;
1402 }
1403}
1404
1405/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1406static void changeFPCCToAArch64CC(ISD::CondCode CC,
1407 AArch64CC::CondCode &CondCode,
1408 AArch64CC::CondCode &CondCode2) {
1409 CondCode2 = AArch64CC::AL;
1410 switch (CC) {
1411 default:
1412 llvm_unreachable("Unknown FP condition!");
1413 case ISD::SETEQ:
1414 case ISD::SETOEQ:
1415 CondCode = AArch64CC::EQ;
1416 break;
1417 case ISD::SETGT:
1418 case ISD::SETOGT:
1419 CondCode = AArch64CC::GT;
1420 break;
1421 case ISD::SETGE:
1422 case ISD::SETOGE:
1423 CondCode = AArch64CC::GE;
1424 break;
1425 case ISD::SETOLT:
1426 CondCode = AArch64CC::MI;
1427 break;
1428 case ISD::SETOLE:
1429 CondCode = AArch64CC::LS;
1430 break;
1431 case ISD::SETONE:
1432 CondCode = AArch64CC::MI;
1433 CondCode2 = AArch64CC::GT;
1434 break;
1435 case ISD::SETO:
1436 CondCode = AArch64CC::VC;
1437 break;
1438 case ISD::SETUO:
1439 CondCode = AArch64CC::VS;
1440 break;
1441 case ISD::SETUEQ:
1442 CondCode = AArch64CC::EQ;
1443 CondCode2 = AArch64CC::VS;
1444 break;
1445 case ISD::SETUGT:
1446 CondCode = AArch64CC::HI;
1447 break;
1448 case ISD::SETUGE:
1449 CondCode = AArch64CC::PL;
1450 break;
1451 case ISD::SETLT:
1452 case ISD::SETULT:
1453 CondCode = AArch64CC::LT;
1454 break;
1455 case ISD::SETLE:
1456 case ISD::SETULE:
1457 CondCode = AArch64CC::LE;
1458 break;
1459 case ISD::SETNE:
1460 case ISD::SETUNE:
1461 CondCode = AArch64CC::NE;
1462 break;
1463 }
1464}
1465
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001466/// Convert a DAG fp condition code to an AArch64 CC.
1467/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1468/// should be AND'ed instead of OR'ed.
1469static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1470 AArch64CC::CondCode &CondCode,
1471 AArch64CC::CondCode &CondCode2) {
1472 CondCode2 = AArch64CC::AL;
1473 switch (CC) {
1474 default:
1475 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1476 assert(CondCode2 == AArch64CC::AL);
1477 break;
1478 case ISD::SETONE:
1479 // (a one b)
1480 // == ((a olt b) || (a ogt b))
1481 // == ((a ord b) && (a une b))
1482 CondCode = AArch64CC::VC;
1483 CondCode2 = AArch64CC::NE;
1484 break;
1485 case ISD::SETUEQ:
1486 // (a ueq b)
1487 // == ((a uno b) || (a oeq b))
1488 // == ((a ule b) && (a uge b))
1489 CondCode = AArch64CC::PL;
1490 CondCode2 = AArch64CC::LE;
1491 break;
1492 }
1493}
1494
Tim Northover3b0846e2014-05-24 12:50:23 +00001495/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1496/// CC usable with the vector instructions. Fewer operations are available
1497/// without a real NZCV register, so we have to use less efficient combinations
1498/// to get the same effect.
1499static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1500 AArch64CC::CondCode &CondCode,
1501 AArch64CC::CondCode &CondCode2,
1502 bool &Invert) {
1503 Invert = false;
1504 switch (CC) {
1505 default:
1506 // Mostly the scalar mappings work fine.
1507 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1508 break;
1509 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001510 Invert = true;
1511 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001512 case ISD::SETO:
1513 CondCode = AArch64CC::MI;
1514 CondCode2 = AArch64CC::GE;
1515 break;
1516 case ISD::SETUEQ:
1517 case ISD::SETULT:
1518 case ISD::SETULE:
1519 case ISD::SETUGT:
1520 case ISD::SETUGE:
1521 // All of the compare-mask comparisons are ordered, but we can switch
1522 // between the two by a double inversion. E.g. ULE == !OGT.
1523 Invert = true;
1524 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1525 break;
1526 }
1527}
1528
1529static bool isLegalArithImmed(uint64_t C) {
1530 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001531 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001532 LLVM_DEBUG(dbgs() << "Is imm " << C
1533 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001534 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001535}
1536
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001537// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1538// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1539// can be set differently by this operation. It comes down to whether
1540// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1541// everything is fine. If not then the optimization is wrong. Thus general
1542// comparisons are only valid if op2 != 0.
1543//
1544// So, finally, the only LLVM-native comparisons that don't mention C and V
1545// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1546// the absence of information about op2.
1547static bool isCMN(SDValue Op, ISD::CondCode CC) {
1548 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1549 (CC == ISD::SETEQ || CC == ISD::SETNE);
1550}
1551
Tim Northover3b0846e2014-05-24 12:50:23 +00001552static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001553 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001554 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001555 const bool FullFP16 =
1556 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001557
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001558 if (VT.isFloatingPoint()) {
1559 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001560 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001561 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1562 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001563 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001564 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001565 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001566 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001567
1568 // The CMP instruction is just an alias for SUBS, and representing it as
1569 // SUBS means that it's possible to get CSE with subtract operations.
1570 // A later phase can perform the optimization of setting the destination
1571 // register to WZR/XZR if it ends up being unused.
1572 unsigned Opcode = AArch64ISD::SUBS;
1573
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001574 if (isCMN(RHS, CC)) {
1575 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001576 Opcode = AArch64ISD::ADDS;
1577 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001578 } else if (isCMN(LHS, CC)) {
1579 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1580 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1581 Opcode = AArch64ISD::ADDS;
1582 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001583 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001584 !isUnsignedIntSetCC(CC)) {
1585 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1586 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1587 // of the signed comparisons.
1588 Opcode = AArch64ISD::ANDS;
1589 RHS = LHS.getOperand(1);
1590 LHS = LHS.getOperand(0);
1591 }
1592
Matthias Braunaf7d7702015-07-16 20:02:37 +00001593 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001594 .getValue(1);
1595}
1596
Matthias Braunaf7d7702015-07-16 20:02:37 +00001597/// \defgroup AArch64CCMP CMP;CCMP matching
1598///
1599/// These functions deal with the formation of CMP;CCMP;... sequences.
1600/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1601/// a comparison. They set the NZCV flags to a predefined value if their
1602/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001603/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001604/// expressed as:
1605/// cmp A
1606/// ccmp B, inv(CB), CA
1607/// check for CB flags
1608///
Matthias Braund0412122018-12-06 01:40:23 +00001609/// This naturally lets us implement chains of AND operations with SETCC
1610/// operands. And we can even implement some other situations by transforming
1611/// them:
1612/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1613/// negating the flags used in a CCMP/FCCMP operations.
1614/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1615/// by negating the flags we test for afterwards. i.e.
1616/// NEG (CMP CCMP CCCMP ...) can be implemented.
1617/// - Note that we can only ever negate all previously processed results.
1618/// What we can not implement by flipping the flags to test is a negation
1619/// of two sub-trees (because the negation affects all sub-trees emitted so
1620/// far, so the 2nd sub-tree we emit would also affect the first).
1621/// With those tools we can implement some OR operations:
1622/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1623/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1624/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1625/// elimination rules from earlier to implement the whole thing as a
1626/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001627///
Matthias Braund0412122018-12-06 01:40:23 +00001628/// As complete example:
1629/// or (or (setCA (cmp A)) (setCB (cmp B)))
1630/// (and (setCC (cmp C)) (setCD (cmp D)))"
1631/// can be reassociated to:
1632/// or (and (setCC (cmp C)) setCD (cmp D))
1633// (or (setCA (cmp A)) (setCB (cmp B)))
1634/// can be transformed to:
1635/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1636/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1637/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001638/// cmp C
1639/// ccmp D, inv(CD), CC
1640/// ccmp A, CA, inv(CD)
1641/// ccmp B, CB, inv(CA)
1642/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001643///
1644/// A counterexample is "or (and A B) (and C D)" which translates to
1645/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1646/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001647/// @{
1648
Geoff Berrye41c2df2015-07-20 22:03:52 +00001649/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001650static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1651 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001652 AArch64CC::CondCode Predicate,
1653 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001654 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001655 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001656 const bool FullFP16 =
1657 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1658
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001659 if (LHS.getValueType().isFloatingPoint()) {
1660 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001661 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001662 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1663 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1664 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001665 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001666 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001667 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001668 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001669 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1670 Opcode = AArch64ISD::CCMN;
1671 RHS = RHS.getOperand(1);
1672 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001673 }
1674 if (Opcode == 0)
1675 Opcode = AArch64ISD::CCMP;
1676
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001677 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1678 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1679 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001680 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1681 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1682}
1683
Matthias Braun96d12512018-11-06 03:15:22 +00001684/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1685/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001686/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1687/// changing the conditions on the SETCC tests.
1688/// (this means we can call emitConjunctionRec() with
1689/// Negate==true on this sub-tree)
1690/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1691/// cannot do the negation naturally. We are required to
1692/// emit the subtree first in this case.
1693/// \param WillNegate Is true if are called when the result of this
1694/// subexpression must be negated. This happens when the
1695/// outer expression is an OR. We can use this fact to know
1696/// that we have a double negation (or (or ...) ...) that
1697/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001698static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001699 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001700 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001701 if (!Val.hasOneUse())
1702 return false;
1703 unsigned Opcode = Val->getOpcode();
1704 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001705 if (Val->getOperand(0).getValueType() == MVT::f128)
1706 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001707 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001708 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001709 return true;
1710 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001711 // Protect against exponential runtime and stack overflow.
1712 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001713 return false;
1714 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001715 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001716 SDValue O0 = Val->getOperand(0);
1717 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001718 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001719 bool MustBeFirstL;
1720 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001721 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001722 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001723 bool MustBeFirstR;
1724 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001725 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001726
Matthias Braund0412122018-12-06 01:40:23 +00001727 if (MustBeFirstL && MustBeFirstR)
1728 return false;
1729
1730 if (IsOR) {
1731 // For an OR expression we need to be able to naturally negate at least
1732 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001733 if (!CanNegateL && !CanNegateR)
1734 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001735 // If we the result of the OR will be negated and we can naturally negate
1736 // the leafs, then this sub-tree as a whole negates naturally.
1737 CanNegate = WillNegate && CanNegateL && CanNegateR;
1738 // If we cannot naturally negate the whole sub-tree, then this must be
1739 // emitted first.
1740 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001741 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001742 assert(Opcode == ISD::AND && "Must be OR or AND");
1743 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001744 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001745 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001746 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001747 return true;
1748 }
1749 return false;
1750}
1751
1752/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1753/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1754/// Tries to transform the given i1 producing node @p Val to a series compare
1755/// and conditional compare operations. @returns an NZCV flags producing node
1756/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1757/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001758/// \p Negate is true if we want this sub-tree being negated just by changing
1759/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001760static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001761 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001762 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001763 // We're at a tree leaf, produce a conditional comparison operation.
1764 unsigned Opcode = Val->getOpcode();
1765 if (Opcode == ISD::SETCC) {
1766 SDValue LHS = Val->getOperand(0);
1767 SDValue RHS = Val->getOperand(1);
1768 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1769 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001770 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001771 CC = getSetCCInverse(CC, isInteger);
1772 SDLoc DL(Val);
1773 // Determine OutCC and handle FP special case.
1774 if (isInteger) {
1775 OutCC = changeIntCCToAArch64CC(CC);
1776 } else {
1777 assert(LHS.getValueType().isFloatingPoint());
1778 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001779 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1780 // Some floating point conditions can't be tested with a single condition
1781 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001782 if (ExtraCC != AArch64CC::AL) {
1783 SDValue ExtraCmp;
1784 if (!CCOp.getNode())
1785 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001786 else
1787 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001788 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001789 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001790 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001791 }
1792 }
1793
1794 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001795 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001796 return emitComparison(LHS, RHS, CC, DL, DAG);
1797 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001798 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001799 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001800 }
Matthias Braund0412122018-12-06 01:40:23 +00001801 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001802
Matthias Braund0412122018-12-06 01:40:23 +00001803 bool IsOR = Opcode == ISD::OR;
1804
Matthias Braunaf7d7702015-07-16 20:02:37 +00001805 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001806 bool CanNegateL;
1807 bool MustBeFirstL;
1808 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1809 assert(ValidL && "Valid conjunction/disjunction tree");
1810 (void)ValidL;
1811
Matthias Braunaf7d7702015-07-16 20:02:37 +00001812 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001813 bool CanNegateR;
1814 bool MustBeFirstR;
1815 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1816 assert(ValidR && "Valid conjunction/disjunction tree");
1817 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001818
Matthias Braund0412122018-12-06 01:40:23 +00001819 // Swap sub-tree that must come first to the right side.
1820 if (MustBeFirstL) {
1821 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1822 std::swap(LHS, RHS);
1823 std::swap(CanNegateL, CanNegateR);
1824 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001825 }
1826
Matthias Braund0412122018-12-06 01:40:23 +00001827 bool NegateR;
1828 bool NegateAfterR;
1829 bool NegateL;
1830 bool NegateAfterAll;
1831 if (Opcode == ISD::OR) {
1832 // Swap the sub-tree that we can negate naturally to the left.
1833 if (!CanNegateL) {
1834 assert(CanNegateR && "at least one side must be negatable");
1835 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1836 assert(!Negate);
1837 std::swap(LHS, RHS);
1838 NegateR = false;
1839 NegateAfterR = true;
1840 } else {
1841 // Negate the left sub-tree if possible, otherwise negate the result.
1842 NegateR = CanNegateR;
1843 NegateAfterR = !CanNegateR;
1844 }
1845 NegateL = true;
1846 NegateAfterAll = !Negate;
1847 } else {
1848 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1849 assert(!Negate && "Valid conjunction/disjunction tree");
1850
1851 NegateL = false;
1852 NegateR = false;
1853 NegateAfterR = false;
1854 NegateAfterAll = false;
1855 }
1856
1857 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001858 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001859 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1860 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001861 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001862 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1863 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001864 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1865 return CmpL;
1866}
1867
Matthias Braun96d12512018-11-06 03:15:22 +00001868/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1869/// In some cases this is even possible with OR operations in the expression.
1870/// See \ref AArch64CCMP.
1871/// \see emitConjunctionRec().
1872static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1873 AArch64CC::CondCode &OutCC) {
1874 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001875 bool DummyMustBeFirst;
1876 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001877 return SDValue();
1878
Matthias Braun96d12512018-11-06 03:15:22 +00001879 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001880}
1881
Matthias Braunaf7d7702015-07-16 20:02:37 +00001882/// @}
1883
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001884/// Returns how profitable it is to fold a comparison's operand's shift and/or
1885/// extension operations.
1886static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1887 auto isSupportedExtend = [&](SDValue V) {
1888 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1889 return true;
1890
1891 if (V.getOpcode() == ISD::AND)
1892 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1893 uint64_t Mask = MaskCst->getZExtValue();
1894 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1895 }
1896
1897 return false;
1898 };
1899
1900 if (!Op.hasOneUse())
1901 return 0;
1902
1903 if (isSupportedExtend(Op))
1904 return 1;
1905
1906 unsigned Opc = Op.getOpcode();
1907 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1908 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1909 uint64_t Shift = ShiftCst->getZExtValue();
1910 if (isSupportedExtend(Op.getOperand(0)))
1911 return (Shift <= 4) ? 2 : 1;
1912 EVT VT = Op.getValueType();
1913 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1914 return 1;
1915 }
1916
1917 return 0;
1918}
1919
Tim Northover3b0846e2014-05-24 12:50:23 +00001920static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001921 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001922 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001923 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1924 EVT VT = RHS.getValueType();
1925 uint64_t C = RHSC->getZExtValue();
1926 if (!isLegalArithImmed(C)) {
1927 // Constant does not fit, try adjusting it by one?
1928 switch (CC) {
1929 default:
1930 break;
1931 case ISD::SETLT:
1932 case ISD::SETGE:
1933 if ((VT == MVT::i32 && C != 0x80000000 &&
1934 isLegalArithImmed((uint32_t)(C - 1))) ||
1935 (VT == MVT::i64 && C != 0x80000000ULL &&
1936 isLegalArithImmed(C - 1ULL))) {
1937 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1938 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001939 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001940 }
1941 break;
1942 case ISD::SETULT:
1943 case ISD::SETUGE:
1944 if ((VT == MVT::i32 && C != 0 &&
1945 isLegalArithImmed((uint32_t)(C - 1))) ||
1946 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1947 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1948 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001949 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001950 }
1951 break;
1952 case ISD::SETLE:
1953 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001954 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001955 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001956 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001957 isLegalArithImmed(C + 1ULL))) {
1958 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1959 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001960 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001961 }
1962 break;
1963 case ISD::SETULE:
1964 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001965 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001966 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001967 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001968 isLegalArithImmed(C + 1ULL))) {
1969 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1970 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001971 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001972 }
1973 break;
1974 }
1975 }
1976 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001977
1978 // Comparisons are canonicalized so that the RHS operand is simpler than the
1979 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1980 // can fold some shift+extend operations on the RHS operand, so swap the
1981 // operands if that can be done.
1982 //
1983 // For example:
1984 // lsl w13, w11, #1
1985 // cmp w13, w12
1986 // can be turned into:
1987 // cmp w12, w11, lsl #1
1988 if (!isa<ConstantSDNode>(RHS) ||
1989 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1990 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1991
1992 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1993 std::swap(LHS, RHS);
1994 CC = ISD::getSetCCSwappedOperands(CC);
1995 }
1996 }
1997
Matthias Braunaf7d7702015-07-16 20:02:37 +00001998 SDValue Cmp;
1999 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00002000 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002001 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2002
2003 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2004 // For the i8 operand, the largest immediate is 255, so this can be easily
2005 // encoded in the compare instruction. For the i16 operand, however, the
2006 // largest immediate cannot be encoded in the compare.
2007 // Therefore, use a sign extending load and cmn to avoid materializing the
2008 // -1 constant. For example,
2009 // movz w1, #65535
2010 // ldrh w0, [x0, #0]
2011 // cmp w0, w1
2012 // >
2013 // ldrsh w0, [x0, #0]
2014 // cmn w0, #1
2015 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2016 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002017 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00002018 // transformation is profitable.
2019 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2020 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2021 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2022 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2023 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2024 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2025 SDValue SExt =
2026 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2027 DAG.getValueType(MVT::i16));
2028 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2029 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002030 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002031 AArch64CC = changeIntCCToAArch64CC(CC);
2032 }
2033 }
2034
2035 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00002036 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002037 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2038 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00002039 }
2040 }
2041 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00002042
2043 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002044 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002045 AArch64CC = changeIntCCToAArch64CC(CC);
2046 }
2047 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00002048 return Cmp;
2049}
2050
2051static std::pair<SDValue, SDValue>
2052getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2053 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2054 "Unsupported value type");
2055 SDValue Value, Overflow;
2056 SDLoc DL(Op);
2057 SDValue LHS = Op.getOperand(0);
2058 SDValue RHS = Op.getOperand(1);
2059 unsigned Opc = 0;
2060 switch (Op.getOpcode()) {
2061 default:
2062 llvm_unreachable("Unknown overflow instruction!");
2063 case ISD::SADDO:
2064 Opc = AArch64ISD::ADDS;
2065 CC = AArch64CC::VS;
2066 break;
2067 case ISD::UADDO:
2068 Opc = AArch64ISD::ADDS;
2069 CC = AArch64CC::HS;
2070 break;
2071 case ISD::SSUBO:
2072 Opc = AArch64ISD::SUBS;
2073 CC = AArch64CC::VS;
2074 break;
2075 case ISD::USUBO:
2076 Opc = AArch64ISD::SUBS;
2077 CC = AArch64CC::LO;
2078 break;
2079 // Multiply needs a little bit extra work.
2080 case ISD::SMULO:
2081 case ISD::UMULO: {
2082 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002083 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002084 if (Op.getValueType() == MVT::i32) {
2085 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2086 // For a 32 bit multiply with overflow check we want the instruction
2087 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2088 // need to generate the following pattern:
2089 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2090 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2091 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2092 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2093 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002094 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002095 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2096 // operation. We need to clear out the upper 32 bits, because we used a
2097 // widening multiply that wrote all 64 bits. In the end this should be a
2098 // noop.
2099 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2100 if (IsSigned) {
2101 // The signed overflow check requires more than just a simple check for
2102 // any bit set in the upper 32 bits of the result. These bits could be
2103 // just the sign bits of a negative number. To perform the overflow
2104 // check we have to arithmetic shift right the 32nd bit of the result by
2105 // 31 bits. Then we compare the result to the upper 32 bits.
2106 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002107 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002108 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2109 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002110 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002111 // It is important that LowerBits is last, otherwise the arithmetic
2112 // shift will not be folded into the compare (SUBS).
2113 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2114 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2115 .getValue(1);
2116 } else {
2117 // The overflow check for unsigned multiply is easy. We only need to
2118 // check if any of the upper 32 bits are set. This can be done with a
2119 // CMP (shifted register). For that we need to generate the following
2120 // pattern:
2121 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2122 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002123 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002124 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2125 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002126 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2127 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002128 UpperBits).getValue(1);
2129 }
2130 break;
2131 }
2132 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2133 // For the 64 bit multiply
2134 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2135 if (IsSigned) {
2136 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2137 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002138 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002139 // It is important that LowerBits is last, otherwise the arithmetic
2140 // shift will not be folded into the compare (SUBS).
2141 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2142 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2143 .getValue(1);
2144 } else {
2145 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2146 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2147 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002148 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2149 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002150 UpperBits).getValue(1);
2151 }
2152 break;
2153 }
2154 } // switch (...)
2155
2156 if (Opc) {
2157 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2158
2159 // Emit the AArch64 operation with overflow check.
2160 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2161 Overflow = Value.getValue(1);
2162 }
2163 return std::make_pair(Value, Overflow);
2164}
2165
2166SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2167 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002168 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002169 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002170}
2171
Amara Emerson24ca39c2017-10-09 15:15:09 +00002172// Returns true if the given Op is the overflow flag result of an overflow
2173// intrinsic operation.
2174static bool isOverflowIntrOpRes(SDValue Op) {
2175 unsigned Opc = Op.getOpcode();
2176 return (Op.getResNo() == 1 &&
2177 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2178 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2179}
2180
Tim Northover3b0846e2014-05-24 12:50:23 +00002181static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2182 SDValue Sel = Op.getOperand(0);
2183 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002184 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002185
Amara Emerson24ca39c2017-10-09 15:15:09 +00002186 // If the operand is an overflow checking operation, invert the condition
2187 // code and kill the Not operation. I.e., transform:
2188 // (xor (overflow_op_bool, 1))
2189 // -->
2190 // (csel 1, 0, invert(cc), overflow_op_bool)
2191 // ... which later gets transformed to just a cset instruction with an
2192 // inverted condition code, rather than a cset + eor sequence.
2193 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2194 // Only lower legal XALUO ops.
2195 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2196 return SDValue();
2197
2198 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2199 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2200 AArch64CC::CondCode CC;
2201 SDValue Value, Overflow;
2202 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2203 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2204 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2205 CCVal, Overflow);
2206 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002207 // If neither operand is a SELECT_CC, give up.
2208 if (Sel.getOpcode() != ISD::SELECT_CC)
2209 std::swap(Sel, Other);
2210 if (Sel.getOpcode() != ISD::SELECT_CC)
2211 return Op;
2212
2213 // The folding we want to perform is:
2214 // (xor x, (select_cc a, b, cc, 0, -1) )
2215 // -->
2216 // (csel x, (xor x, -1), cc ...)
2217 //
2218 // The latter will get matched to a CSINV instruction.
2219
2220 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2221 SDValue LHS = Sel.getOperand(0);
2222 SDValue RHS = Sel.getOperand(1);
2223 SDValue TVal = Sel.getOperand(2);
2224 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002225
2226 // FIXME: This could be generalized to non-integer comparisons.
2227 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2228 return Op;
2229
2230 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2231 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2232
Eric Christopher572e03a2015-06-19 01:53:21 +00002233 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002234 if (!CFVal || !CTVal)
2235 return Op;
2236
2237 // We can commute the SELECT_CC by inverting the condition. This
2238 // might be needed to make this fit into a CSINV pattern.
2239 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2240 std::swap(TVal, FVal);
2241 std::swap(CTVal, CFVal);
2242 CC = ISD::getSetCCInverse(CC, true);
2243 }
2244
2245 // If the constants line up, perform the transform!
2246 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2247 SDValue CCVal;
2248 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2249
2250 FVal = Other;
2251 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002252 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002253
2254 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2255 CCVal, Cmp);
2256 }
2257
2258 return Op;
2259}
2260
2261static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2262 EVT VT = Op.getValueType();
2263
2264 // Let legalize expand this if it isn't a legal type yet.
2265 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2266 return SDValue();
2267
2268 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2269
2270 unsigned Opc;
2271 bool ExtraOp = false;
2272 switch (Op.getOpcode()) {
2273 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002274 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002275 case ISD::ADDC:
2276 Opc = AArch64ISD::ADDS;
2277 break;
2278 case ISD::SUBC:
2279 Opc = AArch64ISD::SUBS;
2280 break;
2281 case ISD::ADDE:
2282 Opc = AArch64ISD::ADCS;
2283 ExtraOp = true;
2284 break;
2285 case ISD::SUBE:
2286 Opc = AArch64ISD::SBCS;
2287 ExtraOp = true;
2288 break;
2289 }
2290
2291 if (!ExtraOp)
2292 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2293 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2294 Op.getOperand(2));
2295}
2296
2297static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2298 // Let legalize expand this if it isn't a legal type yet.
2299 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2300 return SDValue();
2301
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002302 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002303 AArch64CC::CondCode CC;
2304 // The actual operation that sets the overflow or carry flag.
2305 SDValue Value, Overflow;
2306 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2307
2308 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002309 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2310 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002311
2312 // We use an inverted condition, because the conditional select is inverted
2313 // too. This will allow it to be selected to a single instruction:
2314 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002315 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2316 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002317 CCVal, Overflow);
2318
2319 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002320 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002321}
2322
2323// Prefetch operands are:
2324// 1: Address to prefetch
2325// 2: bool isWrite
2326// 3: int locality (0 = no locality ... 3 = extreme locality)
2327// 4: bool isDataCache
2328static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2329 SDLoc DL(Op);
2330 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2331 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002332 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002333
2334 bool IsStream = !Locality;
2335 // When the locality number is set
2336 if (Locality) {
2337 // The front-end should have filtered out the out-of-range values
2338 assert(Locality <= 3 && "Prefetch locality out-of-range");
2339 // The locality degree is the opposite of the cache speed.
2340 // Put the number the other way around.
2341 // The encoding starts at 0 for level 1
2342 Locality = 3 - Locality;
2343 }
2344
2345 // built the mask value encoding the expected behavior.
2346 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002347 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002348 (Locality << 1) | // Cache level bits
2349 (unsigned)IsStream; // Stream bit
2350 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002351 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002352}
2353
2354SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2355 SelectionDAG &DAG) const {
2356 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2357
2358 RTLIB::Libcall LC;
2359 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2360
2361 return LowerF128Call(Op, DAG, LC);
2362}
2363
2364SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2365 SelectionDAG &DAG) const {
2366 if (Op.getOperand(0).getValueType() != MVT::f128) {
2367 // It's legal except when f128 is involved
2368 return Op;
2369 }
2370
2371 RTLIB::Libcall LC;
2372 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2373
2374 // FP_ROUND node has a second operand indicating whether it is known to be
2375 // precise. That doesn't take part in the LibCall so we can't directly use
2376 // LowerF128Call.
2377 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002378 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2379 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002380}
2381
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002382SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2383 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002384 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2385 // Any additional optimization in this function should be recorded
2386 // in the cost tables.
2387 EVT InVT = Op.getOperand(0).getValueType();
2388 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002389 unsigned NumElts = InVT.getVectorNumElements();
2390
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002391 // f16 conversions are promoted to f32 when full fp16 is not supported.
2392 if (InVT.getVectorElementType() == MVT::f16 &&
2393 !Subtarget->hasFullFP16()) {
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002394 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2395 SDLoc dl(Op);
2396 return DAG.getNode(
2397 Op.getOpcode(), dl, Op.getValueType(),
2398 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2399 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002400
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002401 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002402 SDLoc dl(Op);
2403 SDValue Cv =
2404 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2405 Op.getOperand(0));
2406 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002407 }
2408
2409 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002410 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002411 MVT ExtVT =
2412 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2413 VT.getVectorNumElements());
2414 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002415 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2416 }
2417
2418 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002419 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002420}
2421
2422SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2423 SelectionDAG &DAG) const {
2424 if (Op.getOperand(0).getValueType().isVector())
2425 return LowerVectorFP_TO_INT(Op, DAG);
2426
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002427 // f16 conversions are promoted to f32 when full fp16 is not supported.
2428 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2429 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002430 SDLoc dl(Op);
2431 return DAG.getNode(
2432 Op.getOpcode(), dl, Op.getValueType(),
2433 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2434 }
2435
Tim Northover3b0846e2014-05-24 12:50:23 +00002436 if (Op.getOperand(0).getValueType() != MVT::f128) {
2437 // It's legal except when f128 is involved
2438 return Op;
2439 }
2440
2441 RTLIB::Libcall LC;
2442 if (Op.getOpcode() == ISD::FP_TO_SINT)
2443 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2444 else
2445 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2446
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002447 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002448 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002449}
2450
2451static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2452 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2453 // Any additional optimization in this function should be recorded
2454 // in the cost tables.
2455 EVT VT = Op.getValueType();
2456 SDLoc dl(Op);
2457 SDValue In = Op.getOperand(0);
2458 EVT InVT = In.getValueType();
2459
Tim Northoveref0d7602014-06-15 09:27:06 +00002460 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2461 MVT CastVT =
2462 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2463 InVT.getVectorNumElements());
2464 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002465 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002466 }
2467
Tim Northoveref0d7602014-06-15 09:27:06 +00002468 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2469 unsigned CastOpc =
2470 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2471 EVT CastVT = VT.changeVectorElementTypeToInteger();
2472 In = DAG.getNode(CastOpc, dl, CastVT, In);
2473 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002474 }
2475
Tim Northoveref0d7602014-06-15 09:27:06 +00002476 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002477}
2478
2479SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2480 SelectionDAG &DAG) const {
2481 if (Op.getValueType().isVector())
2482 return LowerVectorINT_TO_FP(Op, DAG);
2483
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002484 // f16 conversions are promoted to f32 when full fp16 is not supported.
2485 if (Op.getValueType() == MVT::f16 &&
2486 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002487 SDLoc dl(Op);
2488 return DAG.getNode(
2489 ISD::FP_ROUND, dl, MVT::f16,
2490 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002491 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002492 }
2493
Tim Northover3b0846e2014-05-24 12:50:23 +00002494 // i128 conversions are libcalls.
2495 if (Op.getOperand(0).getValueType() == MVT::i128)
2496 return SDValue();
2497
2498 // Other conversions are legal, unless it's to the completely software-based
2499 // fp128.
2500 if (Op.getValueType() != MVT::f128)
2501 return Op;
2502
2503 RTLIB::Libcall LC;
2504 if (Op.getOpcode() == ISD::SINT_TO_FP)
2505 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2506 else
2507 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2508
2509 return LowerF128Call(Op, DAG, LC);
2510}
2511
2512SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2513 SelectionDAG &DAG) const {
2514 // For iOS, we want to call an alternative entry point: __sincos_stret,
2515 // which returns the values in two S / D registers.
2516 SDLoc dl(Op);
2517 SDValue Arg = Op.getOperand(0);
2518 EVT ArgVT = Arg.getValueType();
2519 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2520
2521 ArgListTy Args;
2522 ArgListEntry Entry;
2523
2524 Entry.Node = Arg;
2525 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002526 Entry.IsSExt = false;
2527 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002528 Args.push_back(Entry);
2529
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002530 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2531 : RTLIB::SINCOS_STRET_F32;
2532 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002533 SDValue Callee =
2534 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002535
Serge Gueltone38003f2017-05-09 19:31:13 +00002536 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002537 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002538 CLI.setDebugLoc(dl)
2539 .setChain(DAG.getEntryNode())
2540 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002541
2542 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2543 return CallResult.first;
2544}
2545
Tim Northoverf8bfe212014-07-18 13:07:05 +00002546static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2547 if (Op.getValueType() != MVT::f16)
2548 return SDValue();
2549
2550 assert(Op.getOperand(0).getValueType() == MVT::i16);
2551 SDLoc DL(Op);
2552
2553 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2554 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2555 return SDValue(
2556 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002557 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002558 0);
2559}
2560
Chad Rosierd9d0f862014-10-08 02:31:24 +00002561static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2562 if (OrigVT.getSizeInBits() >= 64)
2563 return OrigVT;
2564
2565 assert(OrigVT.isSimple() && "Expecting a simple value type");
2566
2567 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2568 switch (OrigSimpleTy) {
2569 default: llvm_unreachable("Unexpected Vector Type");
2570 case MVT::v2i8:
2571 case MVT::v2i16:
2572 return MVT::v2i32;
2573 case MVT::v4i8:
2574 return MVT::v4i16;
2575 }
2576}
2577
2578static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2579 const EVT &OrigTy,
2580 const EVT &ExtTy,
2581 unsigned ExtOpcode) {
2582 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2583 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2584 // 64-bits we need to insert a new extension so that it will be 64-bits.
2585 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2586 if (OrigTy.getSizeInBits() >= 64)
2587 return N;
2588
2589 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2590 EVT NewVT = getExtensionTo64Bits(OrigTy);
2591
2592 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2593}
2594
2595static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2596 bool isSigned) {
2597 EVT VT = N->getValueType(0);
2598
2599 if (N->getOpcode() != ISD::BUILD_VECTOR)
2600 return false;
2601
Pete Cooper3af9a252015-06-26 18:17:36 +00002602 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002604 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002605 unsigned HalfSize = EltSize / 2;
2606 if (isSigned) {
2607 if (!isIntN(HalfSize, C->getSExtValue()))
2608 return false;
2609 } else {
2610 if (!isUIntN(HalfSize, C->getZExtValue()))
2611 return false;
2612 }
2613 continue;
2614 }
2615 return false;
2616 }
2617
2618 return true;
2619}
2620
2621static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2622 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2623 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2624 N->getOperand(0)->getValueType(0),
2625 N->getValueType(0),
2626 N->getOpcode());
2627
2628 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2629 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002630 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002631 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002632 unsigned NumElts = VT.getVectorNumElements();
2633 MVT TruncVT = MVT::getIntegerVT(EltSize);
2634 SmallVector<SDValue, 8> Ops;
2635 for (unsigned i = 0; i != NumElts; ++i) {
2636 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2637 const APInt &CInt = C->getAPIntValue();
2638 // Element types smaller than 32 bits are not legal, so use i32 elements.
2639 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002640 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002641 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002642 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002643}
2644
2645static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002646 return N->getOpcode() == ISD::SIGN_EXTEND ||
2647 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002648}
2649
2650static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002651 return N->getOpcode() == ISD::ZERO_EXTEND ||
2652 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002653}
2654
2655static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2656 unsigned Opcode = N->getOpcode();
2657 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2658 SDNode *N0 = N->getOperand(0).getNode();
2659 SDNode *N1 = N->getOperand(1).getNode();
2660 return N0->hasOneUse() && N1->hasOneUse() &&
2661 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2662 }
2663 return false;
2664}
2665
2666static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2667 unsigned Opcode = N->getOpcode();
2668 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2669 SDNode *N0 = N->getOperand(0).getNode();
2670 SDNode *N1 = N->getOperand(1).getNode();
2671 return N0->hasOneUse() && N1->hasOneUse() &&
2672 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2673 }
2674 return false;
2675}
2676
Tim Northover70666e72018-06-20 12:09:01 +00002677SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2678 SelectionDAG &DAG) const {
2679 // The rounding mode is in bits 23:22 of the FPSCR.
2680 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2681 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2682 // so that the shift + and get folded into a bitfield extract.
2683 SDLoc dl(Op);
2684
2685 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2686 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2687 MVT::i64));
2688 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2689 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2690 DAG.getConstant(1U << 22, dl, MVT::i32));
2691 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2692 DAG.getConstant(22, dl, MVT::i32));
2693 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2694 DAG.getConstant(3, dl, MVT::i32));
2695}
2696
Chad Rosierd9d0f862014-10-08 02:31:24 +00002697static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2698 // Multiplications are only custom-lowered for 128-bit vectors so that
2699 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2700 EVT VT = Op.getValueType();
2701 assert(VT.is128BitVector() && VT.isInteger() &&
2702 "unexpected type for custom-lowering ISD::MUL");
2703 SDNode *N0 = Op.getOperand(0).getNode();
2704 SDNode *N1 = Op.getOperand(1).getNode();
2705 unsigned NewOpc = 0;
2706 bool isMLA = false;
2707 bool isN0SExt = isSignExtended(N0, DAG);
2708 bool isN1SExt = isSignExtended(N1, DAG);
2709 if (isN0SExt && isN1SExt)
2710 NewOpc = AArch64ISD::SMULL;
2711 else {
2712 bool isN0ZExt = isZeroExtended(N0, DAG);
2713 bool isN1ZExt = isZeroExtended(N1, DAG);
2714 if (isN0ZExt && isN1ZExt)
2715 NewOpc = AArch64ISD::UMULL;
2716 else if (isN1SExt || isN1ZExt) {
2717 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2718 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2719 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2720 NewOpc = AArch64ISD::SMULL;
2721 isMLA = true;
2722 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2723 NewOpc = AArch64ISD::UMULL;
2724 isMLA = true;
2725 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2726 std::swap(N0, N1);
2727 NewOpc = AArch64ISD::UMULL;
2728 isMLA = true;
2729 }
2730 }
2731
2732 if (!NewOpc) {
2733 if (VT == MVT::v2i64)
2734 // Fall through to expand this. It is not legal.
2735 return SDValue();
2736 else
2737 // Other vector multiplications are legal.
2738 return Op;
2739 }
2740 }
2741
2742 // Legalize to a S/UMULL instruction
2743 SDLoc DL(Op);
2744 SDValue Op0;
2745 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2746 if (!isMLA) {
2747 Op0 = skipExtensionForVectorMULL(N0, DAG);
2748 assert(Op0.getValueType().is64BitVector() &&
2749 Op1.getValueType().is64BitVector() &&
2750 "unexpected types for extended operands to VMULL");
2751 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2752 }
2753 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2754 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2755 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2756 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2757 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2758 EVT Op1VT = Op1.getValueType();
2759 return DAG.getNode(N0->getOpcode(), DL, VT,
2760 DAG.getNode(NewOpc, DL, VT,
2761 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2762 DAG.getNode(NewOpc, DL, VT,
2763 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2764}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002765
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002766SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2767 SelectionDAG &DAG) const {
2768 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2769 SDLoc dl(Op);
2770 switch (IntNo) {
2771 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002772 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002773 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2774 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2775 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002776 case Intrinsic::aarch64_neon_abs: {
2777 EVT Ty = Op.getValueType();
2778 if (Ty == MVT::i64) {
2779 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2780 Op.getOperand(1));
2781 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2782 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2783 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2784 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2785 } else {
2786 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2787 }
2788 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002789 case Intrinsic::aarch64_neon_smax:
2790 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2791 Op.getOperand(1), Op.getOperand(2));
2792 case Intrinsic::aarch64_neon_umax:
2793 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2794 Op.getOperand(1), Op.getOperand(2));
2795 case Intrinsic::aarch64_neon_smin:
2796 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2797 Op.getOperand(1), Op.getOperand(2));
2798 case Intrinsic::aarch64_neon_umin:
2799 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2800 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002801
2802 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002803 const auto &MF = DAG.getMachineFunction();
2804 const auto *RegInfo = Subtarget->getRegisterInfo();
2805 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002806 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2807 Op.getSimpleValueType());
2808 }
2809
2810 case Intrinsic::eh_recoverfp: {
2811 // FIXME: This needs to be implemented to correctly handle highly aligned
2812 // stack objects. For now we simply return the incoming FP. Refer D53541
2813 // for more details.
2814 SDValue FnOp = Op.getOperand(1);
2815 SDValue IncomingFPOp = Op.getOperand(2);
2816 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2817 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2818 if (!Fn)
2819 report_fatal_error(
2820 "llvm.eh.recoverfp must take a function as the first argument");
2821 return IncomingFPOp;
2822 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002823 }
2824}
2825
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002826// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2827static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2828 EVT VT, EVT MemVT,
2829 SelectionDAG &DAG) {
2830 assert(VT.isVector() && "VT should be a vector type");
2831 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2832
2833 SDValue Value = ST->getValue();
2834
2835 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2836 // the word lane which represent the v4i8 subvector. It optimizes the store
2837 // to:
2838 //
2839 // xtn v0.8b, v0.8h
2840 // str s0, [x0]
2841
2842 SDValue Undef = DAG.getUNDEF(MVT::i16);
2843 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2844 {Undef, Undef, Undef, Undef});
2845
2846 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2847 Value, UndefVec);
2848 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2849
2850 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2851 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2852 Trunc, DAG.getConstant(0, DL, MVT::i64));
2853
2854 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2855 ST->getBasePtr(), ST->getMemOperand());
2856}
2857
2858// Custom lowering for any store, vector or scalar and/or default or with
2859// a truncate operations. Currently only custom lower truncate operation
2860// from vector v4i16 to v4i8.
2861SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2862 SelectionDAG &DAG) const {
2863 SDLoc Dl(Op);
2864 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2865 assert (StoreNode && "Can only custom lower store nodes");
2866
2867 SDValue Value = StoreNode->getValue();
2868
2869 EVT VT = Value.getValueType();
2870 EVT MemVT = StoreNode->getMemoryVT();
2871
2872 assert (VT.isVector() && "Can only custom lower vector store types");
2873
2874 unsigned AS = StoreNode->getAddressSpace();
2875 unsigned Align = StoreNode->getAlignment();
2876 if (Align < MemVT.getStoreSize() &&
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00002877 !allowsMisalignedMemoryAccesses(
2878 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002879 return scalarizeVectorStore(StoreNode, DAG);
2880 }
2881
2882 if (StoreNode->isTruncatingStore()) {
2883 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2884 }
2885
2886 return SDValue();
2887}
2888
Tim Northover3b0846e2014-05-24 12:50:23 +00002889SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2890 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002891 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2892 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002893
Tim Northover3b0846e2014-05-24 12:50:23 +00002894 switch (Op.getOpcode()) {
2895 default:
2896 llvm_unreachable("unimplemented operand");
2897 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002898 case ISD::BITCAST:
2899 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002900 case ISD::GlobalAddress:
2901 return LowerGlobalAddress(Op, DAG);
2902 case ISD::GlobalTLSAddress:
2903 return LowerGlobalTLSAddress(Op, DAG);
2904 case ISD::SETCC:
2905 return LowerSETCC(Op, DAG);
2906 case ISD::BR_CC:
2907 return LowerBR_CC(Op, DAG);
2908 case ISD::SELECT:
2909 return LowerSELECT(Op, DAG);
2910 case ISD::SELECT_CC:
2911 return LowerSELECT_CC(Op, DAG);
2912 case ISD::JumpTable:
2913 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002914 case ISD::BR_JT:
2915 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002916 case ISD::ConstantPool:
2917 return LowerConstantPool(Op, DAG);
2918 case ISD::BlockAddress:
2919 return LowerBlockAddress(Op, DAG);
2920 case ISD::VASTART:
2921 return LowerVASTART(Op, DAG);
2922 case ISD::VACOPY:
2923 return LowerVACOPY(Op, DAG);
2924 case ISD::VAARG:
2925 return LowerVAARG(Op, DAG);
2926 case ISD::ADDC:
2927 case ISD::ADDE:
2928 case ISD::SUBC:
2929 case ISD::SUBE:
2930 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2931 case ISD::SADDO:
2932 case ISD::UADDO:
2933 case ISD::SSUBO:
2934 case ISD::USUBO:
2935 case ISD::SMULO:
2936 case ISD::UMULO:
2937 return LowerXALUO(Op, DAG);
2938 case ISD::FADD:
2939 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2940 case ISD::FSUB:
2941 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2942 case ISD::FMUL:
2943 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2944 case ISD::FDIV:
2945 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2946 case ISD::FP_ROUND:
2947 return LowerFP_ROUND(Op, DAG);
2948 case ISD::FP_EXTEND:
2949 return LowerFP_EXTEND(Op, DAG);
2950 case ISD::FRAMEADDR:
2951 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002952 case ISD::SPONENTRY:
2953 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002954 case ISD::RETURNADDR:
2955 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002956 case ISD::ADDROFRETURNADDR:
2957 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002958 case ISD::INSERT_VECTOR_ELT:
2959 return LowerINSERT_VECTOR_ELT(Op, DAG);
2960 case ISD::EXTRACT_VECTOR_ELT:
2961 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2962 case ISD::BUILD_VECTOR:
2963 return LowerBUILD_VECTOR(Op, DAG);
2964 case ISD::VECTOR_SHUFFLE:
2965 return LowerVECTOR_SHUFFLE(Op, DAG);
2966 case ISD::EXTRACT_SUBVECTOR:
2967 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2968 case ISD::SRA:
2969 case ISD::SRL:
2970 case ISD::SHL:
2971 return LowerVectorSRA_SRL_SHL(Op, DAG);
2972 case ISD::SHL_PARTS:
2973 return LowerShiftLeftParts(Op, DAG);
2974 case ISD::SRL_PARTS:
2975 case ISD::SRA_PARTS:
2976 return LowerShiftRightParts(Op, DAG);
2977 case ISD::CTPOP:
2978 return LowerCTPOP(Op, DAG);
2979 case ISD::FCOPYSIGN:
2980 return LowerFCOPYSIGN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002981 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002982 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002983 case ISD::XOR:
2984 return LowerXOR(Op, DAG);
2985 case ISD::PREFETCH:
2986 return LowerPREFETCH(Op, DAG);
2987 case ISD::SINT_TO_FP:
2988 case ISD::UINT_TO_FP:
2989 return LowerINT_TO_FP(Op, DAG);
2990 case ISD::FP_TO_SINT:
2991 case ISD::FP_TO_UINT:
2992 return LowerFP_TO_INT(Op, DAG);
2993 case ISD::FSINCOS:
2994 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002995 case ISD::FLT_ROUNDS_:
2996 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002997 case ISD::MUL:
2998 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002999 case ISD::INTRINSIC_WO_CHAIN:
3000 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00003001 case ISD::STORE:
3002 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00003003 case ISD::VECREDUCE_ADD:
3004 case ISD::VECREDUCE_SMAX:
3005 case ISD::VECREDUCE_SMIN:
3006 case ISD::VECREDUCE_UMAX:
3007 case ISD::VECREDUCE_UMIN:
3008 case ISD::VECREDUCE_FMAX:
3009 case ISD::VECREDUCE_FMIN:
3010 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00003011 case ISD::ATOMIC_LOAD_SUB:
3012 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00003013 case ISD::ATOMIC_LOAD_AND:
3014 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00003015 case ISD::DYNAMIC_STACKALLOC:
3016 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003017 }
3018}
3019
Tim Northover3b0846e2014-05-24 12:50:23 +00003020//===----------------------------------------------------------------------===//
3021// Calling Convention Implementation
3022//===----------------------------------------------------------------------===//
3023
Robin Morisset039781e2014-08-29 21:53:01 +00003024/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00003025CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3026 bool IsVarArg) const {
3027 switch (CC) {
3028 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00003029 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00003030 case CallingConv::WebKit_JS:
3031 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00003032 case CallingConv::GHC:
3033 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00003034 case CallingConv::C:
3035 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00003036 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00003037 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00003038 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00003039 if (Subtarget->isTargetWindows() && IsVarArg)
3040 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00003041 if (!Subtarget->isTargetDarwin())
3042 return CC_AArch64_AAPCS;
3043 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00003044 case CallingConv::Win64:
3045 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00003046 case CallingConv::AArch64_VectorCall:
3047 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00003048 }
3049}
3050
Tim Northover406024a2016-08-10 21:44:01 +00003051CCAssignFn *
3052AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3053 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3054 : RetCC_AArch64_AAPCS;
3055}
3056
Tim Northover3b0846e2014-05-24 12:50:23 +00003057SDValue AArch64TargetLowering::LowerFormalArguments(
3058 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003059 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3060 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003061 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003062 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003063 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003064
3065 // Assign locations to all of the incoming arguments.
3066 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003067 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3068 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003069
3070 // At this point, Ins[].VT may already be promoted to i32. To correctly
3071 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3072 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3073 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3074 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3075 // LocVT.
3076 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003077 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003078 unsigned CurArgIdx = 0;
3079 for (unsigned i = 0; i != NumArgs; ++i) {
3080 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003081 if (Ins[i].isOrigArg()) {
3082 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3083 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003084
Andrew Trick05938a52015-02-16 18:10:47 +00003085 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003086 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3087 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003088 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3089 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3090 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3091 ValVT = MVT::i8;
3092 else if (ActualMVT == MVT::i16)
3093 ValVT = MVT::i16;
3094 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003095 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3096 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003097 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003098 assert(!Res && "Call operand has unhandled type");
3099 (void)Res;
3100 }
3101 assert(ArgLocs.size() == Ins.size());
3102 SmallVector<SDValue, 16> ArgValues;
3103 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3104 CCValAssign &VA = ArgLocs[i];
3105
3106 if (Ins[i].Flags.isByVal()) {
3107 // Byval is used for HFAs in the PCS, but the system should work in a
3108 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003109 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003110 int Size = Ins[i].Flags.getByValSize();
3111 unsigned NumRegs = (Size + 7) / 8;
3112
3113 // FIXME: This works on big-endian for composite byvals, which are the common
3114 // case. It should also work for fundamental types too.
3115 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003116 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003117 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003118 InVals.push_back(FrameIdxN);
3119
3120 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003121 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003122
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003123 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003124 // Arguments stored in registers.
3125 EVT RegVT = VA.getLocVT();
3126
3127 SDValue ArgValue;
3128 const TargetRegisterClass *RC;
3129
3130 if (RegVT == MVT::i32)
3131 RC = &AArch64::GPR32RegClass;
3132 else if (RegVT == MVT::i64)
3133 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003134 else if (RegVT == MVT::f16)
3135 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003136 else if (RegVT == MVT::f32)
3137 RC = &AArch64::FPR32RegClass;
3138 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3139 RC = &AArch64::FPR64RegClass;
3140 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3141 RC = &AArch64::FPR128RegClass;
3142 else
3143 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3144
3145 // Transform the arguments in physical registers into virtual ones.
3146 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3147 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3148
3149 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3150 // to 64 bits. Insert an assert[sz]ext to capture this, then
3151 // truncate to the right size.
3152 switch (VA.getLocInfo()) {
3153 default:
3154 llvm_unreachable("Unknown loc info!");
3155 case CCValAssign::Full:
3156 break;
3157 case CCValAssign::BCvt:
3158 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3159 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003160 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003161 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003162 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003163 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3164 // nodes after our lowering.
3165 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003166 break;
3167 }
3168
3169 InVals.push_back(ArgValue);
3170
3171 } else { // VA.isRegLoc()
3172 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3173 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003174 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003175
3176 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003177 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3178 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003179 BEAlign = 8 - ArgSize;
3180
Matthias Braun941a7052016-07-28 18:40:00 +00003181 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003182
3183 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003184 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003185 SDValue ArgValue;
3186
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003187 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003188 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003189 MVT MemVT = VA.getValVT();
3190
Tim Northover47e003c2014-05-26 17:21:53 +00003191 switch (VA.getLocInfo()) {
3192 default:
3193 break;
Tim Northover6890add2014-06-03 13:54:53 +00003194 case CCValAssign::BCvt:
3195 MemVT = VA.getLocVT();
3196 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003197 case CCValAssign::SExt:
3198 ExtType = ISD::SEXTLOAD;
3199 break;
3200 case CCValAssign::ZExt:
3201 ExtType = ISD::ZEXTLOAD;
3202 break;
3203 case CCValAssign::AExt:
3204 ExtType = ISD::EXTLOAD;
3205 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003206 }
3207
Alex Lorenze40c8a22015-08-11 23:09:45 +00003208 ArgValue = DAG.getExtLoad(
3209 ExtType, DL, VA.getLocVT(), Chain, FIN,
3210 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003211 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003212
Tim Northover3b0846e2014-05-24 12:50:23 +00003213 InVals.push_back(ArgValue);
3214 }
3215 }
3216
3217 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003218 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003219 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003220 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003221 // The AAPCS variadic function ABI is identical to the non-variadic
3222 // one. As a result there may be more arguments in registers and we should
3223 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003224 // Win64 variadic functions also pass arguments in registers, but all float
3225 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003226 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3227 }
3228
Tim Northover3b0846e2014-05-24 12:50:23 +00003229 // This will point to the next argument passed via stack.
3230 unsigned StackOffset = CCInfo.getNextStackOffset();
3231 // We currently pass all varargs at 8-byte alignment.
3232 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003233 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003234
3235 if (MFI.hasMustTailInVarArgFunc()) {
3236 SmallVector<MVT, 2> RegParmTypes;
3237 RegParmTypes.push_back(MVT::i64);
3238 RegParmTypes.push_back(MVT::f128);
3239 // Compute the set of forwarded registers. The rest are scratch.
3240 SmallVectorImpl<ForwardedRegister> &Forwards =
3241 FuncInfo->getForwardedMustTailRegParms();
3242 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3243 CC_AArch64_AAPCS);
Reid Klecknerb7a78c72019-05-24 01:27:20 +00003244
3245 // Conservatively forward X8, since it might be used for aggregate return.
3246 if (!CCInfo.isAllocated(AArch64::X8)) {
3247 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3248 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3249 }
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003250 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003251 }
3252
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003253 // On Windows, InReg pointers must be returned, so record the pointer in a
3254 // virtual register at the start of the function so it can be returned in the
3255 // epilogue.
3256 if (IsWin64) {
3257 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3258 if (Ins[I].Flags.isInReg()) {
3259 assert(!FuncInfo->getSRetReturnReg());
3260
3261 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3262 unsigned Reg =
3263 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3264 FuncInfo->setSRetReturnReg(Reg);
3265
3266 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3267 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3268 break;
3269 }
3270 }
3271 }
3272
Tim Northover3b0846e2014-05-24 12:50:23 +00003273 unsigned StackArgSize = CCInfo.getNextStackOffset();
3274 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3275 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3276 // This is a non-standard ABI so by fiat I say we're allowed to make full
3277 // use of the stack area to be popped, which must be aligned to 16 bytes in
3278 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003279 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003280
3281 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3282 // a multiple of 16.
3283 FuncInfo->setArgumentStackToRestore(StackArgSize);
3284
3285 // This realignment carries over to the available bytes below. Our own
3286 // callers will guarantee the space is free by giving an aligned value to
3287 // CALLSEQ_START.
3288 }
3289 // Even if we're not expected to free up the space, it's useful to know how
3290 // much is there while considering tail calls (because we can reuse it).
3291 FuncInfo->setBytesInStackArgArea(StackArgSize);
3292
Tri Vo6c47c622018-09-22 22:17:50 +00003293 if (Subtarget->hasCustomCallingConv())
3294 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3295
Tim Northover3b0846e2014-05-24 12:50:23 +00003296 return Chain;
3297}
3298
3299void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003300 SelectionDAG &DAG,
3301 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003302 SDValue &Chain) const {
3303 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003304 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003305 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003306 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003307 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003308
3309 SmallVector<SDValue, 8> MemOps;
3310
3311 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3312 AArch64::X3, AArch64::X4, AArch64::X5,
3313 AArch64::X6, AArch64::X7 };
3314 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003315 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003316
3317 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3318 int GPRIdx = 0;
3319 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003320 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003321 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003322 if (GPRSaveSize & 15)
3323 // The extra size here, if triggered, will always be 8.
3324 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3325 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003326 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003327
Mehdi Amini44ede332015-07-09 02:09:04 +00003328 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003329
3330 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3331 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3332 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003333 SDValue Store = DAG.getStore(
3334 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003335 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003336 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3337 GPRIdx,
3338 (i - FirstVariadicGPR) * 8)
3339 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003340 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003341 FIN =
3342 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003343 }
3344 }
3345 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3346 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3347
Martin Storsjo2f24e932017-07-17 20:05:19 +00003348 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003349 static const MCPhysReg FPRArgRegs[] = {
3350 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3351 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3352 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003353 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003354
3355 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3356 int FPRIdx = 0;
3357 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003358 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003359
Mehdi Amini44ede332015-07-09 02:09:04 +00003360 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003361
3362 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3363 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3364 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3365
Alex Lorenze40c8a22015-08-11 23:09:45 +00003366 SDValue Store = DAG.getStore(
3367 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003368 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003369 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003370 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3371 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003372 }
3373 }
3374 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3375 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3376 }
3377
3378 if (!MemOps.empty()) {
3379 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3380 }
3381}
3382
3383/// LowerCallResult - Lower the result values of a call into the
3384/// appropriate copies out of appropriate physical registers.
3385SDValue AArch64TargetLowering::LowerCallResult(
3386 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003387 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3388 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003389 SDValue ThisVal) const {
3390 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3391 ? RetCC_AArch64_WebKit_JS
3392 : RetCC_AArch64_AAPCS;
3393 // Assign locations to each value returned by this call.
3394 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003395 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3396 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003397 CCInfo.AnalyzeCallResult(Ins, RetCC);
3398
3399 // Copy all of the result registers out of their specified physreg.
3400 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3401 CCValAssign VA = RVLocs[i];
3402
3403 // Pass 'this' value directly from the argument to return value, to avoid
3404 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003405 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003406 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3407 "unexpected return calling convention register assignment");
3408 InVals.push_back(ThisVal);
3409 continue;
3410 }
3411
3412 SDValue Val =
3413 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3414 Chain = Val.getValue(1);
3415 InFlag = Val.getValue(2);
3416
3417 switch (VA.getLocInfo()) {
3418 default:
3419 llvm_unreachable("Unknown loc info!");
3420 case CCValAssign::Full:
3421 break;
3422 case CCValAssign::BCvt:
3423 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3424 break;
3425 }
3426
3427 InVals.push_back(Val);
3428 }
3429
3430 return Chain;
3431}
3432
Matthias Braun1af14142016-09-13 19:27:38 +00003433/// Return true if the calling convention is one that we can guarantee TCO for.
3434static bool canGuaranteeTCO(CallingConv::ID CC) {
3435 return CC == CallingConv::Fast;
3436}
3437
3438/// Return true if we might ever do TCO for calls with this calling convention.
3439static bool mayTailCallThisCC(CallingConv::ID CC) {
3440 switch (CC) {
3441 case CallingConv::C:
3442 case CallingConv::PreserveMost:
3443 case CallingConv::Swift:
3444 return true;
3445 default:
3446 return canGuaranteeTCO(CC);
3447 }
3448}
3449
Tim Northover3b0846e2014-05-24 12:50:23 +00003450bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3451 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003452 const SmallVectorImpl<ISD::OutputArg> &Outs,
3453 const SmallVectorImpl<SDValue> &OutVals,
3454 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003455 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003456 return false;
3457
Matthias Braun8d414362016-03-30 22:46:04 +00003458 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003459 const Function &CallerF = MF.getFunction();
3460 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003461 bool CCMatch = CallerCC == CalleeCC;
3462
3463 // Byval parameters hand the function a pointer directly into the stack area
3464 // we want to reuse during a tail call. Working around this *is* possible (see
3465 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003466 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3467 e = CallerF.arg_end();
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003468 i != e; ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003469 if (i->hasByValAttr())
3470 return false;
3471
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003472 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3473 // In this case, it is necessary to save/restore X0 in the callee. Tail
3474 // call opt interferes with this. So we disable tail call opt when the
3475 // caller has an argument with "inreg" attribute.
3476
3477 // FIXME: Check whether the callee also has an "inreg" argument.
3478 if (i->hasInRegAttr())
3479 return false;
3480 }
3481
Matthias Braun1af14142016-09-13 19:27:38 +00003482 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3483 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003484
Oliver Stannard12993dd2014-08-18 12:42:15 +00003485 // Externally-defined functions with weak linkage should not be
3486 // tail-called on AArch64 when the OS does not support dynamic
3487 // pre-emption of symbols, as the AAELF spec requires normal calls
3488 // to undefined weak functions to be replaced with a NOP or jump to the
3489 // next instruction. The behaviour of branch instructions in this
3490 // situation (as used for tail calls) is implementation-defined, so we
3491 // cannot rely on the linker replacing the tail call with a return.
3492 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3493 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003494 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003495 if (GV->hasExternalWeakLinkage() &&
3496 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003497 return false;
3498 }
3499
Tim Northover3b0846e2014-05-24 12:50:23 +00003500 // Now we search for cases where we can use a tail call without changing the
3501 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3502 // concept.
3503
3504 // I want anyone implementing a new calling convention to think long and hard
3505 // about this assert.
3506 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3507 "Unexpected variadic calling convention");
3508
Matthias Braun8d414362016-03-30 22:46:04 +00003509 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003510 if (isVarArg && !Outs.empty()) {
3511 // At least two cases here: if caller is fastcc then we can't have any
3512 // memory arguments (we'd be expected to clean up the stack afterwards). If
3513 // caller is C then we could potentially use its argument area.
3514
3515 // FIXME: for now we take the most conservative of these in both cases:
3516 // disallow all variadic memory operands.
3517 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003518 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003519
3520 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003521 for (const CCValAssign &ArgLoc : ArgLocs)
3522 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003523 return false;
3524 }
3525
Matthias Braun8d414362016-03-30 22:46:04 +00003526 // Check that the call results are passed in the same way.
3527 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3528 CCAssignFnForCall(CalleeCC, isVarArg),
3529 CCAssignFnForCall(CallerCC, isVarArg)))
3530 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003531 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003532 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3533 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003534 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003535 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003536 if (Subtarget->hasCustomCallingConv()) {
3537 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3538 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3539 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003540 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003541 return false;
3542 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003543
3544 // Nothing more to check if the callee is taking no arguments
3545 if (Outs.empty())
3546 return true;
3547
3548 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003549 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003550
3551 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3552
3553 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3554
Matthias Braun74a0bd32016-04-13 21:43:16 +00003555 // If the stack arguments for this call do not fit into our own save area then
3556 // the call cannot be made tail.
3557 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3558 return false;
3559
Matthias Braun46b0f032016-04-14 01:10:42 +00003560 const MachineRegisterInfo &MRI = MF.getRegInfo();
3561 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3562 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003563
3564 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003565}
3566
3567SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3568 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003569 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003570 int ClobberedFI) const {
3571 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003572 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3573 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003574
3575 // Include the original chain at the beginning of the list. When this is
3576 // used by target LowerCall hooks, this helps legalize find the
3577 // CALLSEQ_BEGIN node.
3578 ArgChains.push_back(Chain);
3579
3580 // Add a chain value for each stack argument corresponding
3581 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3582 UE = DAG.getEntryNode().getNode()->use_end();
3583 U != UE; ++U)
3584 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3585 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3586 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003587 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003588 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003589 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003590
3591 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3592 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3593 ArgChains.push_back(SDValue(L, 1));
3594 }
3595
3596 // Build a tokenfactor for all the chains.
3597 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3598}
3599
3600bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3601 bool TailCallOpt) const {
3602 return CallCC == CallingConv::Fast && TailCallOpt;
3603}
3604
Tim Northover3b0846e2014-05-24 12:50:23 +00003605/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3606/// and add input and output parameter nodes.
3607SDValue
3608AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3609 SmallVectorImpl<SDValue> &InVals) const {
3610 SelectionDAG &DAG = CLI.DAG;
3611 SDLoc &DL = CLI.DL;
3612 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3613 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3614 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3615 SDValue Chain = CLI.Chain;
3616 SDValue Callee = CLI.Callee;
3617 bool &IsTailCall = CLI.IsTailCall;
3618 CallingConv::ID CallConv = CLI.CallConv;
3619 bool IsVarArg = CLI.IsVarArg;
3620
3621 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003622 bool IsThisReturn = false;
3623
3624 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3625 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3626 bool IsSibCall = false;
3627
3628 if (IsTailCall) {
3629 // Check if it's really possible to do a tail call.
3630 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003631 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003632 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003633 report_fatal_error("failed to perform tail call elimination on a call "
3634 "site marked musttail");
3635
3636 // A sibling call is one where we're under the usual C ABI and not planning
3637 // to change that but can still do a tail call:
3638 if (!TailCallOpt && IsTailCall)
3639 IsSibCall = true;
3640
3641 if (IsTailCall)
3642 ++NumTailCalls;
3643 }
3644
3645 // Analyze operands of the call, assigning locations to each operand.
3646 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003647 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3648 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003649
3650 if (IsVarArg) {
3651 // Handle fixed and variable vector arguments differently.
3652 // Variable vector arguments always go into memory.
3653 unsigned NumArgs = Outs.size();
3654
3655 for (unsigned i = 0; i != NumArgs; ++i) {
3656 MVT ArgVT = Outs[i].VT;
3657 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3658 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3659 /*IsVarArg=*/ !Outs[i].IsFixed);
3660 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3661 assert(!Res && "Call operand has unhandled type");
3662 (void)Res;
3663 }
3664 } else {
3665 // At this point, Outs[].VT may already be promoted to i32. To correctly
3666 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3667 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3668 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3669 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3670 // LocVT.
3671 unsigned NumArgs = Outs.size();
3672 for (unsigned i = 0; i != NumArgs; ++i) {
3673 MVT ValVT = Outs[i].VT;
3674 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003675 EVT ActualVT = getValueType(DAG.getDataLayout(),
3676 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003677 /*AllowUnknown*/ true);
3678 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3679 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3680 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003681 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003682 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003683 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003684 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003685
3686 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003687 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003688 assert(!Res && "Call operand has unhandled type");
3689 (void)Res;
3690 }
3691 }
3692
3693 // Get a count of how many bytes are to be pushed on the stack.
3694 unsigned NumBytes = CCInfo.getNextStackOffset();
3695
3696 if (IsSibCall) {
3697 // Since we're not changing the ABI to make this a tail call, the memory
3698 // operands are already available in the caller's incoming argument space.
3699 NumBytes = 0;
3700 }
3701
3702 // FPDiff is the byte offset of the call's argument area from the callee's.
3703 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3704 // by this amount for a tail call. In a sibling call it must be 0 because the
3705 // caller will deallocate the entire stack and the callee still expects its
3706 // arguments to begin at SP+0. Completely unused for non-tail calls.
3707 int FPDiff = 0;
3708
3709 if (IsTailCall && !IsSibCall) {
3710 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3711
3712 // Since callee will pop argument stack as a tail call, we must keep the
3713 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003714 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003715
3716 // FPDiff will be negative if this tail call requires more space than we
3717 // would automatically have in our incoming argument space. Positive if we
3718 // can actually shrink the stack.
3719 FPDiff = NumReusableBytes - NumBytes;
3720
3721 // The stack pointer must be 16-byte aligned at all times it's used for a
3722 // memory operation, which in practice means at *all* times and in
3723 // particular across call boundaries. Therefore our own arguments started at
3724 // a 16-byte aligned SP and the delta applied for the tail call should
3725 // satisfy the same constraint.
3726 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3727 }
3728
3729 // Adjust the stack pointer for the new arguments...
3730 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003731 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003732 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003733
Mehdi Amini44ede332015-07-09 02:09:04 +00003734 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3735 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003736
3737 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3738 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003739 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003740
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003741 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3742 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3743 for (const auto &F : Forwards) {
3744 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3745 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3746 }
3747 }
3748
Tim Northover3b0846e2014-05-24 12:50:23 +00003749 // Walk the register/memloc assignments, inserting copies/loads.
3750 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3751 ++i, ++realArgIdx) {
3752 CCValAssign &VA = ArgLocs[i];
3753 SDValue Arg = OutVals[realArgIdx];
3754 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3755
3756 // Promote the value if needed.
3757 switch (VA.getLocInfo()) {
3758 default:
3759 llvm_unreachable("Unknown loc info!");
3760 case CCValAssign::Full:
3761 break;
3762 case CCValAssign::SExt:
3763 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3764 break;
3765 case CCValAssign::ZExt:
3766 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3767 break;
3768 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003769 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3770 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3771 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3772 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3773 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003774 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3775 break;
3776 case CCValAssign::BCvt:
3777 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3778 break;
3779 case CCValAssign::FPExt:
3780 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3781 break;
3782 }
3783
3784 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003785 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3786 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003787 assert(VA.getLocVT() == MVT::i64 &&
3788 "unexpected calling convention register assignment");
3789 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3790 "unexpected use of 'returned'");
3791 IsThisReturn = true;
3792 }
3793 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3794 } else {
3795 assert(VA.isMemLoc());
3796
3797 SDValue DstAddr;
3798 MachinePointerInfo DstInfo;
3799
3800 // FIXME: This works on big-endian for composite byvals, which are the
3801 // common case. It should also work for fundamental types too.
3802 uint32_t BEAlign = 0;
3803 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003804 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003805 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003806 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3807 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003808 if (OpSize < 8)
3809 BEAlign = 8 - OpSize;
3810 }
3811 unsigned LocMemOffset = VA.getLocMemOffset();
3812 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003813 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003814 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003815
3816 if (IsTailCall) {
3817 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003818 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003819
Mehdi Amini44ede332015-07-09 02:09:04 +00003820 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003821 DstInfo =
3822 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003823
3824 // Make sure any stack arguments overlapping with where we're storing
3825 // are loaded before this eventual operation. Otherwise they'll be
3826 // clobbered.
3827 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3828 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003829 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003830
Mehdi Amini44ede332015-07-09 02:09:04 +00003831 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003832 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3833 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003834 }
3835
3836 if (Outs[i].Flags.isByVal()) {
3837 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003838 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003839 SDValue Cpy = DAG.getMemcpy(
3840 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003841 /*isVol = */ false, /*AlwaysInline = */ false,
3842 /*isTailCall = */ false,
3843 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003844
3845 MemOpChains.push_back(Cpy);
3846 } else {
3847 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3848 // promoted to a legal register type i32, we should truncate Arg back to
3849 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003850 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3851 VA.getValVT() == MVT::i16)
3852 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003853
Justin Lebar9c375812016-07-15 18:27:10 +00003854 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003855 MemOpChains.push_back(Store);
3856 }
3857 }
3858 }
3859
3860 if (!MemOpChains.empty())
3861 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3862
3863 // Build a sequence of copy-to-reg nodes chained together with token chain
3864 // and flag operands which copy the outgoing args into the appropriate regs.
3865 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003866 for (auto &RegToPass : RegsToPass) {
3867 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3868 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003869 InFlag = Chain.getValue(1);
3870 }
3871
3872 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3873 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3874 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003875 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3876 auto GV = G->getGlobal();
3877 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3878 AArch64II::MO_GOT) {
3879 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3880 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003881 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3882 assert(Subtarget->isTargetWindows() &&
3883 "Windows is the only supported COFF target");
3884 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003885 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003886 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003887 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3888 }
3889 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3890 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3891 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003892 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003893 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3894 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003895 } else {
3896 const char *Sym = S->getSymbol();
3897 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003898 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003899 }
3900
3901 // We don't usually want to end the call-sequence here because we would tidy
3902 // the frame up *after* the call, however in the ABI-changing tail-call case
3903 // we've carefully laid out the parameters so that when sp is reset they'll be
3904 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003905 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003906 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3907 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003908 InFlag = Chain.getValue(1);
3909 }
3910
3911 std::vector<SDValue> Ops;
3912 Ops.push_back(Chain);
3913 Ops.push_back(Callee);
3914
3915 if (IsTailCall) {
3916 // Each tail call may have to adjust the stack by a different amount, so
3917 // this information must travel along with the operation for eventual
3918 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003919 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003920 }
3921
3922 // Add argument registers to the end of the list so that they are known live
3923 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003924 for (auto &RegToPass : RegsToPass)
3925 Ops.push_back(DAG.getRegister(RegToPass.first,
3926 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003927
3928 // Add a register mask operand representing the call-preserved registers.
3929 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003930 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003931 if (IsThisReturn) {
3932 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003933 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003934 if (!Mask) {
3935 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003936 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003937 }
3938 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003939 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003940
Tri Vo6c47c622018-09-22 22:17:50 +00003941 if (Subtarget->hasCustomCallingConv())
3942 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3943
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003944 if (TRI->isAnyArgRegReserved(MF))
3945 TRI->emitReservedArgRegCallError(MF);
3946
Tim Northover3b0846e2014-05-24 12:50:23 +00003947 assert(Mask && "Missing call preserved mask for calling convention");
3948 Ops.push_back(DAG.getRegisterMask(Mask));
3949
3950 if (InFlag.getNode())
3951 Ops.push_back(InFlag);
3952
3953 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3954
3955 // If we're doing a tall call, use a TC_RETURN here rather than an
3956 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003957 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003958 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003959 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003960 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003961
3962 // Returns a chain and a flag for retval copy to use.
3963 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3964 InFlag = Chain.getValue(1);
3965
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003966 uint64_t CalleePopBytes =
3967 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003968
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003969 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3970 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3971 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003972 if (!Ins.empty())
3973 InFlag = Chain.getValue(1);
3974
3975 // Handle result values, copying them out of physregs into vregs that we
3976 // return.
3977 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3978 InVals, IsThisReturn,
3979 IsThisReturn ? OutVals[0] : SDValue());
3980}
3981
3982bool AArch64TargetLowering::CanLowerReturn(
3983 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3984 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3985 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3986 ? RetCC_AArch64_WebKit_JS
3987 : RetCC_AArch64_AAPCS;
3988 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003989 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003990 return CCInfo.CheckReturn(Outs, RetCC);
3991}
3992
3993SDValue
3994AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3995 bool isVarArg,
3996 const SmallVectorImpl<ISD::OutputArg> &Outs,
3997 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003998 const SDLoc &DL, SelectionDAG &DAG) const {
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003999 auto &MF = DAG.getMachineFunction();
4000 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4001
Tim Northover3b0846e2014-05-24 12:50:23 +00004002 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4003 ? RetCC_AArch64_WebKit_JS
4004 : RetCC_AArch64_AAPCS;
4005 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00004006 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4007 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00004008 CCInfo.AnalyzeReturn(Outs, RetCC);
4009
4010 // Copy the result values into the output registers.
4011 SDValue Flag;
4012 SmallVector<SDValue, 4> RetOps(1, Chain);
4013 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4014 ++i, ++realRVLocIdx) {
4015 CCValAssign &VA = RVLocs[i];
4016 assert(VA.isRegLoc() && "Can only return in registers!");
4017 SDValue Arg = OutVals[realRVLocIdx];
4018
4019 switch (VA.getLocInfo()) {
4020 default:
4021 llvm_unreachable("Unknown loc info!");
4022 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00004023 if (Outs[i].ArgVT == MVT::i1) {
4024 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4025 // value. This is strictly redundant on Darwin (which uses "zeroext
4026 // i1"), but will be optimised out before ISel.
4027 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4028 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4029 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004030 break;
4031 case CCValAssign::BCvt:
4032 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4033 break;
4034 }
4035
4036 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
4037 Flag = Chain.getValue(1);
4038 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4039 }
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00004040
4041 // Windows AArch64 ABIs require that for returning structs by value we copy
4042 // the sret argument into X0 for the return.
4043 // We saved the argument into a virtual register in the entry block,
4044 // so now we copy the value out and into X0.
4045 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4046 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4047 getPointerTy(MF.getDataLayout()));
4048
4049 unsigned RetValReg = AArch64::X0;
4050 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4051 Flag = Chain.getValue(1);
4052
4053 RetOps.push_back(
4054 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4055 }
4056
Manman Rencbe4f942015-12-16 21:04:19 +00004057 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4058 const MCPhysReg *I =
4059 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4060 if (I) {
4061 for (; *I; ++I) {
4062 if (AArch64::GPR64RegClass.contains(*I))
4063 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4064 else if (AArch64::FPR64RegClass.contains(*I))
4065 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4066 else
4067 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4068 }
4069 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004070
4071 RetOps[0] = Chain; // Update chain.
4072
4073 // Add the flag if we have it.
4074 if (Flag.getNode())
4075 RetOps.push_back(Flag);
4076
4077 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4078}
4079
4080//===----------------------------------------------------------------------===//
4081// Other Lowering Code
4082//===----------------------------------------------------------------------===//
4083
Joel Jonesa7c4a522017-04-21 17:31:03 +00004084SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4085 SelectionDAG &DAG,
4086 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004087 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4088 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004089}
4090
4091SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4092 SelectionDAG &DAG,
4093 unsigned Flag) const {
4094 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4095}
4096
4097SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4098 SelectionDAG &DAG,
4099 unsigned Flag) const {
4100 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4101 N->getOffset(), Flag);
4102}
4103
4104SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4105 SelectionDAG &DAG,
4106 unsigned Flag) const {
4107 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4108}
4109
4110// (loadGOT sym)
4111template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004112SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4113 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004114 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004115 SDLoc DL(N);
4116 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004117 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004118 // FIXME: Once remat is capable of dealing with instructions with register
4119 // operands, expand this into two nodes instead of using a wrapper node.
4120 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4121}
4122
4123// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4124template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004125SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4126 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004127 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004128 SDLoc DL(N);
4129 EVT Ty = getPointerTy(DAG.getDataLayout());
4130 const unsigned char MO_NC = AArch64II::MO_NC;
4131 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004132 AArch64ISD::WrapperLarge, DL, Ty,
4133 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4134 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4135 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4136 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004137}
4138
4139// (addlow (adrp %hi(sym)) %lo(sym))
4140template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004141SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4142 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004143 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004144 SDLoc DL(N);
4145 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004146 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004147 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004148 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004149 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4150 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4151}
4152
David Green9dd1d452018-08-22 11:31:39 +00004153// (adr sym)
4154template <class NodeTy>
4155SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4156 unsigned Flags) const {
4157 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4158 SDLoc DL(N);
4159 EVT Ty = getPointerTy(DAG.getDataLayout());
4160 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4161 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4162}
4163
Tim Northover3b0846e2014-05-24 12:50:23 +00004164SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4165 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004166 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004167 const GlobalValue *GV = GN->getGlobal();
Peter Collingbourne33773d52019-07-31 20:14:09 +00004168 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004169
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004170 if (OpFlags != AArch64II::MO_NO_FLAG)
4171 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4172 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004173
David Green9dd1d452018-08-22 11:31:39 +00004174 // This also catches the large code model case for Darwin, and tiny code
4175 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004176 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004177 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004178 }
4179
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004180 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004181 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004182 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004183 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004184 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004185 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004186 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004187 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004188 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4189 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004190 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004191 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4192 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4193 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004194}
4195
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004196/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004197/// and calls to compute the variable's address (for Darwin, currently) and
4198/// return an SDValue containing the final node.
4199
4200/// Darwin only has one TLS scheme which must be capable of dealing with the
4201/// fully general situation, in the worst case. This means:
4202/// + "extern __thread" declaration.
4203/// + Defined in a possibly unknown dynamic library.
4204///
4205/// The general system is that each __thread variable has a [3 x i64] descriptor
4206/// which contains information used by the runtime to calculate the address. The
4207/// only part of this the compiler needs to know about is the first xword, which
4208/// contains a function pointer that must be called with the address of the
4209/// entire descriptor in "x0".
4210///
4211/// Since this descriptor may be in a different unit, in general even the
4212/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4213/// is:
4214/// adrp x0, _var@TLVPPAGE
4215/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4216/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4217/// ; the function pointer
4218/// blr x1 ; Uses descriptor address in x0
4219/// ; Address of _var is now in x0.
4220///
4221/// If the address of _var's descriptor *is* known to the linker, then it can
4222/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4223/// a slight efficiency gain.
4224SDValue
4225AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4226 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004227 assert(Subtarget->isTargetDarwin() &&
4228 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004229
4230 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004231 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004232 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4233
4234 SDValue TLVPAddr =
4235 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4236 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4237
4238 // The first entry in the descriptor is a function pointer that we must call
4239 // to obtain the address of the variable.
4240 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004241 SDValue FuncTLVGet = DAG.getLoad(
4242 MVT::i64, DL, Chain, DescAddr,
4243 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4244 /* Alignment = */ 8,
4245 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4246 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004247 Chain = FuncTLVGet.getValue(1);
4248
Matthias Braun941a7052016-07-28 18:40:00 +00004249 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4250 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004251
4252 // TLS calls preserve all registers except those that absolutely must be
4253 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4254 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004255 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4256 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4257 if (Subtarget->hasCustomCallingConv())
4258 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004259
4260 // Finally, we can make the call. This is just a degenerate version of a
4261 // normal AArch64 call node: x0 takes the address of the descriptor, and
4262 // returns the address of the variable in this thread.
4263 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4264 Chain =
4265 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4266 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4267 DAG.getRegisterMask(Mask), Chain.getValue(1));
4268 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4269}
4270
4271/// When accessing thread-local variables under either the general-dynamic or
4272/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4273/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004274/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004275///
Kristof Beylsaea84612015-03-04 09:12:08 +00004276/// The sequence is:
4277/// adrp x0, :tlsdesc:var
4278/// ldr x1, [x0, #:tlsdesc_lo12:var]
4279/// add x0, x0, #:tlsdesc_lo12:var
4280/// .tlsdesccall var
4281/// blr x1
4282/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004283///
Kristof Beylsaea84612015-03-04 09:12:08 +00004284/// The above sequence must be produced unscheduled, to enable the linker to
4285/// optimize/relax this sequence.
4286/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4287/// above sequence, and expanded really late in the compilation flow, to ensure
4288/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004289SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4290 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004291 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004292 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004293
Kristof Beylsaea84612015-03-04 09:12:08 +00004294 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004295 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004296
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004297 Chain =
4298 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004299 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004300
4301 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4302}
4303
4304SDValue
4305AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4306 SelectionDAG &DAG) const {
4307 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004308 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4309 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004310 // Different choices can be made for the maximum size of the TLS area for a
4311 // module. For the small address model, the default TLS size is 16MiB and the
4312 // maximum TLS size is 4GiB.
4313 // FIXME: add -mtls-size command line option and make it control the 16MiB
4314 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004315 // FIXME: add tiny codemodel support. We currently generate the same code as
4316 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004317 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4318
4319 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004320
Kristof Beylsaea84612015-03-04 09:12:08 +00004321 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4322 if (Model == TLSModel::LocalDynamic)
4323 Model = TLSModel::GeneralDynamic;
4324 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004325
4326 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004327 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004328 SDLoc DL(Op);
4329 const GlobalValue *GV = GA->getGlobal();
4330
4331 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4332
4333 if (Model == TLSModel::LocalExec) {
4334 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004335 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004336 SDValue LoVar = DAG.getTargetGlobalAddress(
4337 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004338 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004339
Kristof Beylsaea84612015-03-04 09:12:08 +00004340 SDValue TPWithOff_lo =
4341 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004342 HiVar,
4343 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004344 0);
4345 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004346 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4347 LoVar,
4348 DAG.getTargetConstant(0, DL, MVT::i32)),
4349 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004350 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004351 } else if (Model == TLSModel::InitialExec) {
4352 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4353 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4354 } else if (Model == TLSModel::LocalDynamic) {
4355 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4356 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4357 // the beginning of the module's TLS region, followed by a DTPREL offset
4358 // calculation.
4359
4360 // These accesses will need deduplicating if there's more than one.
4361 AArch64FunctionInfo *MFI =
4362 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4363 MFI->incNumLocalDynamicTLSAccesses();
4364
Tim Northover3b0846e2014-05-24 12:50:23 +00004365 // The call needs a relocation too for linker relaxation. It doesn't make
4366 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4367 // the address.
4368 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4369 AArch64II::MO_TLS);
4370
4371 // Now we can calculate the offset from TPIDR_EL0 to this module's
4372 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004373 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004374
4375 // Now use :dtprel_whatever: operations to calculate this variable's offset
4376 // in its thread-storage area.
4377 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004378 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004379 SDValue LoVar = DAG.getTargetGlobalAddress(
4380 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004381 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4382
Kristof Beylsaea84612015-03-04 09:12:08 +00004383 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004384 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004385 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004386 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4387 DAG.getTargetConstant(0, DL, MVT::i32)),
4388 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004389 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004390 // The call needs a relocation too for linker relaxation. It doesn't make
4391 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4392 // the address.
4393 SDValue SymAddr =
4394 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4395
4396 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004397 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004398 } else
4399 llvm_unreachable("Unsupported ELF TLS access model");
4400
4401 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4402}
4403
Martin Storsjocc240962018-03-10 19:05:21 +00004404SDValue
4405AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4406 SelectionDAG &DAG) const {
4407 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4408
4409 SDValue Chain = DAG.getEntryNode();
4410 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4411 SDLoc DL(Op);
4412
4413 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4414
4415 // Load the ThreadLocalStoragePointer from the TEB
4416 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4417 SDValue TLSArray =
4418 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4419 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4420 Chain = TLSArray.getValue(1);
4421
4422 // Load the TLS index from the C runtime;
4423 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4424 // This also does the same as LOADgot, but using a generic i32 load,
4425 // while LOADgot only loads i64.
4426 SDValue TLSIndexHi =
4427 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4428 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4429 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4430 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4431 SDValue TLSIndex =
4432 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4433 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4434 Chain = TLSIndex.getValue(1);
4435
4436 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4437 // offset into the TLSArray.
4438 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4439 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4440 DAG.getConstant(3, DL, PtrVT));
4441 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4442 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4443 MachinePointerInfo());
4444 Chain = TLS.getValue(1);
4445
4446 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4447 const GlobalValue *GV = GA->getGlobal();
4448 SDValue TGAHi = DAG.getTargetGlobalAddress(
4449 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4450 SDValue TGALo = DAG.getTargetGlobalAddress(
4451 GV, DL, PtrVT, 0,
4452 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4453
4454 // Add the offset from the start of the .tls section (section base).
4455 SDValue Addr =
4456 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4457 DAG.getTargetConstant(0, DL, MVT::i32)),
4458 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004459 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004460 return Addr;
4461}
4462
Tim Northover3b0846e2014-05-24 12:50:23 +00004463SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4464 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004465 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004466 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004467 return LowerToTLSEmulatedModel(GA, DAG);
4468
Tim Northover3b0846e2014-05-24 12:50:23 +00004469 if (Subtarget->isTargetDarwin())
4470 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004471 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004472 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004473 if (Subtarget->isTargetWindows())
4474 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004475
4476 llvm_unreachable("Unexpected platform trying to use TLS");
4477}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004478
Tim Northover3b0846e2014-05-24 12:50:23 +00004479SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4480 SDValue Chain = Op.getOperand(0);
4481 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4482 SDValue LHS = Op.getOperand(2);
4483 SDValue RHS = Op.getOperand(3);
4484 SDValue Dest = Op.getOperand(4);
4485 SDLoc dl(Op);
4486
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004487 MachineFunction &MF = DAG.getMachineFunction();
4488 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4489 // will not be produced, as they are conditional branch instructions that do
4490 // not set flags.
4491 bool ProduceNonFlagSettingCondBr =
4492 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4493
Tim Northover3b0846e2014-05-24 12:50:23 +00004494 // Handle f128 first, since lowering it will result in comparing the return
4495 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4496 // is expecting to deal with.
4497 if (LHS.getValueType() == MVT::f128) {
4498 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4499
4500 // If softenSetCCOperands returned a scalar, we need to compare the result
4501 // against zero to select between true and false values.
4502 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004503 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004504 CC = ISD::SETNE;
4505 }
4506 }
4507
4508 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4509 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004510 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4511 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004512 // Only lower legal XALUO ops.
4513 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4514 return SDValue();
4515
4516 // The actual operation with overflow check.
4517 AArch64CC::CondCode OFCC;
4518 SDValue Value, Overflow;
4519 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4520
4521 if (CC == ISD::SETNE)
4522 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004523 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004524
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004525 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4526 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004527 }
4528
4529 if (LHS.getValueType().isInteger()) {
4530 assert((LHS.getValueType() == RHS.getValueType()) &&
4531 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4532
4533 // If the RHS of the comparison is zero, we can potentially fold this
4534 // to a specialized branch.
4535 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004536 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004537 if (CC == ISD::SETEQ) {
4538 // See if we can use a TBZ to fold in an AND as well.
4539 // TBZ has a smaller branch displacement than CBZ. If the offset is
4540 // out of bounds, a late MI-layer pass rewrites branches.
4541 // 403.gcc is an example that hits this case.
4542 if (LHS.getOpcode() == ISD::AND &&
4543 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4544 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4545 SDValue Test = LHS.getOperand(0);
4546 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004547 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004548 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4549 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004550 }
4551
4552 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4553 } else if (CC == ISD::SETNE) {
4554 // See if we can use a TBZ to fold in an AND as well.
4555 // TBZ has a smaller branch displacement than CBZ. If the offset is
4556 // out of bounds, a late MI-layer pass rewrites branches.
4557 // 403.gcc is an example that hits this case.
4558 if (LHS.getOpcode() == ISD::AND &&
4559 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4560 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4561 SDValue Test = LHS.getOperand(0);
4562 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004563 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004564 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4565 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004566 }
4567
4568 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004569 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4570 // Don't combine AND since emitComparison converts the AND to an ANDS
4571 // (a.k.a. TST) and the test in the test bit and branch instruction
4572 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004573 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004574 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004575 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004576 }
4577 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004578 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004579 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004580 // Don't combine AND since emitComparison converts the AND to an ANDS
4581 // (a.k.a. TST) and the test in the test bit and branch instruction
4582 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004583 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004584 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004585 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004586 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004587
4588 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004589 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004590 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4591 Cmp);
4592 }
4593
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004594 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4595 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004596
4597 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4598 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004599 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004600 AArch64CC::CondCode CC1, CC2;
4601 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004602 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004603 SDValue BR1 =
4604 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4605 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004606 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004607 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4608 Cmp);
4609 }
4610
4611 return BR1;
4612}
4613
4614SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4615 SelectionDAG &DAG) const {
4616 EVT VT = Op.getValueType();
4617 SDLoc DL(Op);
4618
4619 SDValue In1 = Op.getOperand(0);
4620 SDValue In2 = Op.getOperand(1);
4621 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004622
4623 if (SrcVT.bitsLT(VT))
4624 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4625 else if (SrcVT.bitsGT(VT))
4626 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004627
4628 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004629 uint64_t EltMask;
4630 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004631
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004632 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004633 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004634 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004635 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004636 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004637 DAG.getUNDEF(VecVT), In2);
4638 } else {
4639 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4640 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4641 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004642 };
4643
4644 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4645 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4646 EltMask = 0x80000000ULL;
4647 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004648 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004649 VecVT = MVT::v2i64;
4650
Eric Christopher572e03a2015-06-19 01:53:21 +00004651 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004652 // immediate moves cannot materialize that in a single instruction for
4653 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004654 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004655
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004656 setVecVal(AArch64::dsub);
4657 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4658 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4659 EltMask = 0x8000ULL;
4660 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004661 } else {
4662 llvm_unreachable("Invalid type for copysign!");
4663 }
4664
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004665 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004666
4667 // If we couldn't materialize the mask above, then the mask vector will be
4668 // the zero vector, and we need to negate it here.
4669 if (VT == MVT::f64 || VT == MVT::v2f64) {
4670 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4671 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4672 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4673 }
4674
4675 SDValue Sel =
4676 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4677
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004678 if (VT == MVT::f16)
4679 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004680 if (VT == MVT::f32)
4681 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4682 else if (VT == MVT::f64)
4683 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4684 else
4685 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4686}
4687
4688SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004689 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004690 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004691 return SDValue();
4692
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004693 if (!Subtarget->hasNEON())
4694 return SDValue();
4695
Tim Northover3b0846e2014-05-24 12:50:23 +00004696 // While there is no integer popcount instruction, it can
4697 // be more efficiently lowered to the following sequence that uses
4698 // AdvSIMD registers/instructions as long as the copies to/from
4699 // the AdvSIMD registers are cheap.
4700 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4701 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4702 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4703 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4704 SDValue Val = Op.getOperand(0);
4705 SDLoc DL(Op);
4706 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004707
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004708 if (VT == MVT::i32 || VT == MVT::i64) {
4709 if (VT == MVT::i32)
4710 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4711 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004712
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004713 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4714 SDValue UaddLV = DAG.getNode(
4715 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4716 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004717
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004718 if (VT == MVT::i64)
4719 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4720 return UaddLV;
4721 }
4722
4723 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4724 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4725 "Unexpected type for custom ctpop lowering");
4726
4727 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4728 Val = DAG.getBitcast(VT8Bit, Val);
4729 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4730
4731 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4732 unsigned EltSize = 8;
4733 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4734 while (EltSize != VT.getScalarSizeInBits()) {
4735 EltSize *= 2;
4736 NumElts /= 2;
4737 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4738 Val = DAG.getNode(
4739 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4740 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4741 }
4742
4743 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004744}
4745
4746SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4747
4748 if (Op.getValueType().isVector())
4749 return LowerVSETCC(Op, DAG);
4750
4751 SDValue LHS = Op.getOperand(0);
4752 SDValue RHS = Op.getOperand(1);
4753 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4754 SDLoc dl(Op);
4755
4756 // We chose ZeroOrOneBooleanContents, so use zero and one.
4757 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004758 SDValue TVal = DAG.getConstant(1, dl, VT);
4759 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004760
4761 // Handle f128 first, since one possible outcome is a normal integer
4762 // comparison which gets picked up by the next if statement.
4763 if (LHS.getValueType() == MVT::f128) {
4764 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4765
4766 // If softenSetCCOperands returned a scalar, use it.
4767 if (!RHS.getNode()) {
4768 assert(LHS.getValueType() == Op.getValueType() &&
4769 "Unexpected setcc expansion!");
4770 return LHS;
4771 }
4772 }
4773
4774 if (LHS.getValueType().isInteger()) {
4775 SDValue CCVal;
4776 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004777 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004778
4779 // Note that we inverted the condition above, so we reverse the order of
4780 // the true and false operands here. This will allow the setcc to be
4781 // matched to a single CSINC instruction.
4782 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4783 }
4784
4785 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004786 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4787 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004788
4789 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4790 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004791 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004792
4793 AArch64CC::CondCode CC1, CC2;
4794 changeFPCCToAArch64CC(CC, CC1, CC2);
4795 if (CC2 == AArch64CC::AL) {
4796 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004797 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004798
4799 // Note that we inverted the condition above, so we reverse the order of
4800 // the true and false operands here. This will allow the setcc to be
4801 // matched to a single CSINC instruction.
4802 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4803 } else {
4804 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4805 // totally clean. Some of them require two CSELs to implement. As is in
4806 // this case, we emit the first CSEL and then emit a second using the output
4807 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4808
4809 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004810 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004811 SDValue CS1 =
4812 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4813
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004814 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004815 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4816 }
4817}
4818
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004819SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4820 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004821 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004822 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004823 // Handle f128 first, because it will result in a comparison of some RTLIB
4824 // call result against zero.
4825 if (LHS.getValueType() == MVT::f128) {
4826 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4827
4828 // If softenSetCCOperands returned a scalar, we need to compare the result
4829 // against zero to select between true and false values.
4830 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004831 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004832 CC = ISD::SETNE;
4833 }
4834 }
4835
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004836 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004837 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004838 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4839 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4840 }
4841
4842 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004843 if (LHS.getValueType().isInteger()) {
4844 assert((LHS.getValueType() == RHS.getValueType()) &&
4845 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4846
4847 unsigned Opcode = AArch64ISD::CSEL;
4848
4849 // If both the TVal and the FVal are constants, see if we can swap them in
4850 // order to for a CSINV or CSINC out of them.
4851 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4852 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4853
4854 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4855 std::swap(TVal, FVal);
4856 std::swap(CTVal, CFVal);
4857 CC = ISD::getSetCCInverse(CC, true);
4858 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4859 std::swap(TVal, FVal);
4860 std::swap(CTVal, CFVal);
4861 CC = ISD::getSetCCInverse(CC, true);
4862 } else if (TVal.getOpcode() == ISD::XOR) {
4863 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4864 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004865 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004866 std::swap(TVal, FVal);
4867 std::swap(CTVal, CFVal);
4868 CC = ISD::getSetCCInverse(CC, true);
4869 }
4870 } else if (TVal.getOpcode() == ISD::SUB) {
4871 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4872 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004873 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004874 std::swap(TVal, FVal);
4875 std::swap(CTVal, CFVal);
4876 CC = ISD::getSetCCInverse(CC, true);
4877 }
4878 } else if (CTVal && CFVal) {
4879 const int64_t TrueVal = CTVal->getSExtValue();
4880 const int64_t FalseVal = CFVal->getSExtValue();
4881 bool Swap = false;
4882
4883 // If both TVal and FVal are constants, see if FVal is the
4884 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4885 // instead of a CSEL in that case.
4886 if (TrueVal == ~FalseVal) {
4887 Opcode = AArch64ISD::CSINV;
4888 } else if (TrueVal == -FalseVal) {
4889 Opcode = AArch64ISD::CSNEG;
4890 } else if (TVal.getValueType() == MVT::i32) {
4891 // If our operands are only 32-bit wide, make sure we use 32-bit
4892 // arithmetic for the check whether we can use CSINC. This ensures that
4893 // the addition in the check will wrap around properly in case there is
4894 // an overflow (which would not be the case if we do the check with
4895 // 64-bit arithmetic).
4896 const uint32_t TrueVal32 = CTVal->getZExtValue();
4897 const uint32_t FalseVal32 = CFVal->getZExtValue();
4898
4899 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4900 Opcode = AArch64ISD::CSINC;
4901
4902 if (TrueVal32 > FalseVal32) {
4903 Swap = true;
4904 }
4905 }
4906 // 64-bit check whether we can use CSINC.
4907 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4908 Opcode = AArch64ISD::CSINC;
4909
4910 if (TrueVal > FalseVal) {
4911 Swap = true;
4912 }
4913 }
4914
4915 // Swap TVal and FVal if necessary.
4916 if (Swap) {
4917 std::swap(TVal, FVal);
4918 std::swap(CTVal, CFVal);
4919 CC = ISD::getSetCCInverse(CC, true);
4920 }
4921
4922 if (Opcode != AArch64ISD::CSEL) {
4923 // Drop FVal since we can get its value by simply inverting/negating
4924 // TVal.
4925 FVal = TVal;
4926 }
4927 }
4928
Chad Rosier58f505b2016-08-26 18:05:50 +00004929 // Avoid materializing a constant when possible by reusing a known value in
4930 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004931 // is one, zero or negative one in the case of a CSEL. We can always
4932 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4933 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004934 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4935 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4936 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4937 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4938 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4939 // "a != C ? x : a" to avoid materializing C.
4940 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4941 TVal = LHS;
4942 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4943 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004944 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4945 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4946 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4947 // avoid materializing C.
4948 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4949 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4950 Opcode = AArch64ISD::CSINV;
4951 TVal = LHS;
4952 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4953 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004954 }
4955
Tim Northover3b0846e2014-05-24 12:50:23 +00004956 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004957 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004958 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004959 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4960 }
4961
4962 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004963 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4964 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004965 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004966 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004967 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004968
4969 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4970 // clean. Some of them require two CSELs to implement.
4971 AArch64CC::CondCode CC1, CC2;
4972 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004973
4974 if (DAG.getTarget().Options.UnsafeFPMath) {
4975 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4976 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4977 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4978 if (RHSVal && RHSVal->isZero()) {
4979 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4980 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4981
4982 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004983 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004984 TVal = LHS;
4985 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004986 CFVal && CFVal->isZero() &&
4987 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004988 FVal = LHS;
4989 }
4990 }
4991
4992 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004993 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004994 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4995
4996 // If we need a second CSEL, emit it, using the output of the first as the
4997 // RHS. We're effectively OR'ing the two CC's together.
4998 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004999 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00005000 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5001 }
5002
5003 // Otherwise, return the output of the first CSEL.
5004 return CS1;
5005}
5006
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005007SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5008 SelectionDAG &DAG) const {
5009 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5010 SDValue LHS = Op.getOperand(0);
5011 SDValue RHS = Op.getOperand(1);
5012 SDValue TVal = Op.getOperand(2);
5013 SDValue FVal = Op.getOperand(3);
5014 SDLoc DL(Op);
5015 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5016}
5017
5018SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5019 SelectionDAG &DAG) const {
5020 SDValue CCVal = Op->getOperand(0);
5021 SDValue TVal = Op->getOperand(1);
5022 SDValue FVal = Op->getOperand(2);
5023 SDLoc DL(Op);
5024
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005025 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5026 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00005027 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005028 // Only lower legal XALUO ops.
5029 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5030 return SDValue();
5031
5032 AArch64CC::CondCode OFCC;
5033 SDValue Value, Overflow;
5034 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005035 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005036
5037 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5038 CCVal, Overflow);
5039 }
5040
5041 // Lower it the same way as we would lower a SELECT_CC node.
5042 ISD::CondCode CC;
5043 SDValue LHS, RHS;
5044 if (CCVal.getOpcode() == ISD::SETCC) {
5045 LHS = CCVal.getOperand(0);
5046 RHS = CCVal.getOperand(1);
5047 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5048 } else {
5049 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005050 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005051 CC = ISD::SETNE;
5052 }
5053 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5054}
5055
Tim Northover3b0846e2014-05-24 12:50:23 +00005056SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5057 SelectionDAG &DAG) const {
5058 // Jump table entries as PC relative offsets. No additional tweaking
5059 // is necessary here. Just get the address of the jump table.
5060 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005061
5062 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5063 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005064 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005065 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5066 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005067 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005068 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005069}
5070
Tim Northover1c353412018-10-24 20:19:09 +00005071SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5072 SelectionDAG &DAG) const {
5073 // Jump table entries as PC relative offsets. No additional tweaking
5074 // is necessary here. Just get the address of the jump table.
5075 SDLoc DL(Op);
5076 SDValue JT = Op.getOperand(1);
5077 SDValue Entry = Op.getOperand(2);
5078 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5079
5080 SDNode *Dest =
5081 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5082 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5083 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5084 SDValue(Dest, 0));
5085}
5086
Tim Northover3b0846e2014-05-24 12:50:23 +00005087SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5088 SelectionDAG &DAG) const {
5089 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005090
5091 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5092 // Use the GOT for the large code model on iOS.
5093 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005094 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005095 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005096 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005097 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5098 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005099 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005100 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005101 }
5102}
5103
5104SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5105 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005106 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005107 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5108 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005109 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005110 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5111 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005112 }
David Green9dd1d452018-08-22 11:31:39 +00005113 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005114}
5115
5116SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5117 SelectionDAG &DAG) const {
5118 AArch64FunctionInfo *FuncInfo =
5119 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5120
5121 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005122 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5123 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005124 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5125 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005126 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005127}
5128
Martin Storsjo68266fa2017-07-13 17:03:12 +00005129SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5130 SelectionDAG &DAG) const {
5131 AArch64FunctionInfo *FuncInfo =
5132 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5133
5134 SDLoc DL(Op);
5135 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5136 ? FuncInfo->getVarArgsGPRIndex()
5137 : FuncInfo->getVarArgsStackIndex(),
5138 getPointerTy(DAG.getDataLayout()));
5139 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5140 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5141 MachinePointerInfo(SV));
5142}
5143
Tim Northover3b0846e2014-05-24 12:50:23 +00005144SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5145 SelectionDAG &DAG) const {
5146 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5147 // Standard, section B.3.
5148 MachineFunction &MF = DAG.getMachineFunction();
5149 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005150 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005151 SDLoc DL(Op);
5152
5153 SDValue Chain = Op.getOperand(0);
5154 SDValue VAList = Op.getOperand(1);
5155 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5156 SmallVector<SDValue, 4> MemOps;
5157
5158 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005159 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005160 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005161 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005162
5163 // void *__gr_top at offset 8
5164 int GPRSize = FuncInfo->getVarArgsGPRSize();
5165 if (GPRSize > 0) {
5166 SDValue GRTop, GRTopAddr;
5167
Mehdi Amini44ede332015-07-09 02:09:04 +00005168 GRTopAddr =
5169 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005170
Mehdi Amini44ede332015-07-09 02:09:04 +00005171 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5172 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5173 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005174
5175 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005176 MachinePointerInfo(SV, 8),
5177 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005178 }
5179
5180 // void *__vr_top at offset 16
5181 int FPRSize = FuncInfo->getVarArgsFPRSize();
5182 if (FPRSize > 0) {
5183 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005184 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5185 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005186
Mehdi Amini44ede332015-07-09 02:09:04 +00005187 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5188 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5189 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005190
5191 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005192 MachinePointerInfo(SV, 16),
5193 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005194 }
5195
5196 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005197 SDValue GROffsAddr =
5198 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005199 MemOps.push_back(DAG.getStore(
5200 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5201 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005202
5203 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005204 SDValue VROffsAddr =
5205 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005206 MemOps.push_back(DAG.getStore(
5207 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5208 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005209
5210 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5211}
5212
5213SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5214 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005215 MachineFunction &MF = DAG.getMachineFunction();
5216
Matthias Braunf1caa282017-12-15 22:22:58 +00005217 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005218 return LowerWin64_VASTART(Op, DAG);
5219 else if (Subtarget->isTargetDarwin())
5220 return LowerDarwin_VASTART(Op, DAG);
5221 else
5222 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005223}
5224
5225SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5226 SelectionDAG &DAG) const {
5227 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5228 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005229 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005230 unsigned VaListSize =
5231 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005232 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5233 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5234
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005235 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5236 Op.getOperand(2),
5237 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005238 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005239 MachinePointerInfo(SrcSV));
5240}
5241
5242SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5243 assert(Subtarget->isTargetDarwin() &&
5244 "automatic va_arg instruction only works on Darwin");
5245
5246 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5247 EVT VT = Op.getValueType();
5248 SDLoc DL(Op);
5249 SDValue Chain = Op.getOperand(0);
5250 SDValue Addr = Op.getOperand(1);
5251 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005252 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005253
Justin Lebar9c375812016-07-15 18:27:10 +00005254 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005255 Chain = VAList.getValue(1);
5256
5257 if (Align > 8) {
5258 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005259 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5260 DAG.getConstant(Align - 1, DL, PtrVT));
5261 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5262 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005263 }
5264
5265 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005266 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005267
5268 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5269 // up to 64 bits. At the very least, we have to increase the striding of the
5270 // vaargs list to match this, and for FP values we need to introduce
5271 // FP_ROUND nodes as well.
5272 if (VT.isInteger() && !VT.isVector())
5273 ArgSize = 8;
5274 bool NeedFPTrunc = false;
5275 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5276 ArgSize = 8;
5277 NeedFPTrunc = true;
5278 }
5279
5280 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005281 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5282 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005283 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005284 SDValue APStore =
5285 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005286
5287 // Load the actual argument out of the pointer VAList
5288 if (NeedFPTrunc) {
5289 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005290 SDValue WideFP =
5291 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005292 // Round the value down to an f32.
5293 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005294 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005295 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5296 // Merge the rounded value with the chain output of the load.
5297 return DAG.getMergeValues(Ops, DL);
5298 }
5299
Justin Lebar9c375812016-07-15 18:27:10 +00005300 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005301}
5302
5303SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5304 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005305 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5306 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005307
5308 EVT VT = Op.getValueType();
5309 SDLoc DL(Op);
5310 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5311 SDValue FrameAddr =
5312 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5313 while (Depth--)
5314 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005315 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005316 return FrameAddr;
5317}
5318
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005319SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5320 SelectionDAG &DAG) const {
5321 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5322
5323 EVT VT = getPointerTy(DAG.getDataLayout());
5324 SDLoc DL(Op);
5325 int FI = MFI.CreateFixedObject(4, 0, false);
5326 return DAG.getFrameIndex(FI, VT);
5327}
5328
Petr Hosekfcbec022019-02-13 17:28:47 +00005329#define GET_REGISTER_MATCHER
5330#include "AArch64GenAsmMatcher.inc"
5331
Tim Northover3b0846e2014-05-24 12:50:23 +00005332// FIXME? Maybe this could be a TableGen attribute on some registers and
5333// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005334unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5335 SelectionDAG &DAG) const {
Petr Hosekfcbec022019-02-13 17:28:47 +00005336 unsigned Reg = MatchRegisterName(RegName);
5337 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5338 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5339 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5340 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5341 Reg = 0;
5342 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005343 if (Reg)
5344 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005345 report_fatal_error(Twine("Invalid register name \""
5346 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005347}
5348
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005349SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5350 SelectionDAG &DAG) const {
5351 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5352
5353 EVT VT = Op.getValueType();
5354 SDLoc DL(Op);
5355
5356 SDValue FrameAddr =
5357 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5358 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5359
5360 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5361}
5362
Tim Northover3b0846e2014-05-24 12:50:23 +00005363SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5364 SelectionDAG &DAG) const {
5365 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005366 MachineFrameInfo &MFI = MF.getFrameInfo();
5367 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005368
5369 EVT VT = Op.getValueType();
5370 SDLoc DL(Op);
5371 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5372 if (Depth) {
5373 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005374 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005375 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5376 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005377 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005378 }
5379
5380 // Return LR, which contains the return address. Mark it an implicit live-in.
5381 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5382 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5383}
5384
5385/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5386/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5387SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5388 SelectionDAG &DAG) const {
5389 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5390 EVT VT = Op.getValueType();
5391 unsigned VTBits = VT.getSizeInBits();
5392 SDLoc dl(Op);
5393 SDValue ShOpLo = Op.getOperand(0);
5394 SDValue ShOpHi = Op.getOperand(1);
5395 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005396 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5397
5398 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5399
5400 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005401 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005402 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5403
5404 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5405 // is "undef". We wanted 0, so CSEL it directly.
5406 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5407 ISD::SETEQ, dl, DAG);
5408 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5409 HiBitsForLo =
5410 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5411 HiBitsForLo, CCVal, Cmp);
5412
Tim Northover3b0846e2014-05-24 12:50:23 +00005413 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005414 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005415
Tim Northoverf3be9d52015-12-02 00:33:54 +00005416 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5417 SDValue LoForNormalShift =
5418 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005419
Tim Northoverf3be9d52015-12-02 00:33:54 +00005420 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5421 dl, DAG);
5422 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5423 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5424 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5425 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005426
5427 // AArch64 shifts larger than the register width are wrapped rather than
5428 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005429 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5430 SDValue HiForBigShift =
5431 Opc == ISD::SRA
5432 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5433 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5434 : DAG.getConstant(0, dl, VT);
5435 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5436 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005437
5438 SDValue Ops[2] = { Lo, Hi };
5439 return DAG.getMergeValues(Ops, dl);
5440}
5441
5442/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5443/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5444SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005445 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005446 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5447 EVT VT = Op.getValueType();
5448 unsigned VTBits = VT.getSizeInBits();
5449 SDLoc dl(Op);
5450 SDValue ShOpLo = Op.getOperand(0);
5451 SDValue ShOpHi = Op.getOperand(1);
5452 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005453
5454 assert(Op.getOpcode() == ISD::SHL_PARTS);
5455 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005456 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005457 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5458
5459 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5460 // is "undef". We wanted 0, so CSEL it directly.
5461 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5462 ISD::SETEQ, dl, DAG);
5463 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5464 LoBitsForHi =
5465 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5466 LoBitsForHi, CCVal, Cmp);
5467
Tim Northover3b0846e2014-05-24 12:50:23 +00005468 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005469 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005470 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5471 SDValue HiForNormalShift =
5472 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005473
Tim Northoverf3be9d52015-12-02 00:33:54 +00005474 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005475
Tim Northoverf3be9d52015-12-02 00:33:54 +00005476 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5477 dl, DAG);
5478 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5479 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5480 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005481
5482 // AArch64 shifts of larger than register sizes are wrapped rather than
5483 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005484 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5485 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5486 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5487 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005488
5489 SDValue Ops[2] = { Lo, Hi };
5490 return DAG.getMergeValues(Ops, dl);
5491}
5492
5493bool AArch64TargetLowering::isOffsetFoldingLegal(
5494 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005495 // Offsets are folded in the DAG combine rather than here so that we can
5496 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005497 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005498}
5499
Adhemerval Zanella664c1ef2019-03-18 18:40:07 +00005500bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5501 bool OptForSize) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005502 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005503 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5504 // 16-bit case when target has full fp16 support.
5505 // FIXME: We should be able to handle f128 as well with a clever lowering.
5506 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005507 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005508 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005509 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005510 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005511 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005512 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5513 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5514 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005515
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005516 // If we can not materialize in immediate field for fmov, check if the
5517 // value can be encoded as the immediate operand of a logical instruction.
5518 // The immediate value will be created with either MOVZ, MOVN, or ORR.
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +00005519 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5520 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5521 // however the mov+fmov sequence is always better because of the reduced
5522 // cache pressure. The timings are still the same if you consider
5523 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5524 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5525 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5526 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5527 Insn);
5528 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5529 IsLegal = Insn.size() <= Limit;
5530 }
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005531
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005532 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5533 << " imm value: "; Imm.dump(););
5534 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005535}
5536
5537//===----------------------------------------------------------------------===//
5538// AArch64 Optimization Hooks
5539//===----------------------------------------------------------------------===//
5540
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005541static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5542 SDValue Operand, SelectionDAG &DAG,
5543 int &ExtraSteps) {
5544 EVT VT = Operand.getValueType();
5545 if (ST->hasNEON() &&
5546 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5547 VT == MVT::f32 || VT == MVT::v1f32 ||
5548 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5549 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5550 // For the reciprocal estimates, convergence is quadratic, so the number
5551 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5552 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5553 // the result for float (23 mantissa bits) is 2 and for double (52
5554 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005555 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005556
5557 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5558 }
5559
5560 return SDValue();
5561}
5562
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005563SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5564 SelectionDAG &DAG, int Enabled,
5565 int &ExtraSteps,
5566 bool &UseOneConst,
5567 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005568 if (Enabled == ReciprocalEstimate::Enabled ||
5569 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5570 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5571 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005572 SDLoc DL(Operand);
5573 EVT VT = Operand.getValueType();
5574
5575 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005576 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005577
5578 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5579 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5580 for (int i = ExtraSteps; i > 0; --i) {
5581 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005582 Flags);
5583 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5584 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005585 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005586 if (!Reciprocal) {
5587 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5588 VT);
5589 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5590 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5591
Amara Emersond28f0cd42017-05-01 15:17:51 +00005592 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005593 // Correct the result if the operand is 0.0.
5594 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5595 VT, Eq, Operand, Estimate);
5596 }
5597
5598 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005599 return Estimate;
5600 }
5601
5602 return SDValue();
5603}
5604
5605SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5606 SelectionDAG &DAG, int Enabled,
5607 int &ExtraSteps) const {
5608 if (Enabled == ReciprocalEstimate::Enabled)
5609 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005610 DAG, ExtraSteps)) {
5611 SDLoc DL(Operand);
5612 EVT VT = Operand.getValueType();
5613
5614 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005615 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005616
5617 // Newton reciprocal iteration: E * (2 - X * E)
5618 // AArch64 reciprocal iteration instruction: (2 - M * N)
5619 for (int i = ExtraSteps; i > 0; --i) {
5620 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005621 Estimate, Flags);
5622 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005623 }
5624
5625 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005626 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005627 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005628
5629 return SDValue();
5630}
5631
Tim Northover3b0846e2014-05-24 12:50:23 +00005632//===----------------------------------------------------------------------===//
5633// AArch64 Inline Assembly Support
5634//===----------------------------------------------------------------------===//
5635
5636// Table of Constraints
5637// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005638// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005639//
5640// r - A general register
5641// w - An FP/SIMD register of some size in the range v0-v31
5642// x - An FP/SIMD register of some size in the range v0-v15
5643// I - Constant that can be used with an ADD instruction
5644// J - Constant that can be used with a SUB instruction
5645// K - Constant that can be used with a 32-bit logical instruction
5646// L - Constant that can be used with a 64-bit logical instruction
5647// M - Constant that can be used as a 32-bit MOV immediate
5648// N - Constant that can be used as a 64-bit MOV immediate
5649// Q - A memory reference with base register and no offset
5650// S - A symbolic address
5651// Y - Floating point constant zero
5652// Z - Integer constant zero
5653//
5654// Note that general register operands will be output using their 64-bit x
5655// register name, whatever the size of the variable, unless the asm operand
5656// is prefixed by the %w modifier. Floating-point and SIMD register operands
5657// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5658// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005659const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5660 // At this point, we have to lower this constraint to something else, so we
5661 // lower it to an "r" or "w". However, by doing this we will force the result
5662 // to be in register, while the X constraint is much more permissive.
5663 //
5664 // Although we are correct (we are free to emit anything, without
5665 // constraints), we might break use cases that would expect us to be more
5666 // efficient and emit something else.
5667 if (!Subtarget->hasFPARMv8())
5668 return "r";
5669
5670 if (ConstraintVT.isFloatingPoint())
5671 return "w";
5672
5673 if (ConstraintVT.isVector() &&
5674 (ConstraintVT.getSizeInBits() == 64 ||
5675 ConstraintVT.getSizeInBits() == 128))
5676 return "w";
5677
5678 return "r";
5679}
Tim Northover3b0846e2014-05-24 12:50:23 +00005680
5681/// getConstraintType - Given a constraint letter, return the type of
5682/// constraint it is for this target.
5683AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005684AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005685 if (Constraint.size() == 1) {
5686 switch (Constraint[0]) {
5687 default:
5688 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005689 case 'x':
5690 case 'w':
5691 return C_RegisterClass;
5692 // An address with a single base register. Due to the way we
5693 // currently handle addresses it is the same as 'r'.
5694 case 'Q':
5695 return C_Memory;
Bill Wendling41a28472019-08-03 05:52:47 +00005696 case 'I':
5697 case 'J':
5698 case 'K':
5699 case 'L':
5700 case 'M':
5701 case 'N':
5702 case 'Y':
5703 case 'Z':
5704 return C_Immediate;
5705 case 'z':
Peter Smithc8117582018-05-16 09:33:25 +00005706 case 'S': // A symbolic address
5707 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005708 }
5709 }
5710 return TargetLowering::getConstraintType(Constraint);
5711}
5712
5713/// Examine constraint type and operand type and determine a weight value.
5714/// This object must already have been set up with the operand type
5715/// and the current alternative constraint selected.
5716TargetLowering::ConstraintWeight
5717AArch64TargetLowering::getSingleConstraintMatchWeight(
5718 AsmOperandInfo &info, const char *constraint) const {
5719 ConstraintWeight weight = CW_Invalid;
5720 Value *CallOperandVal = info.CallOperandVal;
5721 // If we don't have a value, we can't do a match,
5722 // but allow it at the lowest weight.
5723 if (!CallOperandVal)
5724 return CW_Default;
5725 Type *type = CallOperandVal->getType();
5726 // Look at the constraint type.
5727 switch (*constraint) {
5728 default:
5729 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5730 break;
5731 case 'x':
5732 case 'w':
5733 if (type->isFloatingPointTy() || type->isVectorTy())
5734 weight = CW_Register;
5735 break;
5736 case 'z':
5737 weight = CW_Constant;
5738 break;
5739 }
5740 return weight;
5741}
5742
5743std::pair<unsigned, const TargetRegisterClass *>
5744AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005745 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005746 if (Constraint.size() == 1) {
5747 switch (Constraint[0]) {
5748 case 'r':
5749 if (VT.getSizeInBits() == 64)
5750 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5751 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5752 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005753 if (!Subtarget->hasFPARMv8())
5754 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005755 if (VT.getSizeInBits() == 16)
5756 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005757 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005758 return std::make_pair(0U, &AArch64::FPR32RegClass);
5759 if (VT.getSizeInBits() == 64)
5760 return std::make_pair(0U, &AArch64::FPR64RegClass);
5761 if (VT.getSizeInBits() == 128)
5762 return std::make_pair(0U, &AArch64::FPR128RegClass);
5763 break;
5764 // The instructions that this constraint is designed for can
5765 // only take 128-bit registers so just use that regclass.
5766 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005767 if (!Subtarget->hasFPARMv8())
5768 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005769 if (VT.getSizeInBits() == 128)
5770 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5771 break;
5772 }
5773 }
5774 if (StringRef("{cc}").equals_lower(Constraint))
5775 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5776
5777 // Use the default implementation in TargetLowering to convert the register
5778 // constraint into a member of a register class.
5779 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005780 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005781
5782 // Not found as a standard register?
5783 if (!Res.second) {
5784 unsigned Size = Constraint.size();
5785 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5786 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005787 int RegNo;
5788 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5789 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005790 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005791 // By default we'll emit v0-v31 for this unless there's a modifier where
5792 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005793 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5794 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5795 Res.second = &AArch64::FPR64RegClass;
5796 } else {
5797 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5798 Res.second = &AArch64::FPR128RegClass;
5799 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005800 }
5801 }
5802 }
5803
Eli Friedman071203b2018-08-24 19:12:13 +00005804 if (Res.second && !Subtarget->hasFPARMv8() &&
5805 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5806 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5807 return std::make_pair(0U, nullptr);
5808
Tim Northover3b0846e2014-05-24 12:50:23 +00005809 return Res;
5810}
5811
5812/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5813/// vector. If it is invalid, don't add anything to Ops.
5814void AArch64TargetLowering::LowerAsmOperandForConstraint(
5815 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5816 SelectionDAG &DAG) const {
5817 SDValue Result;
5818
5819 // Currently only support length 1 constraints.
5820 if (Constraint.length() != 1)
5821 return;
5822
5823 char ConstraintLetter = Constraint[0];
5824 switch (ConstraintLetter) {
5825 default:
5826 break;
5827
5828 // This set of constraints deal with valid constants for various instructions.
5829 // Validate and return a target constant for them if we can.
5830 case 'z': {
5831 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005832 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005833 return;
5834
5835 if (Op.getValueType() == MVT::i64)
5836 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5837 else
5838 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5839 break;
5840 }
Peter Smithc8117582018-05-16 09:33:25 +00005841 case 'S': {
5842 // An absolute symbolic address or label reference.
5843 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5844 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5845 GA->getValueType(0));
5846 } else if (const BlockAddressSDNode *BA =
5847 dyn_cast<BlockAddressSDNode>(Op)) {
5848 Result =
5849 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5850 } else if (const ExternalSymbolSDNode *ES =
5851 dyn_cast<ExternalSymbolSDNode>(Op)) {
5852 Result =
5853 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5854 } else
5855 return;
5856 break;
5857 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005858
5859 case 'I':
5860 case 'J':
5861 case 'K':
5862 case 'L':
5863 case 'M':
5864 case 'N':
5865 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5866 if (!C)
5867 return;
5868
5869 // Grab the value and do some validation.
5870 uint64_t CVal = C->getZExtValue();
5871 switch (ConstraintLetter) {
5872 // The I constraint applies only to simple ADD or SUB immediate operands:
5873 // i.e. 0 to 4095 with optional shift by 12
5874 // The J constraint applies only to ADD or SUB immediates that would be
5875 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5876 // instruction [or vice versa], in other words -1 to -4095 with optional
5877 // left shift by 12.
5878 case 'I':
5879 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5880 break;
5881 return;
5882 case 'J': {
5883 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005884 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5885 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005886 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005887 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005888 return;
5889 }
5890 // The K and L constraints apply *only* to logical immediates, including
5891 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5892 // been removed and MOV should be used). So these constraints have to
5893 // distinguish between bit patterns that are valid 32-bit or 64-bit
5894 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5895 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5896 // versa.
5897 case 'K':
5898 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5899 break;
5900 return;
5901 case 'L':
5902 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5903 break;
5904 return;
5905 // The M and N constraints are a superset of K and L respectively, for use
5906 // with the MOV (immediate) alias. As well as the logical immediates they
5907 // also match 32 or 64-bit immediates that can be loaded either using a
5908 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5909 // (M) or 64-bit 0x1234000000000000 (N) etc.
5910 // As a note some of this code is liberally stolen from the asm parser.
5911 case 'M': {
5912 if (!isUInt<32>(CVal))
5913 return;
5914 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5915 break;
5916 if ((CVal & 0xFFFF) == CVal)
5917 break;
5918 if ((CVal & 0xFFFF0000ULL) == CVal)
5919 break;
5920 uint64_t NCVal = ~(uint32_t)CVal;
5921 if ((NCVal & 0xFFFFULL) == NCVal)
5922 break;
5923 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5924 break;
5925 return;
5926 }
5927 case 'N': {
5928 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5929 break;
5930 if ((CVal & 0xFFFFULL) == CVal)
5931 break;
5932 if ((CVal & 0xFFFF0000ULL) == CVal)
5933 break;
5934 if ((CVal & 0xFFFF00000000ULL) == CVal)
5935 break;
5936 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5937 break;
5938 uint64_t NCVal = ~CVal;
5939 if ((NCVal & 0xFFFFULL) == NCVal)
5940 break;
5941 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5942 break;
5943 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5944 break;
5945 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5946 break;
5947 return;
5948 }
5949 default:
5950 return;
5951 }
5952
5953 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005954 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005955 break;
5956 }
5957
5958 if (Result.getNode()) {
5959 Ops.push_back(Result);
5960 return;
5961 }
5962
5963 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5964}
5965
5966//===----------------------------------------------------------------------===//
5967// AArch64 Advanced SIMD Support
5968//===----------------------------------------------------------------------===//
5969
5970/// WidenVector - Given a value in the V64 register class, produce the
5971/// equivalent value in the V128 register class.
5972static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5973 EVT VT = V64Reg.getValueType();
5974 unsigned NarrowSize = VT.getVectorNumElements();
5975 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5976 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5977 SDLoc DL(V64Reg);
5978
5979 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005980 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005981}
5982
5983/// getExtFactor - Determine the adjustment factor for the position when
5984/// generating an "extract from vector registers" instruction.
5985static unsigned getExtFactor(SDValue &V) {
5986 EVT EltType = V.getValueType().getVectorElementType();
5987 return EltType.getSizeInBits() / 8;
5988}
5989
5990/// NarrowVector - Given a value in the V128 register class, produce the
5991/// equivalent value in the V64 register class.
5992static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5993 EVT VT = V128Reg.getValueType();
5994 unsigned WideSize = VT.getVectorNumElements();
5995 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5996 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5997 SDLoc DL(V128Reg);
5998
5999 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6000}
6001
6002// Gather data to see if the operation can be modelled as a
6003// shuffle in combination with VEXTs.
6004SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6005 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006006 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006007 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006008 SDLoc dl(Op);
6009 EVT VT = Op.getValueType();
6010 unsigned NumElts = VT.getVectorNumElements();
6011
Tim Northover7324e842014-07-24 15:39:55 +00006012 struct ShuffleSourceInfo {
6013 SDValue Vec;
6014 unsigned MinElt;
6015 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006016
Tim Northover7324e842014-07-24 15:39:55 +00006017 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6018 // be compatible with the shuffle we intend to construct. As a result
6019 // ShuffleVec will be some sliding window into the original Vec.
6020 SDValue ShuffleVec;
6021
6022 // Code should guarantee that element i in Vec starts at element "WindowBase
6023 // + i * WindowScale in ShuffleVec".
6024 int WindowBase;
6025 int WindowScale;
6026
Tim Northover7324e842014-07-24 15:39:55 +00006027 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00006028 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6029 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6030
6031 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00006032 };
6033
6034 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6035 // node.
6036 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00006037 for (unsigned i = 0; i < NumElts; ++i) {
6038 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006039 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006040 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00006041 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6042 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006043 LLVM_DEBUG(
6044 dbgs() << "Reshuffle failed: "
6045 "a shuffle can only come from building a vector from "
6046 "various elements of other vectors, provided their "
6047 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006048 return SDValue();
6049 }
6050
Tim Northover7324e842014-07-24 15:39:55 +00006051 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00006052 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00006053 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00006054 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00006055 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00006056
Tim Northover7324e842014-07-24 15:39:55 +00006057 // Update the minimum and maximum lane number seen.
6058 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6059 Source->MinElt = std::min(Source->MinElt, EltNo);
6060 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00006061 }
6062
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006063 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006064 LLVM_DEBUG(
6065 dbgs() << "Reshuffle failed: currently only do something sane when at "
6066 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006067 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006068 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006069
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006070 // Find out the smallest element size among result and two sources, and use
6071 // it as element size to build the shuffle_vector.
6072 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00006073 for (auto &Source : Sources) {
6074 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006075 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6076 SmallestEltTy = SrcEltTy;
6077 }
6078 }
6079 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006080 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006081 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6082 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00006083
Tim Northover7324e842014-07-24 15:39:55 +00006084 // If the source vector is too wide or too narrow, we may nevertheless be able
6085 // to construct a compatible shuffle either by concatenating it with UNDEF or
6086 // extracting a suitable range of elements.
6087 for (auto &Src : Sources) {
6088 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006089
Tim Northover7324e842014-07-24 15:39:55 +00006090 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00006091 continue;
Tim Northover7324e842014-07-24 15:39:55 +00006092
6093 // This stage of the search produces a source with the same element type as
6094 // the original, but with a total width matching the BUILD_VECTOR output.
6095 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00006096 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6097 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00006098
6099 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6100 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006101 // We can pad out the smaller vector for free, so if it's part of a
6102 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00006103 Src.ShuffleVec =
6104 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6105 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00006106 continue;
6107 }
6108
Tim Northover7324e842014-07-24 15:39:55 +00006109 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006110
James Molloyf497d552014-10-17 17:06:31 +00006111 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006112 LLVM_DEBUG(
6113 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006114 return SDValue();
6115 }
6116
James Molloyf497d552014-10-17 17:06:31 +00006117 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006118 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00006119 Src.ShuffleVec =
6120 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006121 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00006122 Src.WindowBase = -NumSrcElts;
6123 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006124 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006125 Src.ShuffleVec =
6126 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006127 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006128 } else {
6129 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006130 SDValue VEXTSrc1 =
6131 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006132 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006133 SDValue VEXTSrc2 =
6134 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006135 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006136 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6137
6138 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006139 VEXTSrc2,
6140 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006141 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006142 }
6143 }
6144
Tim Northover7324e842014-07-24 15:39:55 +00006145 // Another possible incompatibility occurs from the vector element types. We
6146 // can fix this by bitcasting the source vectors to the same type we intend
6147 // for the shuffle.
6148 for (auto &Src : Sources) {
6149 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6150 if (SrcEltTy == SmallestEltTy)
6151 continue;
6152 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6153 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6154 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6155 Src.WindowBase *= Src.WindowScale;
6156 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006157
Tim Northover7324e842014-07-24 15:39:55 +00006158 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006159 LLVM_DEBUG(for (auto Src
6160 : Sources)
6161 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006162
6163 // The stars all align, our next step is to produce the mask for the shuffle.
6164 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006165 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006166 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006167 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006168 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006169 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006170
David Majnemer0d955d02016-08-11 22:21:41 +00006171 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006172 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6173
6174 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6175 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6176 // segment.
6177 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006178 int BitsDefined =
6179 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006180 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6181
6182 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6183 // starting at the appropriate offset.
6184 int *LaneMask = &Mask[i * ResMultiplier];
6185
6186 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6187 ExtractBase += NumElts * (Src - Sources.begin());
6188 for (int j = 0; j < LanesDefined; ++j)
6189 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006190 }
6191
6192 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006193 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006194 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006195 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006196 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006197
Tim Northover7324e842014-07-24 15:39:55 +00006198 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6199 for (unsigned i = 0; i < Sources.size(); ++i)
6200 ShuffleOps[i] = Sources[i].ShuffleVec;
6201
6202 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006203 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006204 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6205
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006206 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6207 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006208
6209 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006210}
6211
6212// check if an EXT instruction can handle the shuffle mask when the
6213// vector sources of the shuffle are the same.
6214static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6215 unsigned NumElts = VT.getVectorNumElements();
6216
6217 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6218 if (M[0] < 0)
6219 return false;
6220
6221 Imm = M[0];
6222
6223 // If this is a VEXT shuffle, the immediate value is the index of the first
6224 // element. The other shuffle indices must be the successive elements after
6225 // the first one.
6226 unsigned ExpectedElt = Imm;
6227 for (unsigned i = 1; i < NumElts; ++i) {
6228 // Increment the expected index. If it wraps around, just follow it
6229 // back to index zero and keep going.
6230 ++ExpectedElt;
6231 if (ExpectedElt == NumElts)
6232 ExpectedElt = 0;
6233
6234 if (M[i] < 0)
6235 continue; // ignore UNDEF indices
6236 if (ExpectedElt != static_cast<unsigned>(M[i]))
6237 return false;
6238 }
6239
6240 return true;
6241}
6242
6243// check if an EXT instruction can handle the shuffle mask when the
6244// vector sources of the shuffle are different.
6245static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6246 unsigned &Imm) {
6247 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006248 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006249
6250 // Benefit form APInt to handle overflow when calculating expected element.
6251 unsigned NumElts = VT.getVectorNumElements();
6252 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6253 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6254 // The following shuffle indices must be the successive elements after the
6255 // first real element.
6256 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6257 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6258 if (FirstWrongElt != M.end())
6259 return false;
6260
6261 // The index of an EXT is the first element if it is not UNDEF.
6262 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006263 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006264 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6265 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6266 // ExpectedElt is the last mask index plus 1.
6267 Imm = ExpectedElt.getZExtValue();
6268
6269 // There are two difference cases requiring to reverse input vectors.
6270 // For example, for vector <4 x i32> we have the following cases,
6271 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6272 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6273 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6274 // to reverse two input vectors.
6275 if (Imm < NumElts)
6276 ReverseEXT = true;
6277 else
6278 Imm -= NumElts;
6279
6280 return true;
6281}
6282
6283/// isREVMask - Check if a vector shuffle corresponds to a REV
6284/// instruction with the specified blocksize. (The order of the elements
6285/// within each block of the vector is reversed.)
6286static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6287 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6288 "Only possible block sizes for REV are: 16, 32, 64");
6289
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006290 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006291 if (EltSz == 64)
6292 return false;
6293
6294 unsigned NumElts = VT.getVectorNumElements();
6295 unsigned BlockElts = M[0] + 1;
6296 // If the first shuffle index is UNDEF, be optimistic.
6297 if (M[0] < 0)
6298 BlockElts = BlockSize / EltSz;
6299
6300 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6301 return false;
6302
6303 for (unsigned i = 0; i < NumElts; ++i) {
6304 if (M[i] < 0)
6305 continue; // ignore UNDEF indices
6306 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6307 return false;
6308 }
6309
6310 return true;
6311}
6312
6313static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6314 unsigned NumElts = VT.getVectorNumElements();
6315 WhichResult = (M[0] == 0 ? 0 : 1);
6316 unsigned Idx = WhichResult * NumElts / 2;
6317 for (unsigned i = 0; i != NumElts; i += 2) {
6318 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6319 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6320 return false;
6321 Idx += 1;
6322 }
6323
6324 return true;
6325}
6326
6327static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6328 unsigned NumElts = VT.getVectorNumElements();
6329 WhichResult = (M[0] == 0 ? 0 : 1);
6330 for (unsigned i = 0; i != NumElts; ++i) {
6331 if (M[i] < 0)
6332 continue; // ignore UNDEF indices
6333 if ((unsigned)M[i] != 2 * i + WhichResult)
6334 return false;
6335 }
6336
6337 return true;
6338}
6339
6340static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6341 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006342 if (NumElts % 2 != 0)
6343 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006344 WhichResult = (M[0] == 0 ? 0 : 1);
6345 for (unsigned i = 0; i < NumElts; i += 2) {
6346 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6347 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6348 return false;
6349 }
6350 return true;
6351}
6352
6353/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6354/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6355/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6356static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6357 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006358 if (NumElts % 2 != 0)
6359 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006360 WhichResult = (M[0] == 0 ? 0 : 1);
6361 unsigned Idx = WhichResult * NumElts / 2;
6362 for (unsigned i = 0; i != NumElts; i += 2) {
6363 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6364 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6365 return false;
6366 Idx += 1;
6367 }
6368
6369 return true;
6370}
6371
6372/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6373/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6374/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6375static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6376 unsigned Half = VT.getVectorNumElements() / 2;
6377 WhichResult = (M[0] == 0 ? 0 : 1);
6378 for (unsigned j = 0; j != 2; ++j) {
6379 unsigned Idx = WhichResult;
6380 for (unsigned i = 0; i != Half; ++i) {
6381 int MIdx = M[i + j * Half];
6382 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6383 return false;
6384 Idx += 2;
6385 }
6386 }
6387
6388 return true;
6389}
6390
6391/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6392/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6393/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6394static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6395 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006396 if (NumElts % 2 != 0)
6397 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006398 WhichResult = (M[0] == 0 ? 0 : 1);
6399 for (unsigned i = 0; i < NumElts; i += 2) {
6400 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6401 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6402 return false;
6403 }
6404 return true;
6405}
6406
6407static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6408 bool &DstIsLeft, int &Anomaly) {
6409 if (M.size() != static_cast<size_t>(NumInputElements))
6410 return false;
6411
6412 int NumLHSMatch = 0, NumRHSMatch = 0;
6413 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6414
6415 for (int i = 0; i < NumInputElements; ++i) {
6416 if (M[i] == -1) {
6417 ++NumLHSMatch;
6418 ++NumRHSMatch;
6419 continue;
6420 }
6421
6422 if (M[i] == i)
6423 ++NumLHSMatch;
6424 else
6425 LastLHSMismatch = i;
6426
6427 if (M[i] == i + NumInputElements)
6428 ++NumRHSMatch;
6429 else
6430 LastRHSMismatch = i;
6431 }
6432
6433 if (NumLHSMatch == NumInputElements - 1) {
6434 DstIsLeft = true;
6435 Anomaly = LastLHSMismatch;
6436 return true;
6437 } else if (NumRHSMatch == NumInputElements - 1) {
6438 DstIsLeft = false;
6439 Anomaly = LastRHSMismatch;
6440 return true;
6441 }
6442
6443 return false;
6444}
6445
6446static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6447 if (VT.getSizeInBits() != 128)
6448 return false;
6449
6450 unsigned NumElts = VT.getVectorNumElements();
6451
6452 for (int I = 0, E = NumElts / 2; I != E; I++) {
6453 if (Mask[I] != I)
6454 return false;
6455 }
6456
6457 int Offset = NumElts / 2;
6458 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6459 if (Mask[I] != I + SplitLHS * Offset)
6460 return false;
6461 }
6462
6463 return true;
6464}
6465
6466static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6467 SDLoc DL(Op);
6468 EVT VT = Op.getValueType();
6469 SDValue V0 = Op.getOperand(0);
6470 SDValue V1 = Op.getOperand(1);
6471 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6472
6473 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6474 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6475 return SDValue();
6476
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006477 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006478
6479 if (!isConcatMask(Mask, VT, SplitV0))
6480 return SDValue();
6481
6482 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6483 VT.getVectorNumElements() / 2);
6484 if (SplitV0) {
6485 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006486 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006487 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006488 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006489 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006490 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006491 }
6492 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6493}
6494
6495/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6496/// the specified operations to build the shuffle.
6497static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6498 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006499 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006500 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6501 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6502 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6503
6504 enum {
6505 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6506 OP_VREV,
6507 OP_VDUP0,
6508 OP_VDUP1,
6509 OP_VDUP2,
6510 OP_VDUP3,
6511 OP_VEXT1,
6512 OP_VEXT2,
6513 OP_VEXT3,
6514 OP_VUZPL, // VUZP, left result
6515 OP_VUZPR, // VUZP, right result
6516 OP_VZIPL, // VZIP, left result
6517 OP_VZIPR, // VZIP, right result
6518 OP_VTRNL, // VTRN, left result
6519 OP_VTRNR // VTRN, right result
6520 };
6521
6522 if (OpNum == OP_COPY) {
6523 if (LHSID == (1 * 9 + 2) * 9 + 3)
6524 return LHS;
6525 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6526 return RHS;
6527 }
6528
6529 SDValue OpLHS, OpRHS;
6530 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6531 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6532 EVT VT = OpLHS.getValueType();
6533
6534 switch (OpNum) {
6535 default:
6536 llvm_unreachable("Unknown shuffle opcode!");
6537 case OP_VREV:
6538 // VREV divides the vector in half and swaps within the half.
6539 if (VT.getVectorElementType() == MVT::i32 ||
6540 VT.getVectorElementType() == MVT::f32)
6541 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6542 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006543 if (VT.getVectorElementType() == MVT::i16 ||
6544 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006545 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6546 // vrev <4 x i8> -> REV16
6547 assert(VT.getVectorElementType() == MVT::i8);
6548 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6549 case OP_VDUP0:
6550 case OP_VDUP1:
6551 case OP_VDUP2:
6552 case OP_VDUP3: {
6553 EVT EltTy = VT.getVectorElementType();
6554 unsigned Opcode;
6555 if (EltTy == MVT::i8)
6556 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006557 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006558 Opcode = AArch64ISD::DUPLANE16;
6559 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6560 Opcode = AArch64ISD::DUPLANE32;
6561 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6562 Opcode = AArch64ISD::DUPLANE64;
6563 else
6564 llvm_unreachable("Invalid vector element type?");
6565
6566 if (VT.getSizeInBits() == 64)
6567 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006568 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006569 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6570 }
6571 case OP_VEXT1:
6572 case OP_VEXT2:
6573 case OP_VEXT3: {
6574 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6575 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006576 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006577 }
6578 case OP_VUZPL:
6579 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6580 OpRHS);
6581 case OP_VUZPR:
6582 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6583 OpRHS);
6584 case OP_VZIPL:
6585 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6586 OpRHS);
6587 case OP_VZIPR:
6588 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6589 OpRHS);
6590 case OP_VTRNL:
6591 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6592 OpRHS);
6593 case OP_VTRNR:
6594 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6595 OpRHS);
6596 }
6597}
6598
6599static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6600 SelectionDAG &DAG) {
6601 // Check to see if we can use the TBL instruction.
6602 SDValue V1 = Op.getOperand(0);
6603 SDValue V2 = Op.getOperand(1);
6604 SDLoc DL(Op);
6605
6606 EVT EltVT = Op.getValueType().getVectorElementType();
6607 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6608
6609 SmallVector<SDValue, 8> TBLMask;
6610 for (int Val : ShuffleMask) {
6611 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6612 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006613 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006614 }
6615 }
6616
6617 MVT IndexVT = MVT::v8i8;
6618 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006619 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006620 IndexVT = MVT::v16i8;
6621 IndexLen = 16;
6622 }
6623
6624 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6625 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6626
6627 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006628 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006629 if (IndexLen == 8)
6630 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6631 Shuffle = DAG.getNode(
6632 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006633 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006634 DAG.getBuildVector(IndexVT, DL,
6635 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006636 } else {
6637 if (IndexLen == 8) {
6638 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6639 Shuffle = DAG.getNode(
6640 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006641 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006642 DAG.getBuildVector(IndexVT, DL,
6643 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006644 } else {
6645 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6646 // cannot currently represent the register constraints on the input
6647 // table registers.
6648 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006649 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6650 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006651 Shuffle = DAG.getNode(
6652 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006653 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6654 V2Cst, DAG.getBuildVector(IndexVT, DL,
6655 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006656 }
6657 }
6658 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6659}
6660
6661static unsigned getDUPLANEOp(EVT EltType) {
6662 if (EltType == MVT::i8)
6663 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006664 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006665 return AArch64ISD::DUPLANE16;
6666 if (EltType == MVT::i32 || EltType == MVT::f32)
6667 return AArch64ISD::DUPLANE32;
6668 if (EltType == MVT::i64 || EltType == MVT::f64)
6669 return AArch64ISD::DUPLANE64;
6670
6671 llvm_unreachable("Invalid vector element type?");
6672}
6673
6674SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6675 SelectionDAG &DAG) const {
6676 SDLoc dl(Op);
6677 EVT VT = Op.getValueType();
6678
6679 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6680
6681 // Convert shuffles that are directly supported on NEON to target-specific
6682 // DAG nodes, instead of keeping them as shuffles and matching them again
6683 // during code selection. This is more efficient and avoids the possibility
6684 // of inconsistencies between legalization and selection.
6685 ArrayRef<int> ShuffleMask = SVN->getMask();
6686
6687 SDValue V1 = Op.getOperand(0);
6688 SDValue V2 = Op.getOperand(1);
6689
Craig Topperbc56e3b2016-06-30 04:38:51 +00006690 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006691 int Lane = SVN->getSplatIndex();
6692 // If this is undef splat, generate it via "just" vdup, if possible.
6693 if (Lane == -1)
6694 Lane = 0;
6695
6696 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6697 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6698 V1.getOperand(0));
6699 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6700 // constant. If so, we can just reference the lane's definition directly.
6701 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6702 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6703 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6704
6705 // Otherwise, duplicate from the lane of the input vector.
6706 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6707
6708 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6709 // to make a vector of the same size as this SHUFFLE. We can ignore the
6710 // extract entirely, and canonicalise the concat using WidenVector.
6711 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6712 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6713 V1 = V1.getOperand(0);
6714 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6715 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6716 Lane -= Idx * VT.getVectorNumElements() / 2;
6717 V1 = WidenVector(V1.getOperand(Idx), DAG);
6718 } else if (VT.getSizeInBits() == 64)
6719 V1 = WidenVector(V1, DAG);
6720
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006721 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006722 }
6723
6724 if (isREVMask(ShuffleMask, VT, 64))
6725 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6726 if (isREVMask(ShuffleMask, VT, 32))
6727 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6728 if (isREVMask(ShuffleMask, VT, 16))
6729 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6730
6731 bool ReverseEXT = false;
6732 unsigned Imm;
6733 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6734 if (ReverseEXT)
6735 std::swap(V1, V2);
6736 Imm *= getExtFactor(V1);
6737 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006738 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006739 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006740 Imm *= getExtFactor(V1);
6741 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006742 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006743 }
6744
6745 unsigned WhichResult;
6746 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6747 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6748 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6749 }
6750 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6751 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6752 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6753 }
6754 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6755 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6756 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6757 }
6758
6759 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6760 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6761 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6762 }
6763 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6764 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6765 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6766 }
6767 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6768 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6769 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6770 }
6771
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006772 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006773 return Concat;
6774
6775 bool DstIsLeft;
6776 int Anomaly;
6777 int NumInputElements = V1.getValueType().getVectorNumElements();
6778 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6779 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006780 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006781
6782 SDValue SrcVec = V1;
6783 int SrcLane = ShuffleMask[Anomaly];
6784 if (SrcLane >= NumInputElements) {
6785 SrcVec = V2;
6786 SrcLane -= VT.getVectorNumElements();
6787 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006788 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006789
6790 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006791
6792 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006793 ScalarVT = MVT::i32;
6794
6795 return DAG.getNode(
6796 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6797 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6798 DstLaneV);
6799 }
6800
6801 // If the shuffle is not directly supported and it has 4 elements, use
6802 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6803 unsigned NumElts = VT.getVectorNumElements();
6804 if (NumElts == 4) {
6805 unsigned PFIndexes[4];
6806 for (unsigned i = 0; i != 4; ++i) {
6807 if (ShuffleMask[i] < 0)
6808 PFIndexes[i] = 8;
6809 else
6810 PFIndexes[i] = ShuffleMask[i];
6811 }
6812
6813 // Compute the index in the perfect shuffle table.
6814 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6815 PFIndexes[2] * 9 + PFIndexes[3];
6816 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6817 unsigned Cost = (PFEntry >> 30);
6818
6819 if (Cost <= 4)
6820 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6821 }
6822
6823 return GenerateTBL(Op, ShuffleMask, DAG);
6824}
6825
6826static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6827 APInt &UndefBits) {
6828 EVT VT = BVN->getValueType(0);
6829 APInt SplatBits, SplatUndef;
6830 unsigned SplatBitSize;
6831 bool HasAnyUndefs;
6832 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6833 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6834
6835 for (unsigned i = 0; i < NumSplats; ++i) {
6836 CnstBits <<= SplatBitSize;
6837 UndefBits <<= SplatBitSize;
6838 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6839 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6840 }
6841
6842 return true;
6843 }
6844
6845 return false;
6846}
6847
Evandro Menezes72f39832018-02-20 20:31:45 +00006848// Try 64-bit splatted SIMD immediate.
6849static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6850 const APInt &Bits) {
6851 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6852 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6853 EVT VT = Op.getValueType();
6854 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6855
6856 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6857 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6858
6859 SDLoc dl(Op);
6860 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6861 DAG.getConstant(Value, dl, MVT::i32));
6862 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6863 }
6864 }
6865
6866 return SDValue();
6867}
6868
6869// Try 32-bit splatted SIMD immediate.
6870static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6871 const APInt &Bits,
6872 const SDValue *LHS = nullptr) {
6873 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6874 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6875 EVT VT = Op.getValueType();
6876 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6877 bool isAdvSIMDModImm = false;
6878 uint64_t Shift;
6879
6880 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6881 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6882 Shift = 0;
6883 }
6884 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6885 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6886 Shift = 8;
6887 }
6888 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6889 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6890 Shift = 16;
6891 }
6892 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6893 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6894 Shift = 24;
6895 }
6896
6897 if (isAdvSIMDModImm) {
6898 SDLoc dl(Op);
6899 SDValue Mov;
6900
6901 if (LHS)
6902 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6903 DAG.getConstant(Value, dl, MVT::i32),
6904 DAG.getConstant(Shift, dl, MVT::i32));
6905 else
6906 Mov = DAG.getNode(NewOp, dl, MovTy,
6907 DAG.getConstant(Value, dl, MVT::i32),
6908 DAG.getConstant(Shift, dl, MVT::i32));
6909
6910 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6911 }
6912 }
6913
6914 return SDValue();
6915}
6916
6917// Try 16-bit splatted SIMD immediate.
6918static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6919 const APInt &Bits,
6920 const SDValue *LHS = nullptr) {
6921 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6922 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6923 EVT VT = Op.getValueType();
6924 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6925 bool isAdvSIMDModImm = false;
6926 uint64_t Shift;
6927
6928 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6929 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6930 Shift = 0;
6931 }
6932 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6933 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6934 Shift = 8;
6935 }
6936
6937 if (isAdvSIMDModImm) {
6938 SDLoc dl(Op);
6939 SDValue Mov;
6940
6941 if (LHS)
6942 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006943 DAG.getConstant(Value, dl, MVT::i32),
6944 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006945 else
6946 Mov = DAG.getNode(NewOp, dl, MovTy,
6947 DAG.getConstant(Value, dl, MVT::i32),
6948 DAG.getConstant(Shift, dl, MVT::i32));
6949
6950 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6951 }
6952 }
6953
6954 return SDValue();
6955}
6956
6957// Try 32-bit splatted SIMD immediate with shifted ones.
6958static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6959 SelectionDAG &DAG, const APInt &Bits) {
6960 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6961 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6962 EVT VT = Op.getValueType();
6963 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6964 bool isAdvSIMDModImm = false;
6965 uint64_t Shift;
6966
6967 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6968 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6969 Shift = 264;
6970 }
6971 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6972 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6973 Shift = 272;
6974 }
6975
6976 if (isAdvSIMDModImm) {
6977 SDLoc dl(Op);
6978 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6979 DAG.getConstant(Value, dl, MVT::i32),
6980 DAG.getConstant(Shift, dl, MVT::i32));
6981 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6982 }
6983 }
6984
6985 return SDValue();
6986}
6987
6988// Try 8-bit splatted SIMD immediate.
6989static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6990 const APInt &Bits) {
6991 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6992 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6993 EVT VT = Op.getValueType();
6994 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6995
6996 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6997 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6998
6999 SDLoc dl(Op);
7000 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7001 DAG.getConstant(Value, dl, MVT::i32));
7002 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7003 }
7004 }
7005
7006 return SDValue();
7007}
7008
7009// Try FP splatted SIMD immediate.
7010static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7011 const APInt &Bits) {
7012 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7013 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7014 EVT VT = Op.getValueType();
7015 bool isWide = (VT.getSizeInBits() == 128);
7016 MVT MovTy;
7017 bool isAdvSIMDModImm = false;
7018
7019 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7020 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7021 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7022 }
7023 else if (isWide &&
7024 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7025 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7026 MovTy = MVT::v2f64;
7027 }
7028
7029 if (isAdvSIMDModImm) {
7030 SDLoc dl(Op);
7031 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7032 DAG.getConstant(Value, dl, MVT::i32));
7033 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7034 }
7035 }
7036
7037 return SDValue();
7038}
7039
Tim Northover3b0846e2014-05-24 12:50:23 +00007040// Specialized code to quickly find if PotentialBVec is a BuildVector that
7041// consists of only the same constant int value, returned in reference arg
7042// ConstVal
7043static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7044 uint64_t &ConstVal) {
7045 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7046 if (!Bvec)
7047 return false;
7048 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7049 if (!FirstElt)
7050 return false;
7051 EVT VT = Bvec->getValueType(0);
7052 unsigned NumElts = VT.getVectorNumElements();
7053 for (unsigned i = 1; i < NumElts; ++i)
7054 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7055 return false;
7056 ConstVal = FirstElt->getZExtValue();
7057 return true;
7058}
7059
7060static unsigned getIntrinsicID(const SDNode *N) {
7061 unsigned Opcode = N->getOpcode();
7062 switch (Opcode) {
7063 default:
7064 return Intrinsic::not_intrinsic;
7065 case ISD::INTRINSIC_WO_CHAIN: {
7066 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7067 if (IID < Intrinsic::num_intrinsics)
7068 return IID;
7069 return Intrinsic::not_intrinsic;
7070 }
7071 }
7072}
7073
7074// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7075// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7076// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7077// Also, logical shift right -> sri, with the same structure.
7078static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7079 EVT VT = N->getValueType(0);
7080
7081 if (!VT.isVector())
7082 return SDValue();
7083
7084 SDLoc DL(N);
7085
7086 // Is the first op an AND?
7087 const SDValue And = N->getOperand(0);
7088 if (And.getOpcode() != ISD::AND)
7089 return SDValue();
7090
7091 // Is the second op an shl or lshr?
7092 SDValue Shift = N->getOperand(1);
7093 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7094 // or AArch64ISD::VLSHR vector, #shift
7095 unsigned ShiftOpc = Shift.getOpcode();
7096 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7097 return SDValue();
7098 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7099
7100 // Is the shift amount constant?
7101 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7102 if (!C2node)
7103 return SDValue();
7104
7105 // Is the and mask vector all constant?
7106 uint64_t C1;
7107 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7108 return SDValue();
7109
7110 // Is C1 == ~C2, taking into account how much one can shift elements of a
7111 // particular size?
7112 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007113 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007114 if (C2 > ElemSizeInBits)
7115 return SDValue();
7116 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7117 if ((C1 & ElemMask) != (~C2 & ElemMask))
7118 return SDValue();
7119
7120 SDValue X = And.getOperand(0);
7121 SDValue Y = Shift.getOperand(0);
7122
7123 unsigned Intrin =
7124 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7125 SDValue ResultSLI =
7126 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007127 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7128 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007129
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007130 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7131 LLVM_DEBUG(N->dump(&DAG));
7132 LLVM_DEBUG(dbgs() << "into: \n");
7133 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007134
7135 ++NumShiftInserts;
7136 return ResultSLI;
7137}
7138
7139SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7140 SelectionDAG &DAG) const {
7141 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7142 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007143 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007144 return Res;
7145 }
7146
Tim Northover3b0846e2014-05-24 12:50:23 +00007147 EVT VT = Op.getValueType();
7148
Evandro Menezescd855f72018-03-05 17:02:47 +00007149 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007150 BuildVectorSDNode *BVN =
7151 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007152 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007153 // OR commutes, so try swapping the operands.
7154 LHS = Op.getOperand(1);
7155 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007156 }
7157 if (!BVN)
7158 return Op;
7159
Evandro Menezes72f39832018-02-20 20:31:45 +00007160 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007161 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007162 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7163 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007164
Evandro Menezes72f39832018-02-20 20:31:45 +00007165 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7166 DefBits, &LHS)) ||
7167 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7168 DefBits, &LHS)))
7169 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007170
7171 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7172 UndefBits, &LHS)) ||
7173 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7174 UndefBits, &LHS)))
7175 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007176 }
7177
Evandro Menezes72f39832018-02-20 20:31:45 +00007178 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007179 return Op;
7180}
7181
Kevin Qin4473c192014-07-07 02:45:40 +00007182// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7183// be truncated to fit element width.
7184static SDValue NormalizeBuildVector(SDValue Op,
7185 SelectionDAG &DAG) {
7186 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007187 SDLoc dl(Op);
7188 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007189 EVT EltTy= VT.getVectorElementType();
7190
7191 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7192 return Op;
7193
7194 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007195 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007196 // For integer vectors, type legalization would have promoted the
7197 // operands already. Otherwise, if Op is a floating-point splat
7198 // (with operands cast to integers), then the only possibilities
7199 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007200 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007201 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007202 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007203 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007204 } else if (Lane.getNode()->isUndef()) {
7205 Lane = DAG.getUNDEF(MVT::i32);
7206 } else {
7207 assert(Lane.getValueType() == MVT::i32 &&
7208 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007209 }
7210 Ops.push_back(Lane);
7211 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007212 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007213}
7214
Evandro Menezescd855f72018-03-05 17:02:47 +00007215static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007216 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007217
Evandro Menezes72f39832018-02-20 20:31:45 +00007218 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007219 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007220 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007221 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007222 SDValue NewOp;
7223 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7224 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7225 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7226 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7227 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7228 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7229 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007230
Evandro Menezes72f39832018-02-20 20:31:45 +00007231 DefBits = ~DefBits;
7232 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7233 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7234 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7235 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007236
Evandro Menezes72f39832018-02-20 20:31:45 +00007237 DefBits = UndefBits;
7238 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7239 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7240 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7241 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7242 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7243 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7244 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007245
Evandro Menezes72f39832018-02-20 20:31:45 +00007246 DefBits = ~UndefBits;
7247 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7248 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7249 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7250 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007251 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007252
Evandro Menezescd855f72018-03-05 17:02:47 +00007253 return SDValue();
7254}
7255
7256SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7257 SelectionDAG &DAG) const {
7258 EVT VT = Op.getValueType();
7259
7260 // Try to build a simple constant vector.
7261 Op = NormalizeBuildVector(Op, DAG);
7262 if (VT.isInteger()) {
7263 // Certain vector constants, used to express things like logical NOT and
7264 // arithmetic NEG, are passed through unmodified. This allows special
7265 // patterns for these operations to match, which will lower these constants
7266 // to whatever is proven necessary.
7267 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7268 if (BVN->isConstant())
7269 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7270 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7271 APInt Val(BitSize,
7272 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7273 if (Val.isNullValue() || Val.isAllOnesValue())
7274 return Op;
7275 }
7276 }
7277
7278 if (SDValue V = ConstantBuildVector(Op, DAG))
7279 return V;
7280
Tim Northover3b0846e2014-05-24 12:50:23 +00007281 // Scan through the operands to find some interesting properties we can
7282 // exploit:
7283 // 1) If only one value is used, we can use a DUP, or
7284 // 2) if only the low element is not undef, we can just insert that, or
7285 // 3) if only one constant value is used (w/ some non-constant lanes),
7286 // we can splat the constant value into the whole vector then fill
7287 // in the non-constant lanes.
7288 // 4) FIXME: If different constant values are used, but we can intelligently
7289 // select the values we'll be overwriting for the non-constant
7290 // lanes such that we can directly materialize the vector
7291 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007292 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007293 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007294 unsigned NumElts = VT.getVectorNumElements();
7295 bool isOnlyLowElement = true;
7296 bool usesOnlyOneValue = true;
7297 bool usesOnlyOneConstantValue = true;
7298 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007299 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007300 unsigned NumConstantLanes = 0;
7301 SDValue Value;
7302 SDValue ConstantValue;
7303 for (unsigned i = 0; i < NumElts; ++i) {
7304 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007305 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7306 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007307 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007308 continue;
7309 if (i > 0)
7310 isOnlyLowElement = false;
7311 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7312 isConstant = false;
7313
7314 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7315 ++NumConstantLanes;
7316 if (!ConstantValue.getNode())
7317 ConstantValue = V;
7318 else if (ConstantValue != V)
7319 usesOnlyOneConstantValue = false;
7320 }
7321
7322 if (!Value.getNode())
7323 Value = V;
7324 else if (V != Value)
7325 usesOnlyOneValue = false;
7326 }
7327
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007328 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007329 LLVM_DEBUG(
7330 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007331 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007332 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007333
John Brawnd6e0ebe2018-11-22 11:45:23 +00007334 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7335 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7336 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7337 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007338 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7339 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007340 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007341 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007342
Sebastian Popc33af712018-03-01 15:47:39 +00007343 if (AllLanesExtractElt) {
7344 SDNode *Vector = nullptr;
7345 bool Even = false;
7346 bool Odd = false;
7347 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7348 // the Odd pattern <1,3,5,...>.
7349 for (unsigned i = 0; i < NumElts; ++i) {
7350 SDValue V = Op.getOperand(i);
7351 const SDNode *N = V.getNode();
7352 if (!isa<ConstantSDNode>(N->getOperand(1)))
7353 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007354 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007355
7356 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007357 if (!Vector) {
7358 Vector = N0.getNode();
7359 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7360 // BUILD_VECTOR.
7361 if (VT.getVectorElementType() !=
7362 N0.getValueType().getVectorElementType())
7363 break;
7364 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007365 Odd = false;
7366 Even = false;
7367 break;
7368 }
7369
7370 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7371 // indices <1,3,5,...>.
7372 uint64_t Val = N->getConstantOperandVal(1);
7373 if (Val == 2 * i) {
7374 Even = true;
7375 continue;
7376 }
7377 if (Val - 1 == 2 * i) {
7378 Odd = true;
7379 continue;
7380 }
7381
7382 // Something does not match: abort.
7383 Odd = false;
7384 Even = false;
7385 break;
7386 }
7387 if (Even || Odd) {
7388 SDValue LHS =
7389 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7390 DAG.getConstant(0, dl, MVT::i64));
7391 SDValue RHS =
7392 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7393 DAG.getConstant(NumElts, dl, MVT::i64));
7394
7395 if (Even && !Odd)
7396 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7397 RHS);
7398 if (Odd && !Even)
7399 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7400 RHS);
7401 }
7402 }
7403
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007404 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007405 // i32 and try again.
7406 if (usesOnlyOneValue) {
7407 if (!isConstant) {
7408 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007409 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007410 LLVM_DEBUG(
7411 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007412 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007413 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007414
7415 // This is actually a DUPLANExx operation, which keeps everything vectory.
7416
Tim Northover3b0846e2014-05-24 12:50:23 +00007417 SDValue Lane = Value.getOperand(1);
7418 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007419 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007420 LLVM_DEBUG(
7421 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7422 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007423 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007424 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007425
7426 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7427 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7428 }
7429
7430 if (VT.getVectorElementType().isFloatingPoint()) {
7431 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007432 EVT EltTy = VT.getVectorElementType();
7433 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7434 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007435 LLVM_DEBUG(
7436 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7437 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007438 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007439 for (unsigned i = 0; i < NumElts; ++i)
7440 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7441 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007442 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007443 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7444 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007445 Val = LowerBUILD_VECTOR(Val, DAG);
7446 if (Val.getNode())
7447 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7448 }
7449 }
7450
7451 // If there was only one constant value used and for more than one lane,
7452 // start by splatting that value, then replace the non-constant lanes. This
7453 // is better than the default, which will perform a separate initialization
7454 // for each lane.
7455 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007456 // Firstly, try to materialize the splat constant.
7457 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7458 Val = ConstantBuildVector(Vec, DAG);
7459 if (!Val) {
7460 // Otherwise, materialize the constant and splat it.
7461 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7462 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7463 }
7464
Tim Northover3b0846e2014-05-24 12:50:23 +00007465 // Now insert the non-constant lanes.
7466 for (unsigned i = 0; i < NumElts; ++i) {
7467 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007468 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007469 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007470 // Note that type legalization likely mucked about with the VT of the
7471 // source operand, so we may have to convert it here before inserting.
7472 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007473 }
7474 return Val;
7475 }
7476
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007477 // This will generate a load from the constant pool.
7478 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007479 LLVM_DEBUG(
7480 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7481 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007482 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007483 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007484
7485 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7486 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007487 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007488 return shuffle;
7489 }
7490
7491 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7492 // know the default expansion would otherwise fall back on something even
7493 // worse. For a vector with one or two non-undef values, that's
7494 // scalar_to_vector for the elements followed by a shuffle (provided the
7495 // shuffle is valid for the target) and materialization element by element
7496 // on the stack followed by a load for everything else.
7497 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007498 LLVM_DEBUG(
7499 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7500 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007501
Tim Northover3b0846e2014-05-24 12:50:23 +00007502 SDValue Vec = DAG.getUNDEF(VT);
7503 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007504 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007505
7506 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007507 // a) Avoid a RMW dependency on the full vector register, and
7508 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007509 // value is already in an S or D register, and we're forced to emit an
7510 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007511 //
7512 // We also allow types like i8 and i16 which are illegal scalar but legal
7513 // vector element types. After type-legalization the inserted value is
7514 // extended (i32) and it is safe to cast them to the vector type by ignoring
7515 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7516 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007517 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007518 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007519 ++i;
7520 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007521 LLVM_DEBUG(if (i < NumElts) dbgs()
7522 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007523 for (; i < NumElts; ++i) {
7524 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007525 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007526 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007527 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007528 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7529 }
7530 return Vec;
7531 }
7532
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007533 LLVM_DEBUG(
7534 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7535 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007536 return SDValue();
7537}
7538
7539SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7540 SelectionDAG &DAG) const {
7541 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7542
Tim Northovere4b8e132014-07-15 10:00:26 +00007543 // Check for non-constant or out of range lane.
7544 EVT VT = Op.getOperand(0).getValueType();
7545 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7546 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007547 return SDValue();
7548
Tim Northover3b0846e2014-05-24 12:50:23 +00007549
7550 // Insertion/extraction are legal for V128 types.
7551 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007552 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7553 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007554 return Op;
7555
7556 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007557 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007558 return SDValue();
7559
7560 // For V64 types, we perform insertion by expanding the value
7561 // to a V128 type and perform the insertion on that.
7562 SDLoc DL(Op);
7563 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7564 EVT WideTy = WideVec.getValueType();
7565
7566 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7567 Op.getOperand(1), Op.getOperand(2));
7568 // Re-narrow the resultant vector.
7569 return NarrowVector(Node, DAG);
7570}
7571
7572SDValue
7573AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7574 SelectionDAG &DAG) const {
7575 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7576
Tim Northovere4b8e132014-07-15 10:00:26 +00007577 // Check for non-constant or out of range lane.
7578 EVT VT = Op.getOperand(0).getValueType();
7579 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7580 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007581 return SDValue();
7582
Tim Northover3b0846e2014-05-24 12:50:23 +00007583
7584 // Insertion/extraction are legal for V128 types.
7585 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007586 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7587 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007588 return Op;
7589
7590 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007591 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007592 return SDValue();
7593
7594 // For V64 types, we perform extraction by expanding the value
7595 // to a V128 type and perform the extraction on that.
7596 SDLoc DL(Op);
7597 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7598 EVT WideTy = WideVec.getValueType();
7599
7600 EVT ExtrTy = WideTy.getVectorElementType();
7601 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7602 ExtrTy = MVT::i32;
7603
7604 // For extractions, we just return the result directly.
7605 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7606 Op.getOperand(1));
7607}
7608
7609SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7610 SelectionDAG &DAG) const {
7611 EVT VT = Op.getOperand(0).getValueType();
7612 SDLoc dl(Op);
7613 // Just in case...
7614 if (!VT.isVector())
7615 return SDValue();
7616
7617 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7618 if (!Cst)
7619 return SDValue();
7620 unsigned Val = Cst->getZExtValue();
7621
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007622 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007623
7624 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7625 if (Val == 0)
7626 return Op;
7627
Tim Northover3b0846e2014-05-24 12:50:23 +00007628 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7629 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007630 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007631 return Op;
7632
7633 return SDValue();
7634}
7635
Zvi Rackover1b736822017-07-26 08:06:58 +00007636bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007637 if (VT.getVectorNumElements() == 4 &&
7638 (VT.is128BitVector() || VT.is64BitVector())) {
7639 unsigned PFIndexes[4];
7640 for (unsigned i = 0; i != 4; ++i) {
7641 if (M[i] < 0)
7642 PFIndexes[i] = 8;
7643 else
7644 PFIndexes[i] = M[i];
7645 }
7646
7647 // Compute the index in the perfect shuffle table.
7648 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7649 PFIndexes[2] * 9 + PFIndexes[3];
7650 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7651 unsigned Cost = (PFEntry >> 30);
7652
7653 if (Cost <= 4)
7654 return true;
7655 }
7656
7657 bool DummyBool;
7658 int DummyInt;
7659 unsigned DummyUnsigned;
7660
7661 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7662 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7663 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7664 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7665 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7666 isZIPMask(M, VT, DummyUnsigned) ||
7667 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7668 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7669 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7670 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7671 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7672}
7673
7674/// getVShiftImm - Check if this is a valid build_vector for the immediate
7675/// operand of a vector shift operation, where all the elements of the
7676/// build_vector must have the same constant integer value.
7677static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7678 // Ignore bit_converts.
7679 while (Op.getOpcode() == ISD::BITCAST)
7680 Op = Op.getOperand(0);
7681 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7682 APInt SplatBits, SplatUndef;
7683 unsigned SplatBitSize;
7684 bool HasAnyUndefs;
7685 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7686 HasAnyUndefs, ElementBits) ||
7687 SplatBitSize > ElementBits)
7688 return false;
7689 Cnt = SplatBits.getSExtValue();
7690 return true;
7691}
7692
7693/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7694/// operand of a vector shift left operation. That value must be in the range:
7695/// 0 <= Value < ElementBits for a left shift; or
7696/// 0 <= Value <= ElementBits for a long left shift.
7697static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7698 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007699 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007700 if (!getVShiftImm(Op, ElementBits, Cnt))
7701 return false;
7702 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7703}
7704
7705/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007706/// operand of a vector shift right operation. The value must be in the range:
7707/// 1 <= Value <= ElementBits for a right shift; or
7708static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007709 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007710 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007711 if (!getVShiftImm(Op, ElementBits, Cnt))
7712 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007713 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7714}
7715
7716SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7717 SelectionDAG &DAG) const {
7718 EVT VT = Op.getValueType();
7719 SDLoc DL(Op);
7720 int64_t Cnt;
7721
7722 if (!Op.getOperand(1).getValueType().isVector())
7723 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007724 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007725
7726 switch (Op.getOpcode()) {
7727 default:
7728 llvm_unreachable("unexpected shift opcode");
7729
7730 case ISD::SHL:
7731 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007732 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7733 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007734 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007735 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7736 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007737 Op.getOperand(0), Op.getOperand(1));
7738 case ISD::SRA:
7739 case ISD::SRL:
7740 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007741 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007742 unsigned Opc =
7743 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007744 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7745 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007746 }
7747
7748 // Right shift register. Note, there is not a shift right register
7749 // instruction, but the shift left register instruction takes a signed
7750 // value, where negative numbers specify a right shift.
7751 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7752 : Intrinsic::aarch64_neon_ushl;
7753 // negate the shift amount
7754 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7755 SDValue NegShiftLeft =
7756 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007757 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7758 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007759 return NegShiftLeft;
7760 }
7761
7762 return SDValue();
7763}
7764
7765static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7766 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007767 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007768 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007769 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7770 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007771
7772 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7773 APInt CnstBits(VT.getSizeInBits(), 0);
7774 APInt UndefBits(VT.getSizeInBits(), 0);
7775 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7776 bool IsZero = IsCnst && (CnstBits == 0);
7777
7778 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7779 switch (CC) {
7780 default:
7781 return SDValue();
7782 case AArch64CC::NE: {
7783 SDValue Fcmeq;
7784 if (IsZero)
7785 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7786 else
7787 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7788 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7789 }
7790 case AArch64CC::EQ:
7791 if (IsZero)
7792 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7793 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7794 case AArch64CC::GE:
7795 if (IsZero)
7796 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7797 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7798 case AArch64CC::GT:
7799 if (IsZero)
7800 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7801 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7802 case AArch64CC::LS:
7803 if (IsZero)
7804 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7805 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7806 case AArch64CC::LT:
7807 if (!NoNans)
7808 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007809 // If we ignore NaNs then we can use to the MI implementation.
7810 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007811 case AArch64CC::MI:
7812 if (IsZero)
7813 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7814 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7815 }
7816 }
7817
7818 switch (CC) {
7819 default:
7820 return SDValue();
7821 case AArch64CC::NE: {
7822 SDValue Cmeq;
7823 if (IsZero)
7824 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7825 else
7826 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7827 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7828 }
7829 case AArch64CC::EQ:
7830 if (IsZero)
7831 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7832 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7833 case AArch64CC::GE:
7834 if (IsZero)
7835 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7836 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7837 case AArch64CC::GT:
7838 if (IsZero)
7839 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7840 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7841 case AArch64CC::LE:
7842 if (IsZero)
7843 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7844 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7845 case AArch64CC::LS:
7846 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7847 case AArch64CC::LO:
7848 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7849 case AArch64CC::LT:
7850 if (IsZero)
7851 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7852 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7853 case AArch64CC::HI:
7854 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7855 case AArch64CC::HS:
7856 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7857 }
7858}
7859
7860SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7861 SelectionDAG &DAG) const {
7862 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7863 SDValue LHS = Op.getOperand(0);
7864 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007865 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007866 SDLoc dl(Op);
7867
7868 if (LHS.getValueType().getVectorElementType().isInteger()) {
7869 assert(LHS.getValueType() == RHS.getValueType());
7870 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007871 SDValue Cmp =
7872 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7873 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007874 }
7875
Carey Williamsda15b5b2018-01-22 14:16:11 +00007876 const bool FullFP16 =
7877 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7878
7879 // Make v4f16 (only) fcmp operations utilise vector instructions
7880 // v8f16 support will be a litle more complicated
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007881 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7882 if (LHS.getValueType().getVectorNumElements() == 4) {
Carey Williamsda15b5b2018-01-22 14:16:11 +00007883 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7884 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7885 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7886 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7887 CmpVT = MVT::v4i32;
7888 } else
7889 return SDValue();
7890 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007891
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007892 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7893 LHS.getValueType().getVectorElementType() != MVT::f128);
Tim Northover3b0846e2014-05-24 12:50:23 +00007894
7895 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7896 // clean. Some of them require two branches to implement.
7897 AArch64CC::CondCode CC1, CC2;
7898 bool ShouldInvert;
7899 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7900
7901 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7902 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007903 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007904 if (!Cmp.getNode())
7905 return SDValue();
7906
7907 if (CC2 != AArch64CC::AL) {
7908 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007909 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007910 if (!Cmp2.getNode())
7911 return SDValue();
7912
Tim Northover45aa89c2015-02-08 00:50:47 +00007913 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007914 }
7915
Tim Northover45aa89c2015-02-08 00:50:47 +00007916 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7917
Tim Northover3b0846e2014-05-24 12:50:23 +00007918 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007919 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007920
7921 return Cmp;
7922}
7923
Amara Emersonc9916d72017-05-16 21:29:22 +00007924static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7925 SelectionDAG &DAG) {
7926 SDValue VecOp = ScalarOp.getOperand(0);
7927 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7929 DAG.getConstant(0, DL, MVT::i64));
7930}
7931
7932SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7933 SelectionDAG &DAG) const {
7934 SDLoc dl(Op);
7935 switch (Op.getOpcode()) {
7936 case ISD::VECREDUCE_ADD:
7937 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7938 case ISD::VECREDUCE_SMAX:
7939 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7940 case ISD::VECREDUCE_SMIN:
7941 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7942 case ISD::VECREDUCE_UMAX:
7943 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7944 case ISD::VECREDUCE_UMIN:
7945 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7946 case ISD::VECREDUCE_FMAX: {
7947 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7948 return DAG.getNode(
7949 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7950 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7951 Op.getOperand(0));
7952 }
7953 case ISD::VECREDUCE_FMIN: {
7954 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7955 return DAG.getNode(
7956 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7957 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7958 Op.getOperand(0));
7959 }
7960 default:
7961 llvm_unreachable("Unhandled reduction");
7962 }
7963}
7964
Oliver Stannard42699172018-02-12 14:22:03 +00007965SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7966 SelectionDAG &DAG) const {
7967 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7968 if (!Subtarget.hasLSE())
7969 return SDValue();
7970
7971 // LSE has an atomic load-add instruction, but not a load-sub.
7972 SDLoc dl(Op);
7973 MVT VT = Op.getSimpleValueType();
7974 SDValue RHS = Op.getOperand(2);
7975 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7976 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7977 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7978 Op.getOperand(0), Op.getOperand(1), RHS,
7979 AN->getMemOperand());
7980}
7981
Oliver Stannard02f08c92018-02-12 17:03:11 +00007982SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7983 SelectionDAG &DAG) const {
7984 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7985 if (!Subtarget.hasLSE())
7986 return SDValue();
7987
7988 // LSE has an atomic load-clear instruction, but not a load-and.
7989 SDLoc dl(Op);
7990 MVT VT = Op.getSimpleValueType();
7991 SDValue RHS = Op.getOperand(2);
7992 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7993 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7994 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7995 Op.getOperand(0), Op.getOperand(1), RHS,
7996 AN->getMemOperand());
7997}
7998
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007999SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8000 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8001 SDLoc dl(Op);
8002 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8003 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8004
Tri Vo6c47c622018-09-22 22:17:50 +00008005 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8006 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8007 if (Subtarget->hasCustomCallingConv())
8008 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008009
8010 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8011 DAG.getConstant(4, dl, MVT::i64));
8012 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8013 Chain =
8014 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8015 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8016 DAG.getRegisterMask(Mask), Chain.getValue(1));
8017 // To match the actual intent better, we should read the output from X15 here
8018 // again (instead of potentially spilling it to the stack), but rereading Size
8019 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8020 // here.
8021
8022 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8023 DAG.getConstant(4, dl, MVT::i64));
8024 return Chain;
8025}
8026
8027SDValue
8028AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8029 SelectionDAG &DAG) const {
8030 assert(Subtarget->isTargetWindows() &&
8031 "Only Windows alloca probing supported");
8032 SDLoc dl(Op);
8033 // Get the inputs.
8034 SDNode *Node = Op.getNode();
8035 SDValue Chain = Op.getOperand(0);
8036 SDValue Size = Op.getOperand(1);
8037 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8038 EVT VT = Node->getValueType(0);
8039
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00008040 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8041 "no-stack-arg-probe")) {
8042 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8043 Chain = SP.getValue(1);
8044 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8045 if (Align)
8046 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8047 DAG.getConstant(-(uint64_t)Align, dl, VT));
8048 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8049 SDValue Ops[2] = {SP, Chain};
8050 return DAG.getMergeValues(Ops, dl);
8051 }
8052
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008053 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8054
8055 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8056
8057 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8058 Chain = SP.getValue(1);
8059 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00008060 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008061 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8062 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00008063 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008064
8065 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8066 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8067
8068 SDValue Ops[2] = {SP, Chain};
8069 return DAG.getMergeValues(Ops, dl);
8070}
8071
Tim Northover3b0846e2014-05-24 12:50:23 +00008072/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8073/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8074/// specified in the intrinsic calls.
8075bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8076 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00008077 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00008078 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008079 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00008080 switch (Intrinsic) {
8081 case Intrinsic::aarch64_neon_ld2:
8082 case Intrinsic::aarch64_neon_ld3:
8083 case Intrinsic::aarch64_neon_ld4:
8084 case Intrinsic::aarch64_neon_ld1x2:
8085 case Intrinsic::aarch64_neon_ld1x3:
8086 case Intrinsic::aarch64_neon_ld1x4:
8087 case Intrinsic::aarch64_neon_ld2lane:
8088 case Intrinsic::aarch64_neon_ld3lane:
8089 case Intrinsic::aarch64_neon_ld4lane:
8090 case Intrinsic::aarch64_neon_ld2r:
8091 case Intrinsic::aarch64_neon_ld3r:
8092 case Intrinsic::aarch64_neon_ld4r: {
8093 Info.opc = ISD::INTRINSIC_W_CHAIN;
8094 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008095 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008096 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8097 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8098 Info.offset = 0;
8099 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008100 // volatile loads with NEON intrinsics not supported
8101 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008102 return true;
8103 }
8104 case Intrinsic::aarch64_neon_st2:
8105 case Intrinsic::aarch64_neon_st3:
8106 case Intrinsic::aarch64_neon_st4:
8107 case Intrinsic::aarch64_neon_st1x2:
8108 case Intrinsic::aarch64_neon_st1x3:
8109 case Intrinsic::aarch64_neon_st1x4:
8110 case Intrinsic::aarch64_neon_st2lane:
8111 case Intrinsic::aarch64_neon_st3lane:
8112 case Intrinsic::aarch64_neon_st4lane: {
8113 Info.opc = ISD::INTRINSIC_VOID;
8114 // Conservatively set memVT to the entire set of vectors stored.
8115 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008116 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008117 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8118 if (!ArgTy->isVectorTy())
8119 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008120 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008121 }
8122 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8123 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8124 Info.offset = 0;
8125 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008126 // volatile stores with NEON intrinsics not supported
8127 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008128 return true;
8129 }
8130 case Intrinsic::aarch64_ldaxr:
8131 case Intrinsic::aarch64_ldxr: {
8132 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8133 Info.opc = ISD::INTRINSIC_W_CHAIN;
8134 Info.memVT = MVT::getVT(PtrTy->getElementType());
8135 Info.ptrVal = I.getArgOperand(0);
8136 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008137 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008138 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008139 return true;
8140 }
8141 case Intrinsic::aarch64_stlxr:
8142 case Intrinsic::aarch64_stxr: {
8143 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8144 Info.opc = ISD::INTRINSIC_W_CHAIN;
8145 Info.memVT = MVT::getVT(PtrTy->getElementType());
8146 Info.ptrVal = I.getArgOperand(1);
8147 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008148 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008149 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008150 return true;
8151 }
8152 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008153 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008154 Info.opc = ISD::INTRINSIC_W_CHAIN;
8155 Info.memVT = MVT::i128;
8156 Info.ptrVal = I.getArgOperand(0);
8157 Info.offset = 0;
8158 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008159 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008160 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008161 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008162 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008163 Info.opc = ISD::INTRINSIC_W_CHAIN;
8164 Info.memVT = MVT::i128;
8165 Info.ptrVal = I.getArgOperand(2);
8166 Info.offset = 0;
8167 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008168 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008169 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008170 default:
8171 break;
8172 }
8173
8174 return false;
8175}
8176
John Brawne3b44f92018-03-23 14:47:07 +00008177bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8178 ISD::LoadExtType ExtTy,
8179 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008180 // TODO: This may be worth removing. Check regression tests for diffs.
8181 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8182 return false;
8183
John Brawne3b44f92018-03-23 14:47:07 +00008184 // If we're reducing the load width in order to avoid having to use an extra
8185 // instruction to do extension then it's probably a good idea.
8186 if (ExtTy != ISD::NON_EXTLOAD)
8187 return true;
8188 // Don't reduce load width if it would prevent us from combining a shift into
8189 // the offset.
8190 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8191 assert(Mem);
8192 const SDValue &Base = Mem->getBasePtr();
8193 if (Base.getOpcode() == ISD::ADD &&
8194 Base.getOperand(1).getOpcode() == ISD::SHL &&
8195 Base.getOperand(1).hasOneUse() &&
8196 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8197 // The shift can be combined if it matches the size of the value being
8198 // loaded (and so reducing the width would make it not match).
8199 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8200 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8201 if (ShiftAmount == Log2_32(LoadBytes))
8202 return false;
8203 }
8204 // We have no reason to disallow reducing the load width, so allow it.
8205 return true;
8206}
8207
Tim Northover3b0846e2014-05-24 12:50:23 +00008208// Truncations from 64-bit GPR to 32-bit GPR is free.
8209bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8210 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8211 return false;
8212 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8213 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008214 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008215}
8216bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008217 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008218 return false;
8219 unsigned NumBits1 = VT1.getSizeInBits();
8220 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008221 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008222}
8223
Chad Rosier54390052015-02-23 19:15:16 +00008224/// Check if it is profitable to hoist instruction in then/else to if.
8225/// Not profitable if I and it's user can form a FMA instruction
8226/// because we prefer FMSUB/FMADD.
8227bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8228 if (I->getOpcode() != Instruction::FMul)
8229 return true;
8230
Davide Italiano3e9986f2017-04-18 00:29:54 +00008231 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008232 return true;
8233
8234 Instruction *User = I->user_back();
8235
8236 if (User &&
8237 !(User->getOpcode() == Instruction::FSub ||
8238 User->getOpcode() == Instruction::FAdd))
8239 return true;
8240
8241 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008242 const DataLayout &DL = I->getModule()->getDataLayout();
8243 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008244
Eric Christopher114fa1c2016-02-29 22:50:49 +00008245 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8246 isOperationLegalOrCustom(ISD::FMA, VT) &&
8247 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8248 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008249}
8250
Tim Northover3b0846e2014-05-24 12:50:23 +00008251// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8252// 64-bit GPR.
8253bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8254 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8255 return false;
8256 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8257 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008258 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008259}
8260bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008261 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008262 return false;
8263 unsigned NumBits1 = VT1.getSizeInBits();
8264 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008265 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008266}
8267
8268bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8269 EVT VT1 = Val.getValueType();
8270 if (isZExtFree(VT1, VT2)) {
8271 return true;
8272 }
8273
8274 if (Val.getOpcode() != ISD::LOAD)
8275 return false;
8276
8277 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008278 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8279 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8280 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008281}
8282
Quentin Colombet6843ac42015-03-31 20:52:32 +00008283bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8284 if (isa<FPExtInst>(Ext))
8285 return false;
8286
Haicheng Wu50692a22017-08-01 21:26:45 +00008287 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008288 if (Ext->getType()->isVectorTy())
8289 return false;
8290
8291 for (const Use &U : Ext->uses()) {
8292 // The extension is free if we can fold it with a left shift in an
8293 // addressing mode or an arithmetic operation: add, sub, and cmp.
8294
8295 // Is there a shift?
8296 const Instruction *Instr = cast<Instruction>(U.getUser());
8297
8298 // Is this a constant shift?
8299 switch (Instr->getOpcode()) {
8300 case Instruction::Shl:
8301 if (!isa<ConstantInt>(Instr->getOperand(1)))
8302 return false;
8303 break;
8304 case Instruction::GetElementPtr: {
8305 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008306 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008307 std::advance(GTI, U.getOperandNo()-1);
8308 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008309 // This extension will end up with a shift because of the scaling factor.
8310 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8311 // Get the shift amount based on the scaling factor:
8312 // log2(sizeof(IdxTy)) - log2(8).
8313 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008314 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008315 // Is the constant foldable in the shift of the addressing mode?
8316 // I.e., shift amount is between 1 and 4 inclusive.
8317 if (ShiftAmt == 0 || ShiftAmt > 4)
8318 return false;
8319 break;
8320 }
8321 case Instruction::Trunc:
8322 // Check if this is a noop.
8323 // trunc(sext ty1 to ty2) to ty1.
8324 if (Instr->getType() == Ext->getOperand(0)->getType())
8325 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008326 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008327 default:
8328 return false;
8329 }
8330
8331 // At this point we can use the bfm family, so this extension is free
8332 // for that use.
8333 }
8334 return true;
8335}
8336
Florian Hahn3b251962019-02-05 10:27:40 +00008337/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8338/// or upper half of the vector elements.
8339static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8340 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8341 auto *FullVT = cast<VectorType>(FullV->getType());
8342 auto *HalfVT = cast<VectorType>(HalfV->getType());
8343 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8344 };
8345
8346 auto extractHalf = [](Value *FullV, Value *HalfV) {
8347 auto *FullVT = cast<VectorType>(FullV->getType());
8348 auto *HalfVT = cast<VectorType>(HalfV->getType());
8349 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8350 };
8351
8352 Constant *M1, *M2;
8353 Value *S1Op1, *S2Op1;
8354 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8355 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8356 return false;
8357
8358 // Check that the operands are half as wide as the result and we extract
8359 // half of the elements of the input vectors.
8360 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8361 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8362 return false;
8363
8364 // Check the mask extracts either the lower or upper half of vector
8365 // elements.
8366 int M1Start = -1;
8367 int M2Start = -1;
8368 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8369 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8370 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8371 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8372 return false;
8373
8374 return true;
8375}
8376
8377/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8378/// of the vector elements.
8379static bool areExtractExts(Value *Ext1, Value *Ext2) {
8380 auto areExtDoubled = [](Instruction *Ext) {
8381 return Ext->getType()->getScalarSizeInBits() ==
8382 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8383 };
8384
8385 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8386 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8387 !areExtDoubled(cast<Instruction>(Ext1)) ||
8388 !areExtDoubled(cast<Instruction>(Ext2)))
8389 return false;
8390
8391 return true;
8392}
8393
8394/// Check if sinking \p I's operands to I's basic block is profitable, because
8395/// the operands can be folded into a target instruction, e.g.
8396/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8397bool AArch64TargetLowering::shouldSinkOperands(
8398 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8399 if (!I->getType()->isVectorTy())
8400 return false;
8401
8402 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8403 switch (II->getIntrinsicID()) {
8404 case Intrinsic::aarch64_neon_umull:
8405 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8406 return false;
8407 Ops.push_back(&II->getOperandUse(0));
8408 Ops.push_back(&II->getOperandUse(1));
8409 return true;
8410 default:
8411 return false;
8412 }
8413 }
8414
8415 switch (I->getOpcode()) {
8416 case Instruction::Sub:
8417 case Instruction::Add: {
8418 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8419 return false;
8420
8421 // If the exts' operands extract either the lower or upper elements, we
8422 // can sink them too.
8423 auto Ext1 = cast<Instruction>(I->getOperand(0));
8424 auto Ext2 = cast<Instruction>(I->getOperand(1));
8425 if (areExtractShuffleVectors(Ext1, Ext2)) {
8426 Ops.push_back(&Ext1->getOperandUse(0));
8427 Ops.push_back(&Ext2->getOperandUse(0));
8428 }
8429
8430 Ops.push_back(&I->getOperandUse(0));
8431 Ops.push_back(&I->getOperandUse(1));
8432
8433 return true;
8434 }
8435 default:
8436 return false;
8437 }
8438 return false;
8439}
8440
Tim Northover3b0846e2014-05-24 12:50:23 +00008441bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8442 unsigned &RequiredAligment) const {
8443 if (!LoadedType.isSimple() ||
8444 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8445 return false;
8446 // Cyclone supports unaligned accesses.
8447 RequiredAligment = 0;
8448 unsigned NumBits = LoadedType.getSizeInBits();
8449 return NumBits == 32 || NumBits == 64;
8450}
8451
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008452/// A helper function for determining the number of interleaved accesses we
8453/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008454unsigned
8455AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8456 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008457 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8458}
8459
Geoff Berryb1e87142017-07-14 21:44:12 +00008460MachineMemOperand::Flags
8461AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8462 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8463 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8464 return MOStridedAccess;
8465 return MachineMemOperand::MONone;
8466}
8467
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008468bool AArch64TargetLowering::isLegalInterleavedAccessType(
8469 VectorType *VecTy, const DataLayout &DL) const {
8470
8471 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8472 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8473
8474 // Ensure the number of vector elements is greater than 1.
8475 if (VecTy->getNumElements() < 2)
8476 return false;
8477
8478 // Ensure the element type is legal.
8479 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8480 return false;
8481
8482 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8483 // 128 will be split into multiple interleaved accesses.
8484 return VecSize == 64 || VecSize % 128 == 0;
8485}
8486
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008487/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008488///
8489/// E.g. Lower an interleaved load (Factor = 2):
8490/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8491/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8492/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8493///
8494/// Into:
8495/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8496/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8497/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8498bool AArch64TargetLowering::lowerInterleavedLoad(
8499 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8500 ArrayRef<unsigned> Indices, unsigned Factor) const {
8501 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8502 "Invalid interleave factor");
8503 assert(!Shuffles.empty() && "Empty shufflevector input");
8504 assert(Shuffles.size() == Indices.size() &&
8505 "Unmatched number of shufflevectors and indices");
8506
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008507 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008508
8509 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008510
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008511 // Skip if we do not have NEON and skip illegal vector types. We can
8512 // "legalize" wide vector types into multiple interleaved accesses as long as
8513 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008514 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008515 return false;
8516
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008517 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8518
Hao Liu7ec8ee32015-06-26 02:32:07 +00008519 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8520 // load integer vectors first and then convert to pointer vectors.
8521 Type *EltTy = VecTy->getVectorElementType();
8522 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008523 VecTy =
8524 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008525
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008526 IRBuilder<> Builder(LI);
8527
8528 // The base address of the load.
8529 Value *BaseAddr = LI->getPointerOperand();
8530
8531 if (NumLoads > 1) {
8532 // If we're going to generate more than one load, reset the sub-vector type
8533 // to something legal.
8534 VecTy = VectorType::get(VecTy->getVectorElementType(),
8535 VecTy->getVectorNumElements() / NumLoads);
8536
8537 // We will compute the pointer operand of each load from the original base
8538 // address using GEPs. Cast the base address to a pointer to the scalar
8539 // element type.
8540 BaseAddr = Builder.CreateBitCast(
8541 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8542 LI->getPointerAddressSpace()));
8543 }
8544
Hao Liu7ec8ee32015-06-26 02:32:07 +00008545 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8546 Type *Tys[2] = {VecTy, PtrTy};
8547 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8548 Intrinsic::aarch64_neon_ld3,
8549 Intrinsic::aarch64_neon_ld4};
8550 Function *LdNFunc =
8551 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8552
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008553 // Holds sub-vectors extracted from the load intrinsic return values. The
8554 // sub-vectors are associated with the shufflevector instructions they will
8555 // replace.
8556 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008557
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008558 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008559
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008560 // If we're generating more than one load, compute the base address of
8561 // subsequent loads as an offset from the previous.
8562 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008563 BaseAddr =
8564 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8565 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008566
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008567 CallInst *LdN = Builder.CreateCall(
8568 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008569
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008570 // Extract and store the sub-vectors returned by the load intrinsic.
8571 for (unsigned i = 0; i < Shuffles.size(); i++) {
8572 ShuffleVectorInst *SVI = Shuffles[i];
8573 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008574
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008575 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8576
8577 // Convert the integer vector to pointer vector if the element is pointer.
8578 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008579 SubVec = Builder.CreateIntToPtr(
8580 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8581 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008582 SubVecs[SVI].push_back(SubVec);
8583 }
8584 }
8585
8586 // Replace uses of the shufflevector instructions with the sub-vectors
8587 // returned by the load intrinsic. If a shufflevector instruction is
8588 // associated with more than one sub-vector, those sub-vectors will be
8589 // concatenated into a single wide vector.
8590 for (ShuffleVectorInst *SVI : Shuffles) {
8591 auto &SubVec = SubVecs[SVI];
8592 auto *WideVec =
8593 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8594 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008595 }
8596
8597 return true;
8598}
8599
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008600/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008601///
8602/// E.g. Lower an interleaved store (Factor = 3):
8603/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008604/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008605/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8606///
8607/// Into:
8608/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8609/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8610/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8611/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8612///
8613/// Note that the new shufflevectors will be removed and we'll only generate one
8614/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008615///
8616/// Example for a more general valid mask (Factor 3). Lower:
8617/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8618/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8619/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8620///
8621/// Into:
8622/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8623/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8624/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8625/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008626bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8627 ShuffleVectorInst *SVI,
8628 unsigned Factor) const {
8629 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8630 "Invalid interleave factor");
8631
8632 VectorType *VecTy = SVI->getType();
8633 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8634 "Invalid interleaved store");
8635
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008636 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008637 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008638 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008639
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008640 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008641
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008642 // Skip if we do not have NEON and skip illegal vector types. We can
8643 // "legalize" wide vector types into multiple interleaved accesses as long as
8644 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008645 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008646 return false;
8647
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008648 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8649
Hao Liu7ec8ee32015-06-26 02:32:07 +00008650 Value *Op0 = SVI->getOperand(0);
8651 Value *Op1 = SVI->getOperand(1);
8652 IRBuilder<> Builder(SI);
8653
8654 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8655 // vectors to integer vectors.
8656 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008657 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008658 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008659
8660 // Convert to the corresponding integer vector.
8661 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8662 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8663 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8664
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008665 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008666 }
8667
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008668 // The base address of the store.
8669 Value *BaseAddr = SI->getPointerOperand();
8670
8671 if (NumStores > 1) {
8672 // If we're going to generate more than one store, reset the lane length
8673 // and sub-vector type to something legal.
8674 LaneLen /= NumStores;
8675 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8676
8677 // We will compute the pointer operand of each store from the original base
8678 // address using GEPs. Cast the base address to a pointer to the scalar
8679 // element type.
8680 BaseAddr = Builder.CreateBitCast(
8681 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8682 SI->getPointerAddressSpace()));
8683 }
8684
8685 auto Mask = SVI->getShuffleMask();
8686
Hao Liu7ec8ee32015-06-26 02:32:07 +00008687 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8688 Type *Tys[2] = {SubVecTy, PtrTy};
8689 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8690 Intrinsic::aarch64_neon_st3,
8691 Intrinsic::aarch64_neon_st4};
8692 Function *StNFunc =
8693 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8694
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008695 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008696
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008697 SmallVector<Value *, 5> Ops;
8698
8699 // Split the shufflevector operands into sub vectors for the new stN call.
8700 for (unsigned i = 0; i < Factor; i++) {
8701 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8702 if (Mask[IdxI] >= 0) {
8703 Ops.push_back(Builder.CreateShuffleVector(
8704 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8705 } else {
8706 unsigned StartMask = 0;
8707 for (unsigned j = 1; j < LaneLen; j++) {
8708 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8709 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8710 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8711 break;
8712 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008713 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008714 // Note: Filling undef gaps with random elements is ok, since
8715 // those elements were being written anyway (with undefs).
8716 // In the case of all undefs we're defaulting to using elems from 0
8717 // Note: StartMask cannot be negative, it's checked in
8718 // isReInterleaveMask
8719 Ops.push_back(Builder.CreateShuffleVector(
8720 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008721 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008722 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008723
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008724 // If we generating more than one store, we compute the base address of
8725 // subsequent stores as an offset from the previous.
8726 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008727 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8728 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008729
8730 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8731 Builder.CreateCall(StNFunc, Ops);
8732 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008733 return true;
8734}
8735
Tim Northover3b0846e2014-05-24 12:50:23 +00008736static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8737 unsigned AlignCheck) {
8738 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8739 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8740}
8741
Sjoerd Meijer180f1ae2019-04-30 08:38:12 +00008742EVT AArch64TargetLowering::getOptimalMemOpType(
8743 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8744 bool ZeroMemset, bool MemcpyStrSrc,
8745 const AttributeList &FuncAttributes) const {
8746 bool CanImplicitFloat =
8747 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
JF Bastien29200612018-09-06 16:03:32 +00008748 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8749 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8750 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8751 // taken one instruction to materialize the v2i64 zero and one store (with
8752 // restrictive addressing mode). Just do i64 stores.
8753 bool IsSmallMemset = IsMemset && Size < 32;
8754 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8755 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8756 return true;
8757 bool Fast;
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00008758 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8759 &Fast) &&
8760 Fast;
JF Bastien29200612018-09-06 16:03:32 +00008761 };
8762
8763 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8764 AlignmentIsAcceptable(MVT::v2i64, 16))
8765 return MVT::v2i64;
8766 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008767 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008768 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008769 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008770 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008771 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008772 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008773}
8774
Amara Emerson13af1ed2019-07-24 22:17:31 +00008775LLT AArch64TargetLowering::getOptimalMemOpLLT(
8776 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8777 bool ZeroMemset, bool MemcpyStrSrc,
8778 const AttributeList &FuncAttributes) const {
8779 bool CanImplicitFloat =
8780 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8781 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8782 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8783 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8784 // taken one instruction to materialize the v2i64 zero and one store (with
8785 // restrictive addressing mode). Just do i64 stores.
8786 bool IsSmallMemset = IsMemset && Size < 32;
8787 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8788 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8789 return true;
8790 bool Fast;
8791 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8792 &Fast) &&
8793 Fast;
8794 };
8795
8796 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8797 AlignmentIsAcceptable(MVT::v2i64, 16))
8798 return LLT::vector(2, 64);
8799 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8800 return LLT::scalar(128);
8801 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8802 return LLT::scalar(64);
8803 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8804 return LLT::scalar(32);
8805 return LLT();
8806}
8807
Tim Northover3b0846e2014-05-24 12:50:23 +00008808// 12-bit optionally shifted immediates are legal for adds.
8809bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008810 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008811 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8812 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008813 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008814 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008815 // Same encoding for add/sub, just flip the sign.
8816 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008817 bool IsLegal = ((Immed >> 12) == 0 ||
8818 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008819 LLVM_DEBUG(dbgs() << "Is " << Immed
8820 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008821 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008822}
8823
8824// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8825// immediates is the same as for an add or a sub.
8826bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008827 return isLegalAddImmediate(Immed);
8828}
8829
8830/// isLegalAddressingMode - Return true if the addressing mode represented
8831/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008832bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8833 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008834 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008835 // AArch64 has five basic addressing modes:
8836 // reg
8837 // reg + 9-bit signed offset
8838 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8839 // reg1 + reg2
8840 // reg + SIZE_IN_BYTES * reg
8841
8842 // No global is ever allowed as a base.
8843 if (AM.BaseGV)
8844 return false;
8845
8846 // No reg+reg+imm addressing.
8847 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8848 return false;
8849
8850 // check reg + imm case:
8851 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8852 uint64_t NumBytes = 0;
8853 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008854 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008855 NumBytes = NumBits / 8;
8856 if (!isPowerOf2_64(NumBits))
8857 NumBytes = 0;
8858 }
8859
8860 if (!AM.Scale) {
8861 int64_t Offset = AM.BaseOffs;
8862
8863 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008864 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008865 return true;
8866
8867 // 12-bit unsigned offset
8868 unsigned shift = Log2_64(NumBytes);
8869 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8870 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8871 (Offset >> shift) << shift == Offset)
8872 return true;
8873 return false;
8874 }
8875
8876 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8877
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008878 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008879}
8880
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008881bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8882 // Consider splitting large offset of struct or array.
8883 return true;
8884}
8885
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008886int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8887 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008888 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008889 // Scaling factors are not free at all.
8890 // Operands | Rt Latency
8891 // -------------------------------------------
8892 // Rt, [Xn, Xm] | 4
8893 // -------------------------------------------
8894 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8895 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008896 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008897 // Scale represents reg2 * scale, thus account for 1 if
8898 // it is not equal to 0 or 1.
8899 return AM.Scale != 0 && AM.Scale != 1;
8900 return -1;
8901}
8902
8903bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8904 VT = VT.getScalarType();
8905
8906 if (!VT.isSimple())
8907 return false;
8908
8909 switch (VT.getSimpleVT().SimpleTy) {
8910 case MVT::f32:
8911 case MVT::f64:
8912 return true;
8913 default:
8914 break;
8915 }
8916
8917 return false;
8918}
8919
8920const MCPhysReg *
8921AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8922 // LR is a callee-save register, but we must treat it as clobbered by any call
8923 // site. Hence we include LR in the scratch registers, which are in turn added
8924 // as implicit-defs for stackmaps and patchpoints.
8925 static const MCPhysReg ScratchRegs[] = {
8926 AArch64::X16, AArch64::X17, AArch64::LR, 0
8927 };
8928 return ScratchRegs;
8929}
8930
8931bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008932AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8933 CombineLevel Level) const {
8934 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008935 EVT VT = N->getValueType(0);
8936 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8937 // it with shift to let it be lowered to UBFX.
8938 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8939 isa<ConstantSDNode>(N->getOperand(1))) {
8940 uint64_t TruncMask = N->getConstantOperandVal(1);
8941 if (isMask_64(TruncMask) &&
8942 N->getOperand(0).getOpcode() == ISD::SRL &&
8943 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8944 return false;
8945 }
8946 return true;
8947}
8948
8949bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8950 Type *Ty) const {
8951 assert(Ty->isIntegerTy());
8952
8953 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8954 if (BitSize == 0)
8955 return false;
8956
8957 int64_t Val = Imm.getSExtValue();
8958 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8959 return true;
8960
8961 if ((int64_t)Val < 0)
8962 Val = ~Val;
8963 if (BitSize == 32)
8964 Val &= (1LL << 32) - 1;
8965
8966 unsigned LZ = countLeadingZeros((uint64_t)Val);
8967 unsigned Shift = (63 - LZ) / 16;
8968 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008969 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008970}
8971
Sebastian Pop41073e82018-03-06 16:54:55 +00008972bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8973 unsigned Index) const {
8974 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8975 return false;
8976
8977 return (Index == 0 || Index == ResVT.getVectorNumElements());
8978}
8979
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008980/// Turn vector tests of the signbit in the form of:
8981/// xor (sra X, elt_size(X)-1), -1
8982/// into:
8983/// cmge X, X, #0
8984static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8985 const AArch64Subtarget *Subtarget) {
8986 EVT VT = N->getValueType(0);
8987 if (!Subtarget->hasNEON() || !VT.isVector())
8988 return SDValue();
8989
8990 // There must be a shift right algebraic before the xor, and the xor must be a
8991 // 'not' operation.
8992 SDValue Shift = N->getOperand(0);
8993 SDValue Ones = N->getOperand(1);
8994 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8995 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8996 return SDValue();
8997
8998 // The shift should be smearing the sign bit across each vector element.
8999 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9000 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9001 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9002 return SDValue();
9003
9004 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9005}
9006
Tim Northover3b0846e2014-05-24 12:50:23 +00009007// Generate SUBS and CSEL for integer abs.
9008static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9009 EVT VT = N->getValueType(0);
9010
9011 SDValue N0 = N->getOperand(0);
9012 SDValue N1 = N->getOperand(1);
9013 SDLoc DL(N);
9014
9015 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9016 // and change it to SUB and CSEL.
9017 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9018 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9019 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9020 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9021 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009022 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00009023 N0.getOperand(0));
9024 // Generate SUBS & CSEL.
9025 SDValue Cmp =
9026 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009027 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009028 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009029 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00009030 SDValue(Cmp.getNode(), 1));
9031 }
9032 return SDValue();
9033}
9034
Tim Northover3b0846e2014-05-24 12:50:23 +00009035static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9036 TargetLowering::DAGCombinerInfo &DCI,
9037 const AArch64Subtarget *Subtarget) {
9038 if (DCI.isBeforeLegalizeOps())
9039 return SDValue();
9040
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00009041 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9042 return Cmp;
9043
Tim Northover3b0846e2014-05-24 12:50:23 +00009044 return performIntegerAbsCombine(N, DAG);
9045}
9046
Chad Rosier17020f92014-07-23 14:57:52 +00009047SDValue
9048AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9049 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00009050 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00009051 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00009052 if (isIntDivCheap(N->getValueType(0), Attr))
9053 return SDValue(N,0); // Lower SDIV as SDIV
9054
Chad Rosier17020f92014-07-23 14:57:52 +00009055 // fold (sdiv X, pow2)
9056 EVT VT = N->getValueType(0);
9057 if ((VT != MVT::i32 && VT != MVT::i64) ||
9058 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9059 return SDValue();
9060
9061 SDLoc DL(N);
9062 SDValue N0 = N->getOperand(0);
9063 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009064 SDValue Zero = DAG.getConstant(0, DL, VT);
9065 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00009066
9067 // Add (N0 < 0) ? Pow2 - 1 : 0;
9068 SDValue CCVal;
9069 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9070 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9071 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9072
Craig Toppera568a272018-07-30 21:04:34 +00009073 Created.push_back(Cmp.getNode());
9074 Created.push_back(Add.getNode());
9075 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00009076
9077 // Divide by pow2.
9078 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009079 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00009080
9081 // If we're dividing by a positive value, we're done. Otherwise, we must
9082 // negate the result.
9083 if (Divisor.isNonNegative())
9084 return SRA;
9085
Craig Toppera568a272018-07-30 21:04:34 +00009086 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009087 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00009088}
9089
Tim Northover3b0846e2014-05-24 12:50:23 +00009090static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9091 TargetLowering::DAGCombinerInfo &DCI,
9092 const AArch64Subtarget *Subtarget) {
9093 if (DCI.isBeforeLegalizeOps())
9094 return SDValue();
9095
Chad Rosier31ee8132016-11-11 17:07:37 +00009096 // The below optimizations require a constant RHS.
9097 if (!isa<ConstantSDNode>(N->getOperand(1)))
9098 return SDValue();
9099
9100 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9101 const APInt &ConstValue = C->getAPIntValue();
9102
Tim Northover3b0846e2014-05-24 12:50:23 +00009103 // Multiplication of a power of two plus/minus one can be done more
9104 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9105 // future CPUs have a cheaper MADD instruction, this may need to be
9106 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9107 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009108 // More aggressively, some multiplications N0 * C can be lowered to
9109 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9110 // e.g. 6=3*2=(2+1)*2.
9111 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9112 // which equals to (1+2)*16-(1+2).
9113 SDValue N0 = N->getOperand(0);
9114 // TrailingZeroes is used to test if the mul can be lowered to
9115 // shift+add+shift.
9116 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9117 if (TrailingZeroes) {
9118 // Conservatively do not lower to shift+add+shift if the mul might be
9119 // folded into smul or umul.
9120 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9121 isZeroExtended(N0.getNode(), DAG)))
9122 return SDValue();
9123 // Conservatively do not lower to shift+add+shift if the mul might be
9124 // folded into madd or msub.
9125 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9126 N->use_begin()->getOpcode() == ISD::SUB))
9127 return SDValue();
9128 }
9129 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9130 // and shift+add+shift.
9131 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9132
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009133 unsigned ShiftAmt, AddSubOpc;
9134 // Is the shifted value the LHS operand of the add/sub?
9135 bool ShiftValUseIsN0 = true;
9136 // Do we need to negate the result?
9137 bool NegateResult = false;
9138
Chad Rosier31ee8132016-11-11 17:07:37 +00009139 if (ConstValue.isNonNegative()) {
9140 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009141 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009142 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9143 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009144 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009145 if (SCVMinus1.isPowerOf2()) {
9146 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009147 AddSubOpc = ISD::ADD;
9148 } else if (CVPlus1.isPowerOf2()) {
9149 ShiftAmt = CVPlus1.logBase2();
9150 AddSubOpc = ISD::SUB;
9151 } else
9152 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009153 } else {
9154 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009155 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009156 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009157 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009158 if (CVNegPlus1.isPowerOf2()) {
9159 ShiftAmt = CVNegPlus1.logBase2();
9160 AddSubOpc = ISD::SUB;
9161 ShiftValUseIsN0 = false;
9162 } else if (CVNegMinus1.isPowerOf2()) {
9163 ShiftAmt = CVNegMinus1.logBase2();
9164 AddSubOpc = ISD::ADD;
9165 NegateResult = true;
9166 } else
9167 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009168 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009169
9170 SDLoc DL(N);
9171 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009172 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009173 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9174
9175 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9176 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9177 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009178 assert(!(NegateResult && TrailingZeroes) &&
9179 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009180 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009181 if (NegateResult)
9182 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9183 // Shift the result.
9184 if (TrailingZeroes)
9185 return DAG.getNode(ISD::SHL, DL, VT, Res,
9186 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9187 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009188}
9189
Jim Grosbachf7502c42014-07-18 00:40:52 +00009190static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9191 SelectionDAG &DAG) {
9192 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9193 // optimize away operation when it's from a constant.
9194 //
9195 // The general transformation is:
9196 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9197 // AND(VECTOR_CMP(x,y), constant2)
9198 // constant2 = UNARYOP(constant)
9199
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009200 // Early exit if this isn't a vector operation, the operand of the
9201 // unary operation isn't a bitwise AND, or if the sizes of the operations
9202 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009203 EVT VT = N->getValueType(0);
9204 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009205 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9206 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009207 return SDValue();
9208
Jim Grosbach724e4382014-07-23 20:41:43 +00009209 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009210 // make the transformation for non-constant splats as well, but it's unclear
9211 // that would be a benefit as it would not eliminate any operations, just
9212 // perform one more step in scalar code before moving to the vector unit.
9213 if (BuildVectorSDNode *BV =
9214 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009215 // Bail out if the vector isn't a constant.
9216 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009217 return SDValue();
9218
9219 // Everything checks out. Build up the new and improved node.
9220 SDLoc DL(N);
9221 EVT IntVT = BV->getValueType(0);
9222 // Create a new constant of the appropriate type for the transformed
9223 // DAG.
9224 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9225 // The AND node needs bitcasts to/from an integer vector type around it.
9226 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9227 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9228 N->getOperand(0)->getOperand(0), MaskConst);
9229 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9230 return Res;
9231 }
9232
9233 return SDValue();
9234}
9235
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009236static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9237 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009238 // First try to optimize away the conversion when it's conditionally from
9239 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009240 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009241 return Res;
9242
Tim Northover3b0846e2014-05-24 12:50:23 +00009243 EVT VT = N->getValueType(0);
9244 if (VT != MVT::f32 && VT != MVT::f64)
9245 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009246
Tim Northover3b0846e2014-05-24 12:50:23 +00009247 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009248 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009249 return SDValue();
9250
9251 // If the result of an integer load is only used by an integer-to-float
9252 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009253 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009254 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009255 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009256 // Do not change the width of a volatile load.
9257 !cast<LoadSDNode>(N0)->isVolatile()) {
9258 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9259 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009260 LN0->getPointerInfo(), LN0->getAlignment(),
9261 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009262
9263 // Make sure successors of the original load stay after it by updating them
9264 // to use the new Chain.
9265 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9266
9267 unsigned Opcode =
9268 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9269 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9270 }
9271
9272 return SDValue();
9273}
9274
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009275/// Fold a floating-point multiply by power of two into floating-point to
9276/// fixed-point conversion.
9277static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009278 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009279 const AArch64Subtarget *Subtarget) {
9280 if (!Subtarget->hasNEON())
9281 return SDValue();
9282
Sam Parkera0bd6f82019-06-03 08:49:17 +00009283 if (!N->getValueType(0).isSimple())
9284 return SDValue();
9285
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009286 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009287 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9288 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009289 return SDValue();
9290
9291 SDValue ConstVec = Op->getOperand(1);
9292 if (!isa<BuildVectorSDNode>(ConstVec))
9293 return SDValue();
9294
9295 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9296 uint32_t FloatBits = FloatTy.getSizeInBits();
9297 if (FloatBits != 32 && FloatBits != 64)
9298 return SDValue();
9299
9300 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9301 uint32_t IntBits = IntTy.getSizeInBits();
9302 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9303 return SDValue();
9304
9305 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9306 if (IntBits > FloatBits)
9307 return SDValue();
9308
9309 BitVector UndefElements;
9310 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9311 int32_t Bits = IntBits == 64 ? 64 : 32;
9312 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9313 if (C == -1 || C == 0 || C > Bits)
9314 return SDValue();
9315
9316 MVT ResTy;
9317 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9318 switch (NumLanes) {
9319 default:
9320 return SDValue();
9321 case 2:
9322 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9323 break;
9324 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009325 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009326 break;
9327 }
9328
Silviu Barangafa00ba32016-08-08 13:13:57 +00009329 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9330 return SDValue();
9331
9332 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9333 "Illegal vector type after legalization");
9334
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009335 SDLoc DL(N);
9336 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9337 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9338 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9339 SDValue FixConv =
9340 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9341 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9342 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9343 // We can handle smaller integers by generating an extra trunc.
9344 if (IntBits < FloatBits)
9345 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9346
9347 return FixConv;
9348}
9349
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009350/// Fold a floating-point divide by power of two into fixed-point to
9351/// floating-point conversion.
9352static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009353 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009354 const AArch64Subtarget *Subtarget) {
9355 if (!Subtarget->hasNEON())
9356 return SDValue();
9357
9358 SDValue Op = N->getOperand(0);
9359 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009360 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9361 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009362 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9363 return SDValue();
9364
9365 SDValue ConstVec = N->getOperand(1);
9366 if (!isa<BuildVectorSDNode>(ConstVec))
9367 return SDValue();
9368
9369 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9370 int32_t IntBits = IntTy.getSizeInBits();
9371 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9372 return SDValue();
9373
9374 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9375 int32_t FloatBits = FloatTy.getSizeInBits();
9376 if (FloatBits != 32 && FloatBits != 64)
9377 return SDValue();
9378
9379 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9380 if (IntBits > FloatBits)
9381 return SDValue();
9382
9383 BitVector UndefElements;
9384 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9385 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9386 if (C == -1 || C == 0 || C > FloatBits)
9387 return SDValue();
9388
9389 MVT ResTy;
9390 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9391 switch (NumLanes) {
9392 default:
9393 return SDValue();
9394 case 2:
9395 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9396 break;
9397 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009398 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009399 break;
9400 }
9401
Tim Northover85cf5642016-08-26 18:52:31 +00009402 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9403 return SDValue();
9404
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009405 SDLoc DL(N);
9406 SDValue ConvInput = Op.getOperand(0);
9407 bool IsSigned = Opc == ISD::SINT_TO_FP;
9408 if (IntBits < FloatBits)
9409 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9410 ResTy, ConvInput);
9411
9412 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9413 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9414 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9415 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9416 DAG.getConstant(C, DL, MVT::i32));
9417}
9418
Tim Northover3b0846e2014-05-24 12:50:23 +00009419/// An EXTR instruction is made up of two shifts, ORed together. This helper
9420/// searches for and classifies those shifts.
9421static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9422 bool &FromHi) {
9423 if (N.getOpcode() == ISD::SHL)
9424 FromHi = false;
9425 else if (N.getOpcode() == ISD::SRL)
9426 FromHi = true;
9427 else
9428 return false;
9429
9430 if (!isa<ConstantSDNode>(N.getOperand(1)))
9431 return false;
9432
9433 ShiftAmount = N->getConstantOperandVal(1);
9434 Src = N->getOperand(0);
9435 return true;
9436}
9437
9438/// EXTR instruction extracts a contiguous chunk of bits from two existing
9439/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009440/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9441/// with an EXTR. Can't quite be done in TableGen because the two immediates
9442/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009443static SDValue tryCombineToEXTR(SDNode *N,
9444 TargetLowering::DAGCombinerInfo &DCI) {
9445 SelectionDAG &DAG = DCI.DAG;
9446 SDLoc DL(N);
9447 EVT VT = N->getValueType(0);
9448
9449 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9450
9451 if (VT != MVT::i32 && VT != MVT::i64)
9452 return SDValue();
9453
9454 SDValue LHS;
9455 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009456 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009457 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9458 return SDValue();
9459
9460 SDValue RHS;
9461 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009462 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009463 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9464 return SDValue();
9465
9466 // If they're both trying to come from the high part of the register, they're
9467 // not really an EXTR.
9468 if (LHSFromHi == RHSFromHi)
9469 return SDValue();
9470
9471 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9472 return SDValue();
9473
9474 if (LHSFromHi) {
9475 std::swap(LHS, RHS);
9476 std::swap(ShiftLHS, ShiftRHS);
9477 }
9478
9479 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009480 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009481}
9482
9483static SDValue tryCombineToBSL(SDNode *N,
9484 TargetLowering::DAGCombinerInfo &DCI) {
9485 EVT VT = N->getValueType(0);
9486 SelectionDAG &DAG = DCI.DAG;
9487 SDLoc DL(N);
9488
9489 if (!VT.isVector())
9490 return SDValue();
9491
9492 SDValue N0 = N->getOperand(0);
9493 if (N0.getOpcode() != ISD::AND)
9494 return SDValue();
9495
9496 SDValue N1 = N->getOperand(1);
9497 if (N1.getOpcode() != ISD::AND)
9498 return SDValue();
9499
9500 // We only have to look for constant vectors here since the general, variable
9501 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009502 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009503 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9504 for (int i = 1; i >= 0; --i)
9505 for (int j = 1; j >= 0; --j) {
9506 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9507 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9508 if (!BVN0 || !BVN1)
9509 continue;
9510
9511 bool FoundMatch = true;
9512 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9513 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9514 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9515 if (!CN0 || !CN1 ||
9516 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9517 FoundMatch = false;
9518 break;
9519 }
9520 }
9521
9522 if (FoundMatch)
9523 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9524 N0->getOperand(1 - i), N1->getOperand(1 - j));
9525 }
9526
9527 return SDValue();
9528}
9529
9530static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9531 const AArch64Subtarget *Subtarget) {
9532 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009533 SelectionDAG &DAG = DCI.DAG;
9534 EVT VT = N->getValueType(0);
9535
9536 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9537 return SDValue();
9538
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009539 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009540 return Res;
9541
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009542 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009543 return Res;
9544
9545 return SDValue();
9546}
9547
Nikita Popov1a261442019-03-15 21:04:34 +00009548static SDValue performANDCombine(SDNode *N,
9549 TargetLowering::DAGCombinerInfo &DCI) {
9550 SelectionDAG &DAG = DCI.DAG;
9551 SDValue LHS = N->getOperand(0);
9552 EVT VT = N->getValueType(0);
9553 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9554 return SDValue();
9555
9556 BuildVectorSDNode *BVN =
9557 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9558 if (!BVN)
9559 return SDValue();
9560
9561 // AND does not accept an immediate, so check if we can use a BIC immediate
9562 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9563 // pattern in isel, because some immediates may be lowered to the preferred
9564 // (and x, (movi imm)) form, even though an mvni representation also exists.
9565 APInt DefBits(VT.getSizeInBits(), 0);
9566 APInt UndefBits(VT.getSizeInBits(), 0);
9567 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9568 SDValue NewOp;
9569
9570 DefBits = ~DefBits;
9571 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9572 DefBits, &LHS)) ||
9573 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9574 DefBits, &LHS)))
9575 return NewOp;
9576
9577 UndefBits = ~UndefBits;
9578 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9579 UndefBits, &LHS)) ||
9580 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9581 UndefBits, &LHS)))
9582 return NewOp;
9583 }
9584
9585 return SDValue();
9586}
9587
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009588static SDValue performSRLCombine(SDNode *N,
9589 TargetLowering::DAGCombinerInfo &DCI) {
9590 SelectionDAG &DAG = DCI.DAG;
9591 EVT VT = N->getValueType(0);
9592 if (VT != MVT::i32 && VT != MVT::i64)
9593 return SDValue();
9594
9595 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9596 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9597 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9598 SDValue N0 = N->getOperand(0);
9599 if (N0.getOpcode() == ISD::BSWAP) {
9600 SDLoc DL(N);
9601 SDValue N1 = N->getOperand(1);
9602 SDValue N00 = N0.getOperand(0);
9603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9604 uint64_t ShiftAmt = C->getZExtValue();
9605 if (VT == MVT::i32 && ShiftAmt == 16 &&
9606 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9607 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9608 if (VT == MVT::i64 && ShiftAmt == 32 &&
9609 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9610 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9611 }
9612 }
9613 return SDValue();
9614}
9615
Tim Northover3b0846e2014-05-24 12:50:23 +00009616static SDValue performBitcastCombine(SDNode *N,
9617 TargetLowering::DAGCombinerInfo &DCI,
9618 SelectionDAG &DAG) {
9619 // Wait 'til after everything is legalized to try this. That way we have
9620 // legal vector types and such.
9621 if (DCI.isBeforeLegalizeOps())
9622 return SDValue();
9623
9624 // Remove extraneous bitcasts around an extract_subvector.
9625 // For example,
9626 // (v4i16 (bitconvert
9627 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9628 // becomes
9629 // (extract_subvector ((v8i16 ...), (i64 4)))
9630
9631 // Only interested in 64-bit vectors as the ultimate result.
9632 EVT VT = N->getValueType(0);
9633 if (!VT.isVector())
9634 return SDValue();
9635 if (VT.getSimpleVT().getSizeInBits() != 64)
9636 return SDValue();
9637 // Is the operand an extract_subvector starting at the beginning or halfway
9638 // point of the vector? A low half may also come through as an
9639 // EXTRACT_SUBREG, so look for that, too.
9640 SDValue Op0 = N->getOperand(0);
9641 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9642 !(Op0->isMachineOpcode() &&
9643 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9644 return SDValue();
9645 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9646 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9647 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9648 return SDValue();
9649 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9650 if (idx != AArch64::dsub)
9651 return SDValue();
9652 // The dsub reference is equivalent to a lane zero subvector reference.
9653 idx = 0;
9654 }
9655 // Look through the bitcast of the input to the extract.
9656 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9657 return SDValue();
9658 SDValue Source = Op0->getOperand(0)->getOperand(0);
9659 // If the source type has twice the number of elements as our destination
9660 // type, we know this is an extract of the high or low half of the vector.
9661 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009662 if (!SVT.isVector() ||
9663 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009664 return SDValue();
9665
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009666 LLVM_DEBUG(
9667 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009668
9669 // Create the simplified form to just extract the low or high half of the
9670 // vector directly rather than bothering with the bitcasts.
9671 SDLoc dl(N);
9672 unsigned NumElements = VT.getVectorNumElements();
9673 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009674 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009675 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9676 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009677 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009678 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9679 Source, SubReg),
9680 0);
9681 }
9682}
9683
9684static SDValue performConcatVectorsCombine(SDNode *N,
9685 TargetLowering::DAGCombinerInfo &DCI,
9686 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009687 SDLoc dl(N);
9688 EVT VT = N->getValueType(0);
9689 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9690
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009691 // Optimize concat_vectors of truncated vectors, where the intermediate
9692 // type is illegal, to avoid said illegality, e.g.,
9693 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9694 // (v2i16 (truncate (v2i64)))))
9695 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009696 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9697 // (v4i32 (bitcast (v2i64))),
9698 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009699 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9700 // on both input and result type, so we might generate worse code.
9701 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9702 if (N->getNumOperands() == 2 &&
9703 N0->getOpcode() == ISD::TRUNCATE &&
9704 N1->getOpcode() == ISD::TRUNCATE) {
9705 SDValue N00 = N0->getOperand(0);
9706 SDValue N10 = N1->getOperand(0);
9707 EVT N00VT = N00.getValueType();
9708
9709 if (N00VT == N10.getValueType() &&
9710 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9711 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009712 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9713 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9714 for (size_t i = 0; i < Mask.size(); ++i)
9715 Mask[i] = i * 2;
9716 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9717 DAG.getVectorShuffle(
9718 MidVT, dl,
9719 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9720 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009721 }
9722 }
9723
Tim Northover3b0846e2014-05-24 12:50:23 +00009724 // Wait 'til after everything is legalized to try this. That way we have
9725 // legal vector types and such.
9726 if (DCI.isBeforeLegalizeOps())
9727 return SDValue();
9728
Tim Northover3b0846e2014-05-24 12:50:23 +00009729 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9730 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9731 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009732 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009733 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009734 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009735 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009736 }
9737
9738 // Canonicalise concat_vectors so that the right-hand vector has as few
9739 // bit-casts as possible before its real operation. The primary matching
9740 // destination for these operations will be the narrowing "2" instructions,
9741 // which depend on the operation being performed on this right-hand vector.
9742 // For example,
9743 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9744 // becomes
9745 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9746
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009747 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009748 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009749 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009750 MVT RHSTy = RHS.getValueType().getSimpleVT();
9751 // If the RHS is not a vector, this is not the pattern we're looking for.
9752 if (!RHSTy.isVector())
9753 return SDValue();
9754
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009755 LLVM_DEBUG(
9756 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009757
9758 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9759 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009760 return DAG.getNode(ISD::BITCAST, dl, VT,
9761 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9762 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9763 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009764}
9765
9766static SDValue tryCombineFixedPointConvert(SDNode *N,
9767 TargetLowering::DAGCombinerInfo &DCI,
9768 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009769 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009770 // legal vector types and such.
9771 if (DCI.isBeforeLegalizeOps())
9772 return SDValue();
9773 // Transform a scalar conversion of a value from a lane extract into a
9774 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9775 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9776 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9777 //
9778 // The second form interacts better with instruction selection and the
9779 // register allocator to avoid cross-class register copies that aren't
9780 // coalescable due to a lane reference.
9781
9782 // Check the operand and see if it originates from a lane extract.
9783 SDValue Op1 = N->getOperand(1);
9784 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9785 // Yep, no additional predication needed. Perform the transform.
9786 SDValue IID = N->getOperand(0);
9787 SDValue Shift = N->getOperand(2);
9788 SDValue Vec = Op1.getOperand(0);
9789 SDValue Lane = Op1.getOperand(1);
9790 EVT ResTy = N->getValueType(0);
9791 EVT VecResTy;
9792 SDLoc DL(N);
9793
9794 // The vector width should be 128 bits by the time we get here, even
9795 // if it started as 64 bits (the extract_vector handling will have
9796 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009797 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009798 "unexpected vector size on extract_vector_elt!");
9799 if (Vec.getValueType() == MVT::v4i32)
9800 VecResTy = MVT::v4f32;
9801 else if (Vec.getValueType() == MVT::v2i64)
9802 VecResTy = MVT::v2f64;
9803 else
Craig Topper2a30d782014-06-18 05:05:13 +00009804 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009805
9806 SDValue Convert =
9807 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9808 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9809 }
9810 return SDValue();
9811}
9812
9813// AArch64 high-vector "long" operations are formed by performing the non-high
9814// version on an extract_subvector of each operand which gets the high half:
9815//
9816// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9817//
9818// However, there are cases which don't have an extract_high explicitly, but
9819// have another operation that can be made compatible with one for free. For
9820// example:
9821//
9822// (dupv64 scalar) --> (extract_high (dup128 scalar))
9823//
9824// This routine does the actual conversion of such DUPs, once outer routines
9825// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009826// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9827// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009828static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009829 switch (N.getOpcode()) {
9830 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009831 case AArch64ISD::DUPLANE8:
9832 case AArch64ISD::DUPLANE16:
9833 case AArch64ISD::DUPLANE32:
9834 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009835 case AArch64ISD::MOVI:
9836 case AArch64ISD::MOVIshift:
9837 case AArch64ISD::MOVIedit:
9838 case AArch64ISD::MOVImsl:
9839 case AArch64ISD::MVNIshift:
9840 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009841 break;
9842 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009843 // FMOV could be supported, but isn't very useful, as it would only occur
9844 // if you passed a bitcast' floating point immediate to an eligible long
9845 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009846 return SDValue();
9847 }
9848
9849 MVT NarrowTy = N.getSimpleValueType();
9850 if (!NarrowTy.is64BitVector())
9851 return SDValue();
9852
9853 MVT ElementTy = NarrowTy.getVectorElementType();
9854 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009855 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009856
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009857 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009858 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9859 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009860 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009861}
9862
Eli Friedman29c06092019-02-08 00:23:35 +00009863static bool isEssentiallyExtractHighSubvector(SDValue N) {
9864 if (N.getOpcode() == ISD::BITCAST)
9865 N = N.getOperand(0);
9866 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9867 return false;
9868 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9869 N.getOperand(0).getValueType().getVectorNumElements() / 2;
Tim Northover3b0846e2014-05-24 12:50:23 +00009870}
9871
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009872/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009873struct GenericSetCCInfo {
9874 const SDValue *Opnd0;
9875 const SDValue *Opnd1;
9876 ISD::CondCode CC;
9877};
9878
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009879/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009880struct AArch64SetCCInfo {
9881 const SDValue *Cmp;
9882 AArch64CC::CondCode CC;
9883};
9884
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009885/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009886union SetCCInfo {
9887 GenericSetCCInfo Generic;
9888 AArch64SetCCInfo AArch64;
9889};
9890
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009891/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009892/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9893/// GenericSetCCInfo.
9894struct SetCCInfoAndKind {
9895 SetCCInfo Info;
9896 bool IsAArch64;
9897};
9898
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009899/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009900/// an
9901/// AArch64 lowered one.
9902/// \p SetCCInfo is filled accordingly.
9903/// \post SetCCInfo is meanginfull only when this function returns true.
9904/// \return True when Op is a kind of SET_CC operation.
9905static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9906 // If this is a setcc, this is straight forward.
9907 if (Op.getOpcode() == ISD::SETCC) {
9908 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9909 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9910 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9911 SetCCInfo.IsAArch64 = false;
9912 return true;
9913 }
9914 // Otherwise, check if this is a matching csel instruction.
9915 // In other words:
9916 // - csel 1, 0, cc
9917 // - csel 0, 1, !cc
9918 if (Op.getOpcode() != AArch64ISD::CSEL)
9919 return false;
9920 // Set the information about the operands.
9921 // TODO: we want the operands of the Cmp not the csel
9922 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9923 SetCCInfo.IsAArch64 = true;
9924 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9925 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9926
9927 // Check that the operands matches the constraints:
9928 // (1) Both operands must be constants.
9929 // (2) One must be 1 and the other must be 0.
9930 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9931 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9932
9933 // Check (1).
9934 if (!TValue || !FValue)
9935 return false;
9936
9937 // Check (2).
9938 if (!TValue->isOne()) {
9939 // Update the comparison when we are interested in !cc.
9940 std::swap(TValue, FValue);
9941 SetCCInfo.Info.AArch64.CC =
9942 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9943 }
9944 return TValue->isOne() && FValue->isNullValue();
9945}
9946
9947// Returns true if Op is setcc or zext of setcc.
9948static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9949 if (isSetCC(Op, Info))
9950 return true;
9951 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9952 isSetCC(Op->getOperand(0), Info));
9953}
9954
9955// The folding we want to perform is:
9956// (add x, [zext] (setcc cc ...) )
9957// -->
9958// (csel x, (add x, 1), !cc ...)
9959//
9960// The latter will get matched to a CSINC instruction.
9961static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9962 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9963 SDValue LHS = Op->getOperand(0);
9964 SDValue RHS = Op->getOperand(1);
9965 SetCCInfoAndKind InfoAndKind;
9966
9967 // If neither operand is a SET_CC, give up.
9968 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9969 std::swap(LHS, RHS);
9970 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9971 return SDValue();
9972 }
9973
9974 // FIXME: This could be generatized to work for FP comparisons.
9975 EVT CmpVT = InfoAndKind.IsAArch64
9976 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9977 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9978 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9979 return SDValue();
9980
9981 SDValue CCVal;
9982 SDValue Cmp;
9983 SDLoc dl(Op);
9984 if (InfoAndKind.IsAArch64) {
9985 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009986 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9987 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009988 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9989 } else
9990 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9991 *InfoAndKind.Info.Generic.Opnd1,
9992 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9993 CCVal, DAG, dl);
9994
9995 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009996 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009997 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9998}
9999
10000// The basic add/sub long vector instructions have variants with "2" on the end
10001// which act on the high-half of their inputs. They are normally matched by
10002// patterns like:
10003//
10004// (add (zeroext (extract_high LHS)),
10005// (zeroext (extract_high RHS)))
10006// -> uaddl2 vD, vN, vM
10007//
10008// However, if one of the extracts is something like a duplicate, this
10009// instruction can still be used profitably. This function puts the DAG into a
10010// more appropriate form for those patterns to trigger.
10011static SDValue performAddSubLongCombine(SDNode *N,
10012 TargetLowering::DAGCombinerInfo &DCI,
10013 SelectionDAG &DAG) {
10014 if (DCI.isBeforeLegalizeOps())
10015 return SDValue();
10016
10017 MVT VT = N->getSimpleValueType(0);
10018 if (!VT.is128BitVector()) {
10019 if (N->getOpcode() == ISD::ADD)
10020 return performSetccAddFolding(N, DAG);
10021 return SDValue();
10022 }
10023
10024 // Make sure both branches are extended in the same way.
10025 SDValue LHS = N->getOperand(0);
10026 SDValue RHS = N->getOperand(1);
10027 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10028 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10029 LHS.getOpcode() != RHS.getOpcode())
10030 return SDValue();
10031
10032 unsigned ExtType = LHS.getOpcode();
10033
10034 // It's not worth doing if at least one of the inputs isn't already an
10035 // extract, but we don't know which it'll be so we have to try both.
Eli Friedman29c06092019-02-08 00:23:35 +000010036 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010037 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10038 if (!RHS.getNode())
10039 return SDValue();
10040
10041 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
Eli Friedman29c06092019-02-08 00:23:35 +000010042 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010043 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10044 if (!LHS.getNode())
10045 return SDValue();
10046
10047 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10048 }
10049
10050 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10051}
10052
10053// Massage DAGs which we can use the high-half "long" operations on into
10054// something isel will recognize better. E.g.
10055//
10056// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10057// (aarch64_neon_umull (extract_high (v2i64 vec)))
10058// (extract_high (v2i64 (dup128 scalar)))))
10059//
Hal Finkelcd8664c2015-12-11 23:11:52 +000010060static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +000010061 TargetLowering::DAGCombinerInfo &DCI,
10062 SelectionDAG &DAG) {
10063 if (DCI.isBeforeLegalizeOps())
10064 return SDValue();
10065
Hal Finkelcd8664c2015-12-11 23:11:52 +000010066 SDValue LHS = N->getOperand(1);
10067 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +000010068 assert(LHS.getValueType().is64BitVector() &&
10069 RHS.getValueType().is64BitVector() &&
10070 "unexpected shape for long operation");
10071
10072 // Either node could be a DUP, but it's not worth doing both of them (you'd
10073 // just as well use the non-high version) so look for a corresponding extract
10074 // operation on the other "wing".
Eli Friedman29c06092019-02-08 00:23:35 +000010075 if (isEssentiallyExtractHighSubvector(LHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010076 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10077 if (!RHS.getNode())
10078 return SDValue();
Eli Friedman29c06092019-02-08 00:23:35 +000010079 } else if (isEssentiallyExtractHighSubvector(RHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010080 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10081 if (!LHS.getNode())
10082 return SDValue();
10083 }
10084
Hal Finkelcd8664c2015-12-11 23:11:52 +000010085 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10086 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +000010087}
10088
10089static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10090 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10091 unsigned ElemBits = ElemTy.getSizeInBits();
10092
10093 int64_t ShiftAmount;
10094 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10095 APInt SplatValue, SplatUndef;
10096 unsigned SplatBitSize;
10097 bool HasAnyUndefs;
10098 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10099 HasAnyUndefs, ElemBits) ||
10100 SplatBitSize != ElemBits)
10101 return SDValue();
10102
10103 ShiftAmount = SplatValue.getSExtValue();
10104 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10105 ShiftAmount = CVN->getSExtValue();
10106 } else
10107 return SDValue();
10108
10109 unsigned Opcode;
10110 bool IsRightShift;
10111 switch (IID) {
10112 default:
10113 llvm_unreachable("Unknown shift intrinsic");
10114 case Intrinsic::aarch64_neon_sqshl:
10115 Opcode = AArch64ISD::SQSHL_I;
10116 IsRightShift = false;
10117 break;
10118 case Intrinsic::aarch64_neon_uqshl:
10119 Opcode = AArch64ISD::UQSHL_I;
10120 IsRightShift = false;
10121 break;
10122 case Intrinsic::aarch64_neon_srshl:
10123 Opcode = AArch64ISD::SRSHR_I;
10124 IsRightShift = true;
10125 break;
10126 case Intrinsic::aarch64_neon_urshl:
10127 Opcode = AArch64ISD::URSHR_I;
10128 IsRightShift = true;
10129 break;
10130 case Intrinsic::aarch64_neon_sqshlu:
10131 Opcode = AArch64ISD::SQSHLU_I;
10132 IsRightShift = false;
10133 break;
10134 }
10135
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010136 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10137 SDLoc dl(N);
10138 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10139 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10140 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10141 SDLoc dl(N);
10142 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10143 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10144 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010145
10146 return SDValue();
10147}
10148
10149// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10150// the intrinsics must be legal and take an i32, this means there's almost
10151// certainly going to be a zext in the DAG which we can eliminate.
10152static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10153 SDValue AndN = N->getOperand(2);
10154 if (AndN.getOpcode() != ISD::AND)
10155 return SDValue();
10156
10157 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10158 if (!CMask || CMask->getZExtValue() != Mask)
10159 return SDValue();
10160
10161 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10162 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10163}
10164
Ahmed Bougachafab58922015-03-10 20:45:38 +000010165static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10166 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010167 SDLoc dl(N);
10168 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10169 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +000010170 N->getOperand(1).getSimpleValueType(),
10171 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010172 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +000010173}
10174
Tim Northover3b0846e2014-05-24 12:50:23 +000010175static SDValue performIntrinsicCombine(SDNode *N,
10176 TargetLowering::DAGCombinerInfo &DCI,
10177 const AArch64Subtarget *Subtarget) {
10178 SelectionDAG &DAG = DCI.DAG;
10179 unsigned IID = getIntrinsicID(N);
10180 switch (IID) {
10181 default:
10182 break;
10183 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10184 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10185 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010186 case Intrinsic::aarch64_neon_saddv:
10187 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10188 case Intrinsic::aarch64_neon_uaddv:
10189 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10190 case Intrinsic::aarch64_neon_sminv:
10191 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10192 case Intrinsic::aarch64_neon_uminv:
10193 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10194 case Intrinsic::aarch64_neon_smaxv:
10195 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10196 case Intrinsic::aarch64_neon_umaxv:
10197 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010198 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010199 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010200 N->getOperand(1), N->getOperand(2));
10201 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010202 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010203 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010204 case Intrinsic::aarch64_neon_fmaxnm:
10205 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10206 N->getOperand(1), N->getOperand(2));
10207 case Intrinsic::aarch64_neon_fminnm:
10208 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10209 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010210 case Intrinsic::aarch64_neon_smull:
10211 case Intrinsic::aarch64_neon_umull:
10212 case Intrinsic::aarch64_neon_pmull:
10213 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010214 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010215 case Intrinsic::aarch64_neon_sqshl:
10216 case Intrinsic::aarch64_neon_uqshl:
10217 case Intrinsic::aarch64_neon_sqshlu:
10218 case Intrinsic::aarch64_neon_srshl:
10219 case Intrinsic::aarch64_neon_urshl:
10220 return tryCombineShiftImm(IID, N, DAG);
10221 case Intrinsic::aarch64_crc32b:
10222 case Intrinsic::aarch64_crc32cb:
10223 return tryCombineCRC32(0xff, N, DAG);
10224 case Intrinsic::aarch64_crc32h:
10225 case Intrinsic::aarch64_crc32ch:
10226 return tryCombineCRC32(0xffff, N, DAG);
10227 }
10228 return SDValue();
10229}
10230
10231static SDValue performExtendCombine(SDNode *N,
10232 TargetLowering::DAGCombinerInfo &DCI,
10233 SelectionDAG &DAG) {
10234 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10235 // we can convert that DUP into another extract_high (of a bigger DUP), which
10236 // helps the backend to decide that an sabdl2 would be useful, saving a real
10237 // extract_high operation.
10238 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010239 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010240 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010241 unsigned IID = getIntrinsicID(ABDNode);
10242 if (IID == Intrinsic::aarch64_neon_sabd ||
10243 IID == Intrinsic::aarch64_neon_uabd) {
10244 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10245 if (!NewABD.getNode())
10246 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010247
Hal Finkelcd8664c2015-12-11 23:11:52 +000010248 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10249 NewABD);
10250 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010251 }
10252
10253 // This is effectively a custom type legalization for AArch64.
10254 //
10255 // Type legalization will split an extend of a small, legal, type to a larger
10256 // illegal type by first splitting the destination type, often creating
10257 // illegal source types, which then get legalized in isel-confusing ways,
10258 // leading to really terrible codegen. E.g.,
10259 // %result = v8i32 sext v8i8 %value
10260 // becomes
10261 // %losrc = extract_subreg %value, ...
10262 // %hisrc = extract_subreg %value, ...
10263 // %lo = v4i32 sext v4i8 %losrc
10264 // %hi = v4i32 sext v4i8 %hisrc
10265 // Things go rapidly downhill from there.
10266 //
10267 // For AArch64, the [sz]ext vector instructions can only go up one element
10268 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10269 // take two instructions.
10270 //
10271 // This implies that the most efficient way to do the extend from v8i8
10272 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10273 // the normal splitting to happen for the v8i16->v8i32.
10274
10275 // This is pre-legalization to catch some cases where the default
10276 // type legalization will create ill-tempered code.
10277 if (!DCI.isBeforeLegalizeOps())
10278 return SDValue();
10279
10280 // We're only interested in cleaning things up for non-legal vector types
10281 // here. If both the source and destination are legal, things will just
10282 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010283 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010284 EVT ResVT = N->getValueType(0);
10285 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10286 return SDValue();
10287 // If the vector type isn't a simple VT, it's beyond the scope of what
10288 // we're worried about here. Let legalization do its thing and hope for
10289 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010290 SDValue Src = N->getOperand(0);
10291 EVT SrcVT = Src->getValueType(0);
10292 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010293 return SDValue();
10294
Tim Northover3b0846e2014-05-24 12:50:23 +000010295 // If the source VT is a 64-bit vector, we can play games and get the
10296 // better results we want.
10297 if (SrcVT.getSizeInBits() != 64)
10298 return SDValue();
10299
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010300 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010301 unsigned ElementCount = SrcVT.getVectorNumElements();
10302 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10303 SDLoc DL(N);
10304 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10305
10306 // Now split the rest of the operation into two halves, each with a 64
10307 // bit source.
10308 EVT LoVT, HiVT;
10309 SDValue Lo, Hi;
10310 unsigned NumElements = ResVT.getVectorNumElements();
10311 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10312 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10313 ResVT.getVectorElementType(), NumElements / 2);
10314
10315 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10316 LoVT.getVectorNumElements());
10317 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010318 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010319 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010320 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010321 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10322 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10323
10324 // Now combine the parts back together so we still have a single result
10325 // like the combiner expects.
10326 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10327}
10328
Geoff Berry8301c642016-11-16 19:35:19 +000010329static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10330 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010331 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010332 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010333 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010334
10335 // Create scalar stores. This is at least as good as the code sequence for a
10336 // split unaligned store which is a dup.s, ext.b, and two stores.
10337 // Most of the time the three stores should be replaced by store pair
10338 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010339 SDLoc DL(&St);
10340 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010341 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010342
John Brawn3a9c8422017-02-06 18:07:20 +000010343 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010344 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010345 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010346 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010347
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010348 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010349 if (BasePtr->getOpcode() == ISD::ADD &&
10350 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10351 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10352 BasePtr = BasePtr->getOperand(0);
10353 }
10354
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010355 unsigned Offset = EltOffset;
10356 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010357 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010358 SDValue OffsetPtr =
10359 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10360 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010361 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010362 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010363 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010364 Offset += EltOffset;
10365 }
10366 return NewST1;
10367}
10368
Geoff Berry526c5052016-11-14 19:39:04 +000010369/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10370/// load store optimizer pass will merge them to store pair stores. This should
10371/// be better than a movi to create the vector zero followed by a vector store
10372/// if the zero constant is not re-used, since one instructions and one register
10373/// live range will be removed.
10374///
10375/// For example, the final generated code should be:
10376///
10377/// stp xzr, xzr, [x0]
10378///
10379/// instead of:
10380///
10381/// movi v0.2d, #0
10382/// str q0, [x0]
10383///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010384static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10385 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010386 EVT VT = StVal.getValueType();
10387
Geoff Berry8301c642016-11-16 19:35:19 +000010388 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10389 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010390 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010391 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10392 VT.getVectorElementType().getSizeInBits() == 64) ||
10393 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10394 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010395 return SDValue();
10396
10397 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10398 return SDValue();
10399
10400 // If the zero constant has more than one use then the vector store could be
10401 // better since the constant mov will be amortized and stp q instructions
10402 // should be able to be formed.
10403 if (!StVal.hasOneUse())
10404 return SDValue();
10405
Tim Northover964eea72019-01-08 13:30:27 +000010406 // If the store is truncating then it's going down to i16 or smaller, which
10407 // means it can be implemented in a single store anyway.
10408 if (St.isTruncatingStore())
10409 return SDValue();
10410
Geoff Berry526c5052016-11-14 19:39:04 +000010411 // If the immediate offset of the address operand is too large for the stp
10412 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010413 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10414 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010415 if (Offset < -512 || Offset > 504)
10416 return SDValue();
10417 }
10418
10419 for (int I = 0; I < NumVecElts; ++I) {
10420 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010421 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010422 return SDValue();
10423 }
Geoff Berry8301c642016-11-16 19:35:19 +000010424
Geoff Berrybb23df92017-09-21 21:10:06 +000010425 // Use a CopyFromReg WZR/XZR here to prevent
10426 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10427 SDLoc DL(&St);
10428 unsigned ZeroReg;
10429 EVT ZeroVT;
10430 if (VT.getVectorElementType().getSizeInBits() == 32) {
10431 ZeroReg = AArch64::WZR;
10432 ZeroVT = MVT::i32;
10433 } else {
10434 ZeroReg = AArch64::XZR;
10435 ZeroVT = MVT::i64;
10436 }
10437 SDValue SplatVal =
10438 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010439 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010440}
10441
Tim Northover3b0846e2014-05-24 12:50:23 +000010442/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10443/// value. The load store optimizer pass will merge them to store pair stores.
10444/// This has better performance than a splat of the scalar followed by a split
10445/// vector store. Even if the stores are not merged it is four stores vs a dup,
10446/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010447static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10448 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010449 EVT VT = StVal.getValueType();
10450
10451 // Don't replace floating point stores, they possibly won't be transformed to
10452 // stp because of the store pair suppress pass.
10453 if (VT.isFloatingPoint())
10454 return SDValue();
10455
Tim Northover3b0846e2014-05-24 12:50:23 +000010456 // We can express a splat as store pair(s) for 2 or 4 elements.
10457 unsigned NumVecElts = VT.getVectorNumElements();
10458 if (NumVecElts != 4 && NumVecElts != 2)
10459 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010460
Tim Northover964eea72019-01-08 13:30:27 +000010461 // If the store is truncating then it's going down to i16 or smaller, which
10462 // means it can be implemented in a single store anyway.
10463 if (St.isTruncatingStore())
10464 return SDValue();
10465
Tim Northover3b0846e2014-05-24 12:50:23 +000010466 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010467 // Make sure that each of the relevant vector element locations are inserted
10468 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10469 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10470 SDValue SplatVal;
10471 for (unsigned I = 0; I < NumVecElts; ++I) {
10472 // Check for insert vector elements.
10473 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010474 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010475
10476 // Check that same value is inserted at each vector element.
10477 if (I == 0)
10478 SplatVal = StVal.getOperand(1);
10479 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010480 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010481
10482 // Check insert element index.
10483 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10484 if (!CIndex)
10485 return SDValue();
10486 uint64_t IndexVal = CIndex->getZExtValue();
10487 if (IndexVal >= NumVecElts)
10488 return SDValue();
10489 IndexNotInserted.reset(IndexVal);
10490
10491 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010492 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010493 // Check that all vector element locations were inserted to.
10494 if (IndexNotInserted.any())
10495 return SDValue();
10496
Geoff Berry8301c642016-11-16 19:35:19 +000010497 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010498}
10499
Geoff Berry8301c642016-11-16 19:35:19 +000010500static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10501 SelectionDAG &DAG,
10502 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010503
10504 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010505 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010506 return SDValue();
10507
Geoff Berry526c5052016-11-14 19:39:04 +000010508 SDValue StVal = S->getValue();
10509 EVT VT = StVal.getValueType();
10510 if (!VT.isVector())
10511 return SDValue();
10512
10513 // If we get a splat of zeros, convert this vector store to a store of
10514 // scalars. They will be merged into store pairs of xzr thereby removing one
10515 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010516 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010517 return ReplacedZeroSplat;
10518
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010519 // FIXME: The logic for deciding if an unaligned store should be split should
10520 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10521 // a call to that function here.
10522
Matthias Braun651cff42016-06-02 18:03:53 +000010523 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010524 return SDValue();
10525
Sanjay Patel924879a2015-08-04 15:49:57 +000010526 // Don't split at -Oz.
Evandro Menezes85bd3972019-04-04 22:40:06 +000010527 if (DAG.getMachineFunction().getFunction().hasMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010528 return SDValue();
10529
Tim Northover3b0846e2014-05-24 12:50:23 +000010530 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10531 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010532 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010533 return SDValue();
10534
10535 // Split unaligned 16B stores. They are terrible for performance.
10536 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10537 // extensions can use this to mark that it does not want splitting to happen
10538 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10539 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10540 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10541 S->getAlignment() <= 2)
10542 return SDValue();
10543
10544 // If we get a splat of a scalar convert this vector store to a store of
10545 // scalars. They will be merged into store pairs thereby removing two
10546 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010547 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010548 return ReplacedSplat;
10549
10550 SDLoc DL(S);
10551 unsigned NumElts = VT.getVectorNumElements() / 2;
10552 // Split VT into two.
10553 EVT HalfVT =
10554 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10555 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010556 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010557 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010558 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010559 SDValue BasePtr = S->getBasePtr();
10560 SDValue NewST1 =
10561 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010562 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010563 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010564 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010565 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010566 S->getPointerInfo(), S->getAlignment(),
10567 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010568}
10569
10570/// Target-specific DAG combine function for post-increment LD1 (lane) and
10571/// post-increment LD1R.
10572static SDValue performPostLD1Combine(SDNode *N,
10573 TargetLowering::DAGCombinerInfo &DCI,
10574 bool IsLaneOp) {
10575 if (DCI.isBeforeLegalizeOps())
10576 return SDValue();
10577
10578 SelectionDAG &DAG = DCI.DAG;
10579 EVT VT = N->getValueType(0);
10580
10581 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10582 SDNode *LD = N->getOperand(LoadIdx).getNode();
10583 // If it is not LOAD, can not do such combine.
10584 if (LD->getOpcode() != ISD::LOAD)
10585 return SDValue();
10586
Geoff Berry60460262018-05-11 16:25:06 +000010587 // The vector lane must be a constant in the LD1LANE opcode.
10588 SDValue Lane;
10589 if (IsLaneOp) {
10590 Lane = N->getOperand(2);
10591 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10592 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10593 return SDValue();
10594 }
10595
Tim Northover3b0846e2014-05-24 12:50:23 +000010596 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10597 EVT MemVT = LoadSDN->getMemoryVT();
10598 // Check if memory operand is the same type as the vector element.
10599 if (MemVT != VT.getVectorElementType())
10600 return SDValue();
10601
10602 // Check if there are other uses. If so, do not combine as it will introduce
10603 // an extra load.
10604 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10605 ++UI) {
10606 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10607 continue;
10608 if (*UI != N)
10609 return SDValue();
10610 }
10611
10612 SDValue Addr = LD->getOperand(1);
10613 SDValue Vector = N->getOperand(0);
10614 // Search for a use of the address operand that is an increment.
10615 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10616 Addr.getNode()->use_end(); UI != UE; ++UI) {
10617 SDNode *User = *UI;
10618 if (User->getOpcode() != ISD::ADD
10619 || UI.getUse().getResNo() != Addr.getResNo())
10620 continue;
10621
Tim Northover3b0846e2014-05-24 12:50:23 +000010622 // If the increment is a constant, it must match the memory ref size.
10623 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10624 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10625 uint32_t IncVal = CInc->getZExtValue();
10626 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10627 if (IncVal != NumBytes)
10628 continue;
10629 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10630 }
10631
Nirav Davee40e2bb2018-09-25 15:30:22 +000010632 // To avoid cycle construction make sure that neither the load nor the add
10633 // are predecessors to each other or the Vector.
10634 SmallPtrSet<const SDNode *, 32> Visited;
10635 SmallVector<const SDNode *, 16> Worklist;
10636 Visited.insert(N);
10637 Worklist.push_back(User);
10638 Worklist.push_back(LD);
10639 Worklist.push_back(Vector.getNode());
10640 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10641 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010642 continue;
10643
Tim Northover3b0846e2014-05-24 12:50:23 +000010644 SmallVector<SDValue, 8> Ops;
10645 Ops.push_back(LD->getOperand(0)); // Chain
10646 if (IsLaneOp) {
10647 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010648 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010649 }
10650 Ops.push_back(Addr);
10651 Ops.push_back(Inc);
10652
10653 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010654 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010655 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10656 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10657 MemVT,
10658 LoadSDN->getMemOperand());
10659
10660 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010661 SDValue NewResults[] = {
10662 SDValue(LD, 0), // The result of load
10663 SDValue(UpdN.getNode(), 2) // Chain
10664 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010665 DCI.CombineTo(LD, NewResults);
10666 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10667 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10668
10669 break;
10670 }
10671 return SDValue();
10672}
10673
Joel Jones7466ccf2017-07-10 22:11:50 +000010674/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010675/// address translation.
10676static bool performTBISimplification(SDValue Addr,
10677 TargetLowering::DAGCombinerInfo &DCI,
10678 SelectionDAG &DAG) {
10679 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010680 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010681 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10682 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010684 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010685 DCI.CommitTargetLoweringOpt(TLO);
10686 return true;
10687 }
10688 return false;
10689}
10690
10691static SDValue performSTORECombine(SDNode *N,
10692 TargetLowering::DAGCombinerInfo &DCI,
10693 SelectionDAG &DAG,
10694 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010695 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010696 return Split;
10697
10698 if (Subtarget->supportsAddressTopByteIgnored() &&
10699 performTBISimplification(N->getOperand(2), DCI, DAG))
10700 return SDValue(N, 0);
10701
10702 return SDValue();
10703}
10704
Chad Rosier6c36eff2015-09-03 18:13:57 +000010705
Tim Northover3b0846e2014-05-24 12:50:23 +000010706/// Target-specific DAG combine function for NEON load/store intrinsics
10707/// to merge base address updates.
10708static SDValue performNEONPostLDSTCombine(SDNode *N,
10709 TargetLowering::DAGCombinerInfo &DCI,
10710 SelectionDAG &DAG) {
10711 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10712 return SDValue();
10713
10714 unsigned AddrOpIdx = N->getNumOperands() - 1;
10715 SDValue Addr = N->getOperand(AddrOpIdx);
10716
10717 // Search for a use of the address operand that is an increment.
10718 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10719 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10720 SDNode *User = *UI;
10721 if (User->getOpcode() != ISD::ADD ||
10722 UI.getUse().getResNo() != Addr.getResNo())
10723 continue;
10724
10725 // Check that the add is independent of the load/store. Otherwise, folding
10726 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010727 SmallPtrSet<const SDNode *, 32> Visited;
10728 SmallVector<const SDNode *, 16> Worklist;
10729 Visited.insert(Addr.getNode());
10730 Worklist.push_back(N);
10731 Worklist.push_back(User);
10732 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10733 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010734 continue;
10735
10736 // Find the new opcode for the updating load/store.
10737 bool IsStore = false;
10738 bool IsLaneOp = false;
10739 bool IsDupOp = false;
10740 unsigned NewOpc = 0;
10741 unsigned NumVecs = 0;
10742 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10743 switch (IntNo) {
10744 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10745 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10746 NumVecs = 2; break;
10747 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10748 NumVecs = 3; break;
10749 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10750 NumVecs = 4; break;
10751 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10752 NumVecs = 2; IsStore = true; break;
10753 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10754 NumVecs = 3; IsStore = true; break;
10755 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10756 NumVecs = 4; IsStore = true; break;
10757 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10758 NumVecs = 2; break;
10759 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10760 NumVecs = 3; break;
10761 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10762 NumVecs = 4; break;
10763 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10764 NumVecs = 2; IsStore = true; break;
10765 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10766 NumVecs = 3; IsStore = true; break;
10767 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10768 NumVecs = 4; IsStore = true; break;
10769 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10770 NumVecs = 2; IsDupOp = true; break;
10771 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10772 NumVecs = 3; IsDupOp = true; break;
10773 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10774 NumVecs = 4; IsDupOp = true; break;
10775 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10776 NumVecs = 2; IsLaneOp = true; break;
10777 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10778 NumVecs = 3; IsLaneOp = true; break;
10779 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10780 NumVecs = 4; IsLaneOp = true; break;
10781 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10782 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10783 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10784 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10785 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10786 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10787 }
10788
10789 EVT VecTy;
10790 if (IsStore)
10791 VecTy = N->getOperand(2).getValueType();
10792 else
10793 VecTy = N->getValueType(0);
10794
10795 // If the increment is a constant, it must match the memory ref size.
10796 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10797 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10798 uint32_t IncVal = CInc->getZExtValue();
10799 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10800 if (IsLaneOp || IsDupOp)
10801 NumBytes /= VecTy.getVectorNumElements();
10802 if (IncVal != NumBytes)
10803 continue;
10804 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10805 }
10806 SmallVector<SDValue, 8> Ops;
10807 Ops.push_back(N->getOperand(0)); // Incoming chain
10808 // Load lane and store have vector list as input.
10809 if (IsLaneOp || IsStore)
10810 for (unsigned i = 2; i < AddrOpIdx; ++i)
10811 Ops.push_back(N->getOperand(i));
10812 Ops.push_back(Addr); // Base register
10813 Ops.push_back(Inc);
10814
10815 // Return Types.
10816 EVT Tys[6];
10817 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10818 unsigned n;
10819 for (n = 0; n < NumResultVecs; ++n)
10820 Tys[n] = VecTy;
10821 Tys[n++] = MVT::i64; // Type of write back register
10822 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010823 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010824
10825 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10826 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10827 MemInt->getMemoryVT(),
10828 MemInt->getMemOperand());
10829
10830 // Update the uses.
10831 std::vector<SDValue> NewResults;
10832 for (unsigned i = 0; i < NumResultVecs; ++i) {
10833 NewResults.push_back(SDValue(UpdN.getNode(), i));
10834 }
10835 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10836 DCI.CombineTo(N, NewResults);
10837 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10838
10839 break;
10840 }
10841 return SDValue();
10842}
10843
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010844// Checks to see if the value is the prescribed width and returns information
10845// about its extension mode.
10846static
10847bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10848 ExtType = ISD::NON_EXTLOAD;
10849 switch(V.getNode()->getOpcode()) {
10850 default:
10851 return false;
10852 case ISD::LOAD: {
10853 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10854 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10855 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10856 ExtType = LoadNode->getExtensionType();
10857 return true;
10858 }
10859 return false;
10860 }
10861 case ISD::AssertSext: {
10862 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10863 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10864 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10865 ExtType = ISD::SEXTLOAD;
10866 return true;
10867 }
10868 return false;
10869 }
10870 case ISD::AssertZext: {
10871 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10872 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10873 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10874 ExtType = ISD::ZEXTLOAD;
10875 return true;
10876 }
10877 return false;
10878 }
10879 case ISD::Constant:
10880 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010881 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10882 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010883 }
10884 }
10885
10886 return true;
10887}
10888
10889// This function does a whole lot of voodoo to determine if the tests are
10890// equivalent without and with a mask. Essentially what happens is that given a
10891// DAG resembling:
10892//
10893// +-------------+ +-------------+ +-------------+ +-------------+
10894// | Input | | AddConstant | | CompConstant| | CC |
10895// +-------------+ +-------------+ +-------------+ +-------------+
10896// | | | |
10897// V V | +----------+
10898// +-------------+ +----+ | |
10899// | ADD | |0xff| | |
10900// +-------------+ +----+ | |
10901// | | | |
10902// V V | |
10903// +-------------+ | |
10904// | AND | | |
10905// +-------------+ | |
10906// | | |
10907// +-----+ | |
10908// | | |
10909// V V V
10910// +-------------+
10911// | CMP |
10912// +-------------+
10913//
10914// The AND node may be safely removed for some combinations of inputs. In
10915// particular we need to take into account the extension type of the Input,
10916// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10917// width of the input (this can work for any width inputs, the above graph is
10918// specific to 8 bits.
10919//
10920// The specific equations were worked out by generating output tables for each
10921// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10922// problem was simplified by working with 4 bit inputs, which means we only
10923// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10924// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10925// patterns present in both extensions (0,7). For every distinct set of
10926// AddConstant and CompConstants bit patterns we can consider the masked and
10927// unmasked versions to be equivalent if the result of this function is true for
10928// all 16 distinct bit patterns of for the current extension type of Input (w0).
10929//
10930// sub w8, w0, w1
10931// and w10, w8, #0x0f
10932// cmp w8, w2
10933// cset w9, AArch64CC
10934// cmp w10, w2
10935// cset w11, AArch64CC
10936// cmp w9, w11
10937// cset w0, eq
10938// ret
10939//
10940// Since the above function shows when the outputs are equivalent it defines
10941// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10942// would be expensive to run during compiles. The equations below were written
10943// in a test harness that confirmed they gave equivalent outputs to the above
10944// for all inputs function, so they can be used determine if the removal is
10945// legal instead.
10946//
10947// isEquivalentMaskless() is the code for testing if the AND can be removed
10948// factored out of the DAG recognition as the DAG can take several forms.
10949
David Majnemere61e4bf2016-06-21 05:10:24 +000010950static bool isEquivalentMaskless(unsigned CC, unsigned width,
10951 ISD::LoadExtType ExtType, int AddConstant,
10952 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010953 // By being careful about our equations and only writing the in term
10954 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10955 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010956 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010957
10958 // For the purposes of these comparisons sign extending the type is
10959 // equivalent to zero extending the add and displacing it by half the integer
10960 // width. Provided we are careful and make sure our equations are valid over
10961 // the whole range we can just adjust the input and avoid writing equations
10962 // for sign extended inputs.
10963 if (ExtType == ISD::SEXTLOAD)
10964 AddConstant -= (1 << (width-1));
10965
10966 switch(CC) {
10967 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010968 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010969 if ((AddConstant == 0) ||
10970 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10971 (AddConstant >= 0 && CompConstant < 0) ||
10972 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10973 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010974 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010975 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010976 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010977 if ((AddConstant == 0) ||
10978 (AddConstant >= 0 && CompConstant <= 0) ||
10979 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10980 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010981 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010982 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010983 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010984 if ((AddConstant >= 0 && CompConstant < 0) ||
10985 (AddConstant <= 0 && CompConstant >= -1 &&
10986 CompConstant < AddConstant + MaxUInt))
10987 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010988 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010989 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010990 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010991 if ((AddConstant == 0) ||
10992 (AddConstant > 0 && CompConstant <= 0) ||
10993 (AddConstant < 0 && CompConstant <= AddConstant))
10994 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010995 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010996 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010997 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010998 if ((AddConstant >= 0 && CompConstant <= 0) ||
10999 (AddConstant <= 0 && CompConstant >= 0 &&
11000 CompConstant <= AddConstant + MaxUInt))
11001 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011002 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011003 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011004 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011005 if ((AddConstant > 0 && CompConstant < 0) ||
11006 (AddConstant < 0 && CompConstant >= 0 &&
11007 CompConstant < AddConstant + MaxUInt) ||
11008 (AddConstant >= 0 && CompConstant >= 0 &&
11009 CompConstant >= AddConstant) ||
11010 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011011 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011012 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011013 case AArch64CC::VS:
11014 case AArch64CC::VC:
11015 case AArch64CC::AL:
11016 case AArch64CC::NV:
11017 return true;
11018 case AArch64CC::Invalid:
11019 break;
11020 }
11021
11022 return false;
11023}
11024
11025static
11026SDValue performCONDCombine(SDNode *N,
11027 TargetLowering::DAGCombinerInfo &DCI,
11028 SelectionDAG &DAG, unsigned CCIndex,
11029 unsigned CmpIndex) {
11030 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11031 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11032 unsigned CondOpcode = SubsNode->getOpcode();
11033
11034 if (CondOpcode != AArch64ISD::SUBS)
11035 return SDValue();
11036
11037 // There is a SUBS feeding this condition. Is it fed by a mask we can
11038 // use?
11039
11040 SDNode *AndNode = SubsNode->getOperand(0).getNode();
11041 unsigned MaskBits = 0;
11042
11043 if (AndNode->getOpcode() != ISD::AND)
11044 return SDValue();
11045
11046 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11047 uint32_t CNV = CN->getZExtValue();
11048 if (CNV == 255)
11049 MaskBits = 8;
11050 else if (CNV == 65535)
11051 MaskBits = 16;
11052 }
11053
11054 if (!MaskBits)
11055 return SDValue();
11056
11057 SDValue AddValue = AndNode->getOperand(0);
11058
11059 if (AddValue.getOpcode() != ISD::ADD)
11060 return SDValue();
11061
11062 // The basic dag structure is correct, grab the inputs and validate them.
11063
11064 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11065 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11066 SDValue SubsInputValue = SubsNode->getOperand(1);
11067
11068 // The mask is present and the provenance of all the values is a smaller type,
11069 // lets see if the mask is superfluous.
11070
11071 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11072 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11073 return SDValue();
11074
11075 ISD::LoadExtType ExtType;
11076
11077 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11078 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11079 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11080 return SDValue();
11081
11082 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11083 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11084 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11085 return SDValue();
11086
11087 // The AND is not necessary, remove it.
11088
11089 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11090 SubsNode->getValueType(1));
11091 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11092
11093 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11094 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11095
11096 return SDValue(N, 0);
11097}
11098
Tim Northover3b0846e2014-05-24 12:50:23 +000011099// Optimize compare with zero and branch.
11100static SDValue performBRCONDCombine(SDNode *N,
11101 TargetLowering::DAGCombinerInfo &DCI,
11102 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000011103 MachineFunction &MF = DAG.getMachineFunction();
11104 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11105 // will not be produced, as they are conditional branch instructions that do
11106 // not set flags.
11107 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11108 return SDValue();
11109
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000011110 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011111 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000011112 SDValue Chain = N->getOperand(0);
11113 SDValue Dest = N->getOperand(1);
11114 SDValue CCVal = N->getOperand(2);
11115 SDValue Cmp = N->getOperand(3);
11116
11117 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11118 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11119 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11120 return SDValue();
11121
11122 unsigned CmpOpc = Cmp.getOpcode();
11123 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11124 return SDValue();
11125
11126 // Only attempt folding if there is only one use of the flag and no use of the
11127 // value.
11128 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11129 return SDValue();
11130
11131 SDValue LHS = Cmp.getOperand(0);
11132 SDValue RHS = Cmp.getOperand(1);
11133
11134 assert(LHS.getValueType() == RHS.getValueType() &&
11135 "Expected the value type to be the same for both operands!");
11136 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11137 return SDValue();
11138
Artyom Skrobov314ee042015-11-25 19:41:11 +000011139 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011140 std::swap(LHS, RHS);
11141
Artyom Skrobov314ee042015-11-25 19:41:11 +000011142 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011143 return SDValue();
11144
11145 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11146 LHS.getOpcode() == ISD::SRL)
11147 return SDValue();
11148
11149 // Fold the compare into the branch instruction.
11150 SDValue BR;
11151 if (CC == AArch64CC::EQ)
11152 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11153 else
11154 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11155
11156 // Do not add new nodes to DAG combiner worklist.
11157 DCI.CombineTo(N, BR, false);
11158
11159 return SDValue();
11160}
11161
Geoff Berry9e934b02016-01-04 18:55:47 +000011162// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11163// as well as whether the test should be inverted. This code is required to
11164// catch these cases (as opposed to standard dag combines) because
11165// AArch64ISD::TBZ is matched during legalization.
11166static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11167 SelectionDAG &DAG) {
11168
11169 if (!Op->hasOneUse())
11170 return Op;
11171
11172 // We don't handle undef/constant-fold cases below, as they should have
11173 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11174 // etc.)
11175
11176 // (tbz (trunc x), b) -> (tbz x, b)
11177 // This case is just here to enable more of the below cases to be caught.
11178 if (Op->getOpcode() == ISD::TRUNCATE &&
11179 Bit < Op->getValueType(0).getSizeInBits()) {
11180 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11181 }
11182
Craig Topper35fe0792019-04-10 17:27:29 +000011183 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11184 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11185 Bit < Op->getOperand(0).getValueSizeInBits()) {
11186 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11187 }
11188
Geoff Berry9e934b02016-01-04 18:55:47 +000011189 if (Op->getNumOperands() != 2)
11190 return Op;
11191
11192 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11193 if (!C)
11194 return Op;
11195
11196 switch (Op->getOpcode()) {
11197 default:
11198 return Op;
11199
11200 // (tbz (and x, m), b) -> (tbz x, b)
11201 case ISD::AND:
11202 if ((C->getZExtValue() >> Bit) & 1)
11203 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11204 return Op;
11205
11206 // (tbz (shl x, c), b) -> (tbz x, b-c)
11207 case ISD::SHL:
11208 if (C->getZExtValue() <= Bit &&
11209 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11210 Bit = Bit - C->getZExtValue();
11211 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11212 }
11213 return Op;
11214
11215 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11216 case ISD::SRA:
11217 Bit = Bit + C->getZExtValue();
11218 if (Bit >= Op->getValueType(0).getSizeInBits())
11219 Bit = Op->getValueType(0).getSizeInBits() - 1;
11220 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11221
11222 // (tbz (srl x, c), b) -> (tbz x, b+c)
11223 case ISD::SRL:
11224 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11225 Bit = Bit + C->getZExtValue();
11226 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11227 }
11228 return Op;
11229
11230 // (tbz (xor x, -1), b) -> (tbnz x, b)
11231 case ISD::XOR:
11232 if ((C->getZExtValue() >> Bit) & 1)
11233 Invert = !Invert;
11234 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11235 }
11236}
11237
11238// Optimize test single bit zero/non-zero and branch.
11239static SDValue performTBZCombine(SDNode *N,
11240 TargetLowering::DAGCombinerInfo &DCI,
11241 SelectionDAG &DAG) {
11242 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11243 bool Invert = false;
11244 SDValue TestSrc = N->getOperand(1);
11245 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11246
11247 if (TestSrc == NewTestSrc)
11248 return SDValue();
11249
11250 unsigned NewOpc = N->getOpcode();
11251 if (Invert) {
11252 if (NewOpc == AArch64ISD::TBZ)
11253 NewOpc = AArch64ISD::TBNZ;
11254 else {
11255 assert(NewOpc == AArch64ISD::TBNZ);
11256 NewOpc = AArch64ISD::TBZ;
11257 }
11258 }
11259
11260 SDLoc DL(N);
11261 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11262 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11263}
11264
Tim Northover3b0846e2014-05-24 12:50:23 +000011265// vselect (v1i1 setcc) ->
11266// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11267// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11268// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11269// such VSELECT.
11270static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11271 SDValue N0 = N->getOperand(0);
11272 EVT CCVT = N0.getValueType();
11273
11274 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11275 CCVT.getVectorElementType() != MVT::i1)
11276 return SDValue();
11277
11278 EVT ResVT = N->getValueType(0);
11279 EVT CmpVT = N0.getOperand(0).getValueType();
11280 // Only combine when the result type is of the same size as the compared
11281 // operands.
11282 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11283 return SDValue();
11284
11285 SDValue IfTrue = N->getOperand(1);
11286 SDValue IfFalse = N->getOperand(2);
11287 SDValue SetCC =
11288 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11289 N0.getOperand(0), N0.getOperand(1),
11290 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11291 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11292 IfTrue, IfFalse);
11293}
11294
11295/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11296/// the compare-mask instructions rather than going via NZCV, even if LHS and
11297/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11298/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011299static SDValue performSelectCombine(SDNode *N,
11300 TargetLowering::DAGCombinerInfo &DCI) {
11301 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011302 SDValue N0 = N->getOperand(0);
11303 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011304
Ahmed Bougachac004c602015-04-27 21:43:12 +000011305 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011306 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011307
Ahmed Bougachac004c602015-04-27 21:43:12 +000011308 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11309 // scalar SetCCResultType. We also don't expect vectors, because we assume
11310 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11311 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11312 "Scalar-SETCC feeding SELECT has unexpected result type!");
11313
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011314 // If NumMaskElts == 0, the comparison is larger than select result. The
11315 // largest real NEON comparison is 64-bits per lane, which means the result is
11316 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011317 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011318
11319 // Don't try to do this optimization when the setcc itself has i1 operands.
11320 // There are no legal vectors of i1, so this would be pointless.
11321 if (SrcVT == MVT::i1)
11322 return SDValue();
11323
Tim Northover3c0915e2014-08-29 15:34:58 +000011324 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011325 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011326 return SDValue();
11327
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011328 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011329 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11330
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011331 // Also bail out if the vector CCVT isn't the same size as ResVT.
11332 // This can happen if the SETCC operand size doesn't divide the ResVT size
11333 // (e.g., f64 vs v3f32).
11334 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11335 return SDValue();
11336
Ahmed Bougachac004c602015-04-27 21:43:12 +000011337 // Make sure we didn't create illegal types, if we're not supposed to.
11338 assert(DCI.isBeforeLegalize() ||
11339 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11340
Tim Northover3b0846e2014-05-24 12:50:23 +000011341 // First perform a vector comparison, where lane 0 is the one we're interested
11342 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011343 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011344 SDValue LHS =
11345 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11346 SDValue RHS =
11347 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11348 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11349
11350 // Now duplicate the comparison mask we want across all other lanes.
11351 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011352 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011353 Mask = DAG.getNode(ISD::BITCAST, DL,
11354 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011355
11356 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11357}
11358
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011359/// Get rid of unnecessary NVCASTs (that don't change the type).
11360static SDValue performNVCASTCombine(SDNode *N) {
11361 if (N->getValueType(0) == N->getOperand(0).getValueType())
11362 return N->getOperand(0);
11363
11364 return SDValue();
11365}
11366
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011367// If all users of the globaladdr are of the form (globaladdr + constant), find
11368// the smallest constant, fold it into the globaladdr's offset and rewrite the
11369// globaladdr as (globaladdr + constant) - constant.
11370static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11371 const AArch64Subtarget *Subtarget,
11372 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011373 auto *GN = cast<GlobalAddressSDNode>(N);
11374 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11375 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011376 return SDValue();
11377
11378 uint64_t MinOffset = -1ull;
11379 for (SDNode *N : GN->uses()) {
11380 if (N->getOpcode() != ISD::ADD)
11381 return SDValue();
11382 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11383 if (!C)
11384 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11385 if (!C)
11386 return SDValue();
11387 MinOffset = std::min(MinOffset, C->getZExtValue());
11388 }
11389 uint64_t Offset = MinOffset + GN->getOffset();
11390
11391 // Require that the new offset is larger than the existing one. Otherwise, we
11392 // can end up oscillating between two possible DAGs, for example,
11393 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11394 if (Offset <= uint64_t(GN->getOffset()))
11395 return SDValue();
11396
11397 // Check whether folding this offset is legal. It must not go out of bounds of
11398 // the referenced object to avoid violating the code model, and must be
11399 // smaller than 2^21 because this is the largest offset expressible in all
11400 // object formats.
11401 //
11402 // This check also prevents us from folding negative offsets, which will end
11403 // up being treated in the same way as large positive ones. They could also
11404 // cause code model violations, and aren't really common enough to matter.
11405 if (Offset >= (1 << 21))
11406 return SDValue();
11407
11408 const GlobalValue *GV = GN->getGlobal();
11409 Type *T = GV->getValueType();
11410 if (!T->isSized() ||
11411 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11412 return SDValue();
11413
11414 SDLoc DL(GN);
11415 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11416 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11417 DAG.getConstant(MinOffset, DL, MVT::i64));
11418}
11419
Tim Northover3b0846e2014-05-24 12:50:23 +000011420SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11421 DAGCombinerInfo &DCI) const {
11422 SelectionDAG &DAG = DCI.DAG;
11423 switch (N->getOpcode()) {
11424 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011425 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011426 break;
11427 case ISD::ADD:
11428 case ISD::SUB:
11429 return performAddSubLongCombine(N, DCI, DAG);
11430 case ISD::XOR:
11431 return performXorCombine(N, DAG, DCI, Subtarget);
11432 case ISD::MUL:
11433 return performMulCombine(N, DAG, DCI, Subtarget);
11434 case ISD::SINT_TO_FP:
11435 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011436 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011437 case ISD::FP_TO_SINT:
11438 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011439 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011440 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011441 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011442 case ISD::OR:
11443 return performORCombine(N, DCI, Subtarget);
Nikita Popov1a261442019-03-15 21:04:34 +000011444 case ISD::AND:
11445 return performANDCombine(N, DCI);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011446 case ISD::SRL:
11447 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011448 case ISD::INTRINSIC_WO_CHAIN:
11449 return performIntrinsicCombine(N, DCI, Subtarget);
11450 case ISD::ANY_EXTEND:
11451 case ISD::ZERO_EXTEND:
11452 case ISD::SIGN_EXTEND:
11453 return performExtendCombine(N, DCI, DAG);
11454 case ISD::BITCAST:
11455 return performBitcastCombine(N, DCI, DAG);
11456 case ISD::CONCAT_VECTORS:
11457 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011458 case ISD::SELECT:
11459 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011460 case ISD::VSELECT:
11461 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011462 case ISD::LOAD:
11463 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11464 return SDValue(N, 0);
11465 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011466 case ISD::STORE:
11467 return performSTORECombine(N, DCI, DAG, Subtarget);
11468 case AArch64ISD::BRCOND:
11469 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011470 case AArch64ISD::TBNZ:
11471 case AArch64ISD::TBZ:
11472 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011473 case AArch64ISD::CSEL:
11474 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011475 case AArch64ISD::DUP:
11476 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011477 case AArch64ISD::NVCAST:
11478 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011479 case ISD::INSERT_VECTOR_ELT:
11480 return performPostLD1Combine(N, DCI, true);
11481 case ISD::INTRINSIC_VOID:
11482 case ISD::INTRINSIC_W_CHAIN:
11483 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11484 case Intrinsic::aarch64_neon_ld2:
11485 case Intrinsic::aarch64_neon_ld3:
11486 case Intrinsic::aarch64_neon_ld4:
11487 case Intrinsic::aarch64_neon_ld1x2:
11488 case Intrinsic::aarch64_neon_ld1x3:
11489 case Intrinsic::aarch64_neon_ld1x4:
11490 case Intrinsic::aarch64_neon_ld2lane:
11491 case Intrinsic::aarch64_neon_ld3lane:
11492 case Intrinsic::aarch64_neon_ld4lane:
11493 case Intrinsic::aarch64_neon_ld2r:
11494 case Intrinsic::aarch64_neon_ld3r:
11495 case Intrinsic::aarch64_neon_ld4r:
11496 case Intrinsic::aarch64_neon_st2:
11497 case Intrinsic::aarch64_neon_st3:
11498 case Intrinsic::aarch64_neon_st4:
11499 case Intrinsic::aarch64_neon_st1x2:
11500 case Intrinsic::aarch64_neon_st1x3:
11501 case Intrinsic::aarch64_neon_st1x4:
11502 case Intrinsic::aarch64_neon_st2lane:
11503 case Intrinsic::aarch64_neon_st3lane:
11504 case Intrinsic::aarch64_neon_st4lane:
11505 return performNEONPostLDSTCombine(N, DCI, DAG);
11506 default:
11507 break;
11508 }
Reid Klecknereb568942018-11-01 18:02:27 +000011509 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011510 case ISD::GlobalAddress:
11511 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011512 }
11513 return SDValue();
11514}
11515
11516// Check if the return value is used as only a return value, as otherwise
11517// we can't perform a tail-call. In particular, we need to check for
11518// target ISD nodes that are returns and any other "odd" constructs
11519// that the generic analysis code won't necessarily catch.
11520bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11521 SDValue &Chain) const {
11522 if (N->getNumValues() != 1)
11523 return false;
11524 if (!N->hasNUsesOfValue(1, 0))
11525 return false;
11526
11527 SDValue TCChain = Chain;
11528 SDNode *Copy = *N->use_begin();
11529 if (Copy->getOpcode() == ISD::CopyToReg) {
11530 // If the copy has a glue operand, we conservatively assume it isn't safe to
11531 // perform a tail call.
11532 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11533 MVT::Glue)
11534 return false;
11535 TCChain = Copy->getOperand(0);
11536 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11537 return false;
11538
11539 bool HasRet = false;
11540 for (SDNode *Node : Copy->uses()) {
11541 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11542 return false;
11543 HasRet = true;
11544 }
11545
11546 if (!HasRet)
11547 return false;
11548
11549 Chain = TCChain;
11550 return true;
11551}
11552
11553// Return whether the an instruction can potentially be optimized to a tail
11554// call. This will cause the optimizers to attempt to move, or duplicate,
11555// return instructions to help enable tail call optimizations for this
11556// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011557bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011558 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011559}
11560
11561bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11562 SDValue &Offset,
11563 ISD::MemIndexedMode &AM,
11564 bool &IsInc,
11565 SelectionDAG &DAG) const {
11566 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11567 return false;
11568
11569 Base = Op->getOperand(0);
11570 // All of the indexed addressing mode instructions take a signed
11571 // 9 bit immediate offset.
11572 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011573 int64_t RHSC = RHS->getSExtValue();
11574 if (Op->getOpcode() == ISD::SUB)
11575 RHSC = -(uint64_t)RHSC;
11576 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011577 return false;
11578 IsInc = (Op->getOpcode() == ISD::ADD);
11579 Offset = Op->getOperand(1);
11580 return true;
11581 }
11582 return false;
11583}
11584
11585bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11586 SDValue &Offset,
11587 ISD::MemIndexedMode &AM,
11588 SelectionDAG &DAG) const {
11589 EVT VT;
11590 SDValue Ptr;
11591 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11592 VT = LD->getMemoryVT();
11593 Ptr = LD->getBasePtr();
11594 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11595 VT = ST->getMemoryVT();
11596 Ptr = ST->getBasePtr();
11597 } else
11598 return false;
11599
11600 bool IsInc;
11601 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11602 return false;
11603 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11604 return true;
11605}
11606
11607bool AArch64TargetLowering::getPostIndexedAddressParts(
11608 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11609 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11610 EVT VT;
11611 SDValue Ptr;
11612 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11613 VT = LD->getMemoryVT();
11614 Ptr = LD->getBasePtr();
11615 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11616 VT = ST->getMemoryVT();
11617 Ptr = ST->getBasePtr();
11618 } else
11619 return false;
11620
11621 bool IsInc;
11622 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11623 return false;
11624 // Post-indexing updates the base, so it's not a valid transform
11625 // if that's not the same as the load's pointer.
11626 if (Ptr != Base)
11627 return false;
11628 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11629 return true;
11630}
11631
Tim Northoverf8bfe212014-07-18 13:07:05 +000011632static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11633 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011634 SDLoc DL(N);
11635 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011636
11637 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11638 return;
11639
Tim Northoverf8bfe212014-07-18 13:07:05 +000011640 Op = SDValue(
11641 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11642 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011643 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011644 0);
11645 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11646 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11647}
11648
Charlie Turner434d4592015-10-16 15:38:25 +000011649static void ReplaceReductionResults(SDNode *N,
11650 SmallVectorImpl<SDValue> &Results,
11651 SelectionDAG &DAG, unsigned InterOp,
11652 unsigned AcrossOp) {
11653 EVT LoVT, HiVT;
11654 SDValue Lo, Hi;
11655 SDLoc dl(N);
11656 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11657 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11658 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11659 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11660 Results.push_back(SplitVal);
11661}
11662
Tim Northover2f32e7f2016-08-04 19:32:28 +000011663static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11664 SDLoc DL(N);
11665 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11666 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11667 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11668 DAG.getConstant(64, DL, MVT::i64)));
11669 return std::make_pair(Lo, Hi);
11670}
11671
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011672// Create an even/odd pair of X registers holding integer value V.
11673static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11674 SDLoc dl(V.getNode());
11675 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11676 SDValue VHi = DAG.getAnyExtOrTrunc(
11677 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11678 dl, MVT::i64);
11679 if (DAG.getDataLayout().isBigEndian())
11680 std::swap (VLo, VHi);
11681 SDValue RegClass =
11682 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11683 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11684 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11685 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11686 return SDValue(
11687 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11688}
11689
Tim Northovercdf15292016-04-14 17:03:29 +000011690static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011691 SmallVectorImpl<SDValue> &Results,
11692 SelectionDAG &DAG,
11693 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011694 assert(N->getValueType(0) == MVT::i128 &&
11695 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011696
11697 if (Subtarget->hasLSE()) {
11698 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11699 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11700 SDValue Ops[] = {
11701 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11702 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11703 N->getOperand(1), // Ptr
11704 N->getOperand(0), // Chain in
11705 };
11706
Chandler Carruth66654b72018-08-14 23:30:32 +000011707 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011708
11709 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011710 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011711 case AtomicOrdering::Monotonic:
11712 Opcode = AArch64::CASPX;
11713 break;
11714 case AtomicOrdering::Acquire:
11715 Opcode = AArch64::CASPAX;
11716 break;
11717 case AtomicOrdering::Release:
11718 Opcode = AArch64::CASPLX;
11719 break;
11720 case AtomicOrdering::AcquireRelease:
11721 case AtomicOrdering::SequentiallyConsistent:
11722 Opcode = AArch64::CASPALX;
11723 break;
11724 default:
11725 llvm_unreachable("Unexpected ordering!");
11726 }
11727
11728 MachineSDNode *CmpSwap = DAG.getMachineNode(
11729 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011730 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011731
11732 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11733 if (DAG.getDataLayout().isBigEndian())
11734 std::swap(SubReg1, SubReg2);
11735 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11736 SDValue(CmpSwap, 0)));
11737 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11738 SDValue(CmpSwap, 0)));
11739 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11740 return;
11741 }
11742
Tim Northover2f32e7f2016-08-04 19:32:28 +000011743 auto Desired = splitInt128(N->getOperand(2), DAG);
11744 auto New = splitInt128(N->getOperand(3), DAG);
11745 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11746 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011747 SDNode *CmpSwap = DAG.getMachineNode(
11748 AArch64::CMP_SWAP_128, SDLoc(N),
11749 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11750
Chandler Carruth66654b72018-08-14 23:30:32 +000011751 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11752 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011753
11754 Results.push_back(SDValue(CmpSwap, 0));
11755 Results.push_back(SDValue(CmpSwap, 1));
11756 Results.push_back(SDValue(CmpSwap, 3));
11757}
11758
Tim Northover3b0846e2014-05-24 12:50:23 +000011759void AArch64TargetLowering::ReplaceNodeResults(
11760 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11761 switch (N->getOpcode()) {
11762 default:
11763 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011764 case ISD::BITCAST:
11765 ReplaceBITCASTResults(N, Results, DAG);
11766 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011767 case ISD::VECREDUCE_ADD:
11768 case ISD::VECREDUCE_SMAX:
11769 case ISD::VECREDUCE_SMIN:
11770 case ISD::VECREDUCE_UMAX:
11771 case ISD::VECREDUCE_UMIN:
11772 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11773 return;
11774
Charlie Turner434d4592015-10-16 15:38:25 +000011775 case AArch64ISD::SADDV:
11776 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11777 return;
11778 case AArch64ISD::UADDV:
11779 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11780 return;
11781 case AArch64ISD::SMINV:
11782 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11783 return;
11784 case AArch64ISD::UMINV:
11785 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11786 return;
11787 case AArch64ISD::SMAXV:
11788 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11789 return;
11790 case AArch64ISD::UMAXV:
11791 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11792 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011793 case ISD::FP_TO_UINT:
11794 case ISD::FP_TO_SINT:
11795 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11796 // Let normal code take care of it by not adding anything to Results.
11797 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011798 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011799 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011800 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011801 }
11802}
11803
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011804bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011805 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11806 return TargetLowering::useLoadStackGuardNode();
11807 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011808}
11809
Sanjay Patel1dd15592015-07-28 23:05:48 +000011810unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011811 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11812 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011813 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011814}
11815
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011816TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011817AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011818 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11819 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011820 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11821 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011822 return TypeWidenVector;
11823
11824 return TargetLoweringBase::getPreferredVectorAction(VT);
11825}
11826
Robin Morisseted3d48f2014-09-03 21:29:59 +000011827// Loads and stores less than 128-bits are already atomic; ones above that
11828// are doomed anyway, so defer to the default libcall and blame the OS when
11829// things go wrong.
11830bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11831 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11832 return Size == 128;
11833}
11834
11835// Loads and stores less than 128-bits are already atomic; ones above that
11836// are doomed anyway, so defer to the default libcall and blame the OS when
11837// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011838TargetLowering::AtomicExpansionKind
11839AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011840 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011841 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011842}
11843
11844// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011845TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011846AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011847 if (AI->isFloatingPointOperation())
11848 return AtomicExpansionKind::CmpXChg;
11849
Robin Morisseted3d48f2014-09-03 21:29:59 +000011850 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011851 if (Size > 128) return AtomicExpansionKind::None;
11852 // Nand not supported in LSE.
11853 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011854 // Leave 128 bits to LLSC.
11855 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011856}
11857
Alex Bradbury79518b02018-09-19 14:51:42 +000011858TargetLowering::AtomicExpansionKind
11859AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011860 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011861 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011862 if (Subtarget->hasLSE())
11863 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011864 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11865 // implement cmpxchg without spilling. If the address being exchanged is also
11866 // on the stack and close enough to the spill slot, this can lead to a
11867 // situation where the monitor always gets cleared and the atomic operation
11868 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011869 if (getTargetMachine().getOptLevel() == 0)
11870 return AtomicExpansionKind::None;
11871 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011872}
11873
Tim Northover3b0846e2014-05-24 12:50:23 +000011874Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11875 AtomicOrdering Ord) const {
11876 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11877 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011878 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011879
11880 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11881 // intrinsic must return {i64, i64} and we have to recombine them into a
11882 // single i128 here.
11883 if (ValTy->getPrimitiveSizeInBits() == 128) {
11884 Intrinsic::ID Int =
11885 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011886 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011887
11888 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11889 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11890
11891 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11892 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11893 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11894 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11895 return Builder.CreateOr(
11896 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11897 }
11898
11899 Type *Tys[] = { Addr->getType() };
11900 Intrinsic::ID Int =
11901 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011902 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011903
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011904 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11905
11906 const DataLayout &DL = M->getDataLayout();
11907 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11908 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11909
11910 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011911}
11912
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011913void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11914 IRBuilder<> &Builder) const {
11915 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011916 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011917}
11918
Tim Northover3b0846e2014-05-24 12:50:23 +000011919Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11920 Value *Val, Value *Addr,
11921 AtomicOrdering Ord) const {
11922 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011923 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011924
11925 // Since the intrinsics must have legal type, the i128 intrinsics take two
11926 // parameters: "i64, i64". We must marshal Val into the appropriate form
11927 // before the call.
11928 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11929 Intrinsic::ID Int =
11930 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11931 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11932 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11933
11934 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11935 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11936 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011937 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011938 }
11939
11940 Intrinsic::ID Int =
11941 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11942 Type *Tys[] = { Addr->getType() };
11943 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11944
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011945 const DataLayout &DL = M->getDataLayout();
11946 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11947 Val = Builder.CreateBitCast(Val, IntValTy);
11948
David Blaikieff6409d2015-05-18 22:13:54 +000011949 return Builder.CreateCall(Stxr,
11950 {Builder.CreateZExtOrBitCast(
11951 Val, Stxr->getFunctionType()->getParamType(0)),
11952 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011953}
Tim Northover3c55cca2014-11-27 21:02:42 +000011954
11955bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11956 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11957 return Ty->isArrayTy();
11958}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011959
11960bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11961 EVT) const {
11962 return false;
11963}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011964
Petr Hoseka7d59162017-02-24 03:10:10 +000011965static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011966 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11967 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011968 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011969 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000011970 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11971 Offset),
11972 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011973}
11974
Petr Hoseka7d59162017-02-24 03:10:10 +000011975Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11976 // Android provides a fixed TLS slot for the stack cookie. See the definition
11977 // of TLS_SLOT_STACK_GUARD in
11978 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11979 if (Subtarget->isTargetAndroid())
11980 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011981
Petr Hoseka7d59162017-02-24 03:10:10 +000011982 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011983 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011984 if (Subtarget->isTargetFuchsia())
11985 return UseTlsOffset(IRB, -0x10);
11986
11987 return TargetLowering::getIRStackGuard(IRB);
11988}
11989
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011990void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11991 // MSVC CRT provides functionalities for stack protection.
11992 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11993 // MSVC CRT has a global variable holding security cookie.
11994 M.getOrInsertGlobal("__security_cookie",
11995 Type::getInt8PtrTy(M.getContext()));
11996
11997 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000011998 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11999 "__security_check_cookie", Type::getVoidTy(M.getContext()),
12000 Type::getInt8PtrTy(M.getContext()));
12001 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12002 F->setCallingConv(CallingConv::Win64);
12003 F->addAttribute(1, Attribute::AttrKind::InReg);
12004 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012005 return;
12006 }
12007 TargetLowering::insertSSPDeclarations(M);
12008}
12009
12010Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12011 // MSVC CRT has a global variable holding security cookie.
12012 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12013 return M.getGlobalVariable("__security_cookie");
12014 return TargetLowering::getSDagStackGuard(M);
12015}
12016
James Y Knight7976eb52019-02-01 20:43:25 +000012017Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012018 // MSVC CRT has a function to validate security cookie.
12019 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12020 return M.getFunction("__security_check_cookie");
12021 return TargetLowering::getSSPStackGuardCheck(M);
12022}
12023
Petr Hoseka7d59162017-02-24 03:10:10 +000012024Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012025 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12026 // definition of TLS_SLOT_SAFESTACK in
12027 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000012028 if (Subtarget->isTargetAndroid())
12029 return UseTlsOffset(IRB, 0x48);
12030
12031 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000012032 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000012033 if (Subtarget->isTargetFuchsia())
12034 return UseTlsOffset(IRB, -0x8);
12035
12036 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012037}
Manman Rencbe4f942015-12-16 21:04:19 +000012038
Geoff Berry5d534b62017-02-21 18:53:14 +000012039bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12040 const Instruction &AndI) const {
12041 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12042 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12043 // may be beneficial to sink in other cases, but we would have to check that
12044 // the cmp would not get folded into the br to form a cbz for these to be
12045 // beneficial.
12046 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12047 if (!Mask)
12048 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000012049 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000012050}
12051
Roman Lebedev017e2722019-07-24 22:57:22 +000012052bool AArch64TargetLowering::
12053 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12054 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12055 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12056 SelectionDAG &DAG) const {
12057 // Does baseline recommend not to perform the fold by default?
12058 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12059 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12060 return false;
12061 // Else, if this is a vector shift, prefer 'shl'.
12062 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12063}
12064
Manman Rencbe4f942015-12-16 21:04:19 +000012065void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12066 // Update IsSplitCSR in AArch64unctionInfo.
12067 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12068 AFI->setIsSplitCSR(true);
12069}
12070
12071void AArch64TargetLowering::insertCopiesSplitCSR(
12072 MachineBasicBlock *Entry,
12073 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12074 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12075 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12076 if (!IStart)
12077 return;
12078
12079 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12080 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000012081 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000012082 for (const MCPhysReg *I = IStart; *I; ++I) {
12083 const TargetRegisterClass *RC = nullptr;
12084 if (AArch64::GPR64RegClass.contains(*I))
12085 RC = &AArch64::GPR64RegClass;
12086 else if (AArch64::FPR64RegClass.contains(*I))
12087 RC = &AArch64::FPR64RegClass;
12088 else
12089 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12090
12091 unsigned NewVR = MRI->createVirtualRegister(RC);
12092 // Create copy from CSR to a virtual register.
12093 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12094 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12095 // nounwind. If we want to generalize this later, we may need to emit
12096 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000012097 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000012098 Attribute::NoUnwind) &&
12099 "Function should be nounwind in insertCopiesSplitCSR!");
12100 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000012101 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000012102 .addReg(*I);
12103
Manman Ren4632e8e2016-01-15 20:13:28 +000012104 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000012105 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000012106 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12107 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000012108 .addReg(NewVR);
12109 }
12110}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012111
Reid Klecknerb5180542017-03-21 16:57:19 +000012112bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012113 // Integer division on AArch64 is expensive. However, when aggressively
12114 // optimizing for code size, we prefer to use a div instruction, as it is
12115 // usually smaller than the alternative sequence.
12116 // The exception to this is vector division. Since AArch64 doesn't have vector
12117 // integer division, leaving the division as-is is a loss even in terms of
12118 // size, because it will have to be scalarized, while the alternative code
12119 // sequence can be performed in vector form.
12120 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000012121 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012122 return OptSize && !VT.isVector();
12123}
Tim Northoverf19d4672017-02-08 17:57:20 +000012124
Roman Lebedevc4b83a62019-07-03 09:41:35 +000012125bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12126 // We want inc-of-add for scalars and sub-of-not for vectors.
12127 return VT.isScalarInteger();
12128}
12129
Joel Jones07150922018-01-25 21:55:39 +000012130bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12131 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12132}
12133
Tim Northoverf19d4672017-02-08 17:57:20 +000012134unsigned
12135AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000012136 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000012137 return getPointerTy(DL).getSizeInBits();
12138
12139 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12140}
Matthias Braun5c290dc2018-01-19 03:16:36 +000012141
12142void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12143 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12144 TargetLoweringBase::finalizeLowering(MF);
12145}
Eli Friedmanad1151c2018-11-09 23:33:30 +000012146
12147// Unlike X86, we let frame lowering assign offsets to all catch objects.
12148bool AArch64TargetLowering::needsFixedCatchObjects() const {
12149 return false;
12150}