blob: 361e2eaa7b09f285ca3aa3f6bb4f2f94dd56ee5a [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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000013#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000014#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000015#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000016#include "AArch64PerfectShuffle.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000017#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000018#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000020#include "Utils/AArch64BaseInfo.h"
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/ArrayRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000025#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000026#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000027#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/StringSwitch.h"
29#include "llvm/ADT/Triple.h"
30#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000031#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000033#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000034#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000035#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000037#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000038#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000040#include "llvm/CodeGen/RuntimeLibcalls.h"
41#include "llvm/CodeGen/SelectionDAG.h"
42#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000043#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000044#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000045#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000046#include "llvm/IR/Attributes.h"
47#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000051#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000052#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000053#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000054#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000055#include "llvm/IR/Instruction.h"
56#include "llvm/IR/Instructions.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000057#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000058#include "llvm/IR/Module.h"
59#include "llvm/IR/OperandTraits.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000060#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000061#include "llvm/IR/Use.h"
62#include "llvm/IR/Value.h"
63#include "llvm/MC/MCRegisterInfo.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000066#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000067#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000068#include "llvm/Support/Debug.h"
69#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000070#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000071#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000072#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000073#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000074#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000075#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000076#include <algorithm>
77#include <bitset>
78#include <cassert>
79#include <cctype>
80#include <cstdint>
81#include <cstdlib>
82#include <iterator>
83#include <limits>
84#include <tuple>
85#include <utility>
86#include <vector>
87
Tim Northover3b0846e2014-05-24 12:50:23 +000088using namespace llvm;
89
90#define DEBUG_TYPE "aarch64-lower"
91
92STATISTIC(NumTailCalls, "Number of tail calls");
93STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000094STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000095
Tim Northover3b0846e2014-05-24 12:50:23 +000096static cl::opt<bool>
97EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000098 cl::desc("Allow AArch64 SLI/SRI formation"),
99 cl::init(false));
100
101// FIXME: The necessary dtprel relocations don't seem to be supported
102// well in the GNU bfd and gold linkers at the moment. Therefore, by
103// default, for now, fall back to GeneralDynamic code generation.
104cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
105 "aarch64-elf-ldtls-generation", cl::Hidden,
106 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
107 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000108
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000109static cl::opt<bool>
110EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
111 cl::desc("Enable AArch64 logical imm instruction "
112 "optimization"),
113 cl::init(true));
114
Matthias Braunaf7d7702015-07-16 20:02:37 +0000115/// Value type used for condition codes.
116static const MVT MVT_CC = MVT::i32;
117
Eric Christopher905f12d2015-01-29 00:19:42 +0000118AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
119 const AArch64Subtarget &STI)
120 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000121 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
122 // we have to make something up. Arbitrarily, choose ZeroOrOne.
123 setBooleanContents(ZeroOrOneBooleanContent);
124 // When comparing vectors the result sets the different elements in the
125 // vector to all-one or all-zero.
126 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
127
128 // Set up the register classes.
129 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
130 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
131
132 if (Subtarget->hasFPARMv8()) {
133 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
134 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
135 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
136 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
137 }
138
139 if (Subtarget->hasNEON()) {
140 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
141 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
142 // Someone set us up the NEON.
143 addDRTypeForNEON(MVT::v2f32);
144 addDRTypeForNEON(MVT::v8i8);
145 addDRTypeForNEON(MVT::v4i16);
146 addDRTypeForNEON(MVT::v2i32);
147 addDRTypeForNEON(MVT::v1i64);
148 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000149 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000150
151 addQRTypeForNEON(MVT::v4f32);
152 addQRTypeForNEON(MVT::v2f64);
153 addQRTypeForNEON(MVT::v16i8);
154 addQRTypeForNEON(MVT::v8i16);
155 addQRTypeForNEON(MVT::v4i32);
156 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000157 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000158 }
159
160 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000161 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000162
163 // Provide all sorts of operation actions
164 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
165 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
166 setOperationAction(ISD::SETCC, MVT::i32, Custom);
167 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000168 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000169 setOperationAction(ISD::SETCC, MVT::f32, Custom);
170 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000171 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
172 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000173 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
174 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
175 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000176 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000177 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
178 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
179 setOperationAction(ISD::SELECT, MVT::i32, Custom);
180 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000181 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000182 setOperationAction(ISD::SELECT, MVT::f32, Custom);
183 setOperationAction(ISD::SELECT, MVT::f64, Custom);
184 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000186 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000187 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
188 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000189 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
191
192 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
193 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
194 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
195
196 setOperationAction(ISD::FREM, MVT::f32, Expand);
197 setOperationAction(ISD::FREM, MVT::f64, Expand);
198 setOperationAction(ISD::FREM, MVT::f80, Expand);
199
Amara Emersone27d5012018-04-10 19:01:58 +0000200 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
201
Tim Northover3b0846e2014-05-24 12:50:23 +0000202 // Custom lowering hooks are needed for XOR
203 // to fold it into CSINC/CSINV.
204 setOperationAction(ISD::XOR, MVT::i32, Custom);
205 setOperationAction(ISD::XOR, MVT::i64, Custom);
206
207 // Virtually no operation on f128 is legal, but LLVM can't expand them when
208 // there's a valid register class, so we need custom operations in most cases.
209 setOperationAction(ISD::FABS, MVT::f128, Expand);
210 setOperationAction(ISD::FADD, MVT::f128, Custom);
211 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
212 setOperationAction(ISD::FCOS, MVT::f128, Expand);
213 setOperationAction(ISD::FDIV, MVT::f128, Custom);
214 setOperationAction(ISD::FMA, MVT::f128, Expand);
215 setOperationAction(ISD::FMUL, MVT::f128, Custom);
216 setOperationAction(ISD::FNEG, MVT::f128, Expand);
217 setOperationAction(ISD::FPOW, MVT::f128, Expand);
218 setOperationAction(ISD::FREM, MVT::f128, Expand);
219 setOperationAction(ISD::FRINT, MVT::f128, Expand);
220 setOperationAction(ISD::FSIN, MVT::f128, Expand);
221 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
222 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
223 setOperationAction(ISD::FSUB, MVT::f128, Custom);
224 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
225 setOperationAction(ISD::SETCC, MVT::f128, Custom);
226 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
227 setOperationAction(ISD::SELECT, MVT::f128, Custom);
228 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
229 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
230
231 // Lowering for many of the conversions is actually specified by the non-f128
232 // type. The LowerXXX function will be trivial when f128 isn't involved.
233 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
234 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
235 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
236 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
237 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
238 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
239 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
240 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
241 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
242 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
243 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
244 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
245 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
246 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
247
248 // Variable arguments.
249 setOperationAction(ISD::VASTART, MVT::Other, Custom);
250 setOperationAction(ISD::VAARG, MVT::Other, Custom);
251 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
252 setOperationAction(ISD::VAEND, MVT::Other, Expand);
253
254 // Variable-sized objects.
255 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
256 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000257
258 if (Subtarget->isTargetWindows())
259 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
260 else
261 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000262
Tim Northover3b0846e2014-05-24 12:50:23 +0000263 // Constant pool entries
264 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
265
266 // BlockAddress
267 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
268
269 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
270 setOperationAction(ISD::ADDC, MVT::i32, Custom);
271 setOperationAction(ISD::ADDE, MVT::i32, Custom);
272 setOperationAction(ISD::SUBC, MVT::i32, Custom);
273 setOperationAction(ISD::SUBE, MVT::i32, Custom);
274 setOperationAction(ISD::ADDC, MVT::i64, Custom);
275 setOperationAction(ISD::ADDE, MVT::i64, Custom);
276 setOperationAction(ISD::SUBC, MVT::i64, Custom);
277 setOperationAction(ISD::SUBE, MVT::i64, Custom);
278
279 // AArch64 lacks both left-rotate and popcount instructions.
280 setOperationAction(ISD::ROTL, MVT::i32, Expand);
281 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000282 for (MVT VT : MVT::vector_valuetypes()) {
283 setOperationAction(ISD::ROTL, VT, Expand);
284 setOperationAction(ISD::ROTR, VT, Expand);
285 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000286
287 // AArch64 doesn't have {U|S}MUL_LOHI.
288 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
289 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
290
Tim Northover3b0846e2014-05-24 12:50:23 +0000291 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
292 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
293
294 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
295 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000296 for (MVT VT : MVT::vector_valuetypes()) {
297 setOperationAction(ISD::SDIVREM, VT, Expand);
298 setOperationAction(ISD::UDIVREM, VT, Expand);
299 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000300 setOperationAction(ISD::SREM, MVT::i32, Expand);
301 setOperationAction(ISD::SREM, MVT::i64, Expand);
302 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
303 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
304 setOperationAction(ISD::UREM, MVT::i32, Expand);
305 setOperationAction(ISD::UREM, MVT::i64, Expand);
306
307 // Custom lower Add/Sub/Mul with overflow.
308 setOperationAction(ISD::SADDO, MVT::i32, Custom);
309 setOperationAction(ISD::SADDO, MVT::i64, Custom);
310 setOperationAction(ISD::UADDO, MVT::i32, Custom);
311 setOperationAction(ISD::UADDO, MVT::i64, Custom);
312 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
313 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
314 setOperationAction(ISD::USUBO, MVT::i32, Custom);
315 setOperationAction(ISD::USUBO, MVT::i64, Custom);
316 setOperationAction(ISD::SMULO, MVT::i32, Custom);
317 setOperationAction(ISD::SMULO, MVT::i64, Custom);
318 setOperationAction(ISD::UMULO, MVT::i32, Custom);
319 setOperationAction(ISD::UMULO, MVT::i64, Custom);
320
321 setOperationAction(ISD::FSIN, MVT::f32, Expand);
322 setOperationAction(ISD::FSIN, MVT::f64, Expand);
323 setOperationAction(ISD::FCOS, MVT::f32, Expand);
324 setOperationAction(ISD::FCOS, MVT::f64, Expand);
325 setOperationAction(ISD::FPOW, MVT::f32, Expand);
326 setOperationAction(ISD::FPOW, MVT::f64, Expand);
327 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
328 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000329 if (Subtarget->hasFullFP16())
330 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
331 else
332 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000333
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000334 setOperationAction(ISD::FREM, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000335 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
336 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000337 setOperationAction(ISD::FPOW, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000338 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
339 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000340 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000341 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
342 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000343 setOperationAction(ISD::FCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000344 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
345 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000346 setOperationAction(ISD::FSIN, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000347 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
348 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000349 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000350 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
351 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000352 setOperationAction(ISD::FEXP, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000353 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
354 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000355 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000356 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
357 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000358 setOperationAction(ISD::FLOG, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000359 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
360 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000361 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000362 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
363 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000364 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000365 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
366 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000367
368 if (!Subtarget->hasFullFP16()) {
369 setOperationAction(ISD::SELECT, MVT::f16, Promote);
370 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
371 setOperationAction(ISD::SETCC, MVT::f16, Promote);
372 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
373 setOperationAction(ISD::FADD, MVT::f16, Promote);
374 setOperationAction(ISD::FSUB, MVT::f16, Promote);
375 setOperationAction(ISD::FMUL, MVT::f16, Promote);
376 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000377 setOperationAction(ISD::FMA, MVT::f16, Promote);
378 setOperationAction(ISD::FNEG, MVT::f16, Promote);
379 setOperationAction(ISD::FABS, MVT::f16, Promote);
380 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
381 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000382 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
383 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
384 setOperationAction(ISD::FRINT, MVT::f16, Promote);
385 setOperationAction(ISD::FROUND, MVT::f16, Promote);
386 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
387 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
388 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000389 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
390 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000391
392 // promote v4f16 to v4f32 when that is known to be safe.
393 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
394 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
395 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
396 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
397 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
398 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
399 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
400 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
401 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
402 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
403 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
404 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
405
406 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
407 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
408 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
409 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
410 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
411 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
412 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
413 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
414 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
415 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
416 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
417 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
418 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
419 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
420 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000421
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000422 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
423 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
424 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
425 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
426 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
427 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
428 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
429 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
430 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
431 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
432 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
433 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
434 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
435 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
436 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
437 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
438 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
439 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
440 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
441 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
442 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000443
Tim Northover3b0846e2014-05-24 12:50:23 +0000444 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000445 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000446 setOperationAction(ISD::FFLOOR, Ty, Legal);
447 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
448 setOperationAction(ISD::FCEIL, Ty, Legal);
449 setOperationAction(ISD::FRINT, Ty, Legal);
450 setOperationAction(ISD::FTRUNC, Ty, Legal);
451 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000452 setOperationAction(ISD::FMINNUM, Ty, Legal);
453 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000454 setOperationAction(ISD::FMINIMUM, Ty, Legal);
455 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000456 }
457
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000458 if (Subtarget->hasFullFP16()) {
459 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
460 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
461 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
462 setOperationAction(ISD::FRINT, MVT::f16, Legal);
463 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
464 setOperationAction(ISD::FROUND, MVT::f16, Legal);
465 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
466 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000467 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
468 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000469 }
470
Tim Northover3b0846e2014-05-24 12:50:23 +0000471 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
472
Tim Northover70666e72018-06-20 12:09:01 +0000473 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
474
Tim Northovercdf15292016-04-14 17:03:29 +0000475 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000476 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
477 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000478 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
479 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000480
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000481 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
482 // This requires the Performance Monitors extension.
483 if (Subtarget->hasPerfMon())
484 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
485
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000486 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
487 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
488 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000489 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
490 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
491 } else {
492 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
493 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
494 }
495
Juergen Ributzka23266502014-12-10 19:43:32 +0000496 // Make floating-point constants legal for the large code model, so they don't
497 // become loads from the constant pool.
498 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
499 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
500 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
501 }
502
Tim Northover3b0846e2014-05-24 12:50:23 +0000503 // AArch64 does not have floating-point extending loads, i1 sign-extending
504 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000505 for (MVT VT : MVT::fp_valuetypes()) {
506 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
507 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
508 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
509 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
510 }
511 for (MVT VT : MVT::integer_valuetypes())
512 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
513
Tim Northover3b0846e2014-05-24 12:50:23 +0000514 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
515 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
516 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
517 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
518 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
519 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
520 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000521
522 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
523 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
524
Tim Northover3b0846e2014-05-24 12:50:23 +0000525 // Indexed loads and stores are supported.
526 for (unsigned im = (unsigned)ISD::PRE_INC;
527 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
528 setIndexedLoadAction(im, MVT::i8, Legal);
529 setIndexedLoadAction(im, MVT::i16, Legal);
530 setIndexedLoadAction(im, MVT::i32, Legal);
531 setIndexedLoadAction(im, MVT::i64, Legal);
532 setIndexedLoadAction(im, MVT::f64, Legal);
533 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000534 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000535 setIndexedStoreAction(im, MVT::i8, Legal);
536 setIndexedStoreAction(im, MVT::i16, Legal);
537 setIndexedStoreAction(im, MVT::i32, Legal);
538 setIndexedStoreAction(im, MVT::i64, Legal);
539 setIndexedStoreAction(im, MVT::f64, Legal);
540 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000541 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000542 }
543
544 // Trap.
545 setOperationAction(ISD::TRAP, MVT::Other, Legal);
546
547 // We combine OR nodes for bitfield operations.
548 setTargetDAGCombine(ISD::OR);
549
550 // Vector add and sub nodes may conceal a high-half opportunity.
551 // Also, try to fold ADD into CSINC/CSINV..
552 setTargetDAGCombine(ISD::ADD);
553 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000554 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000555 setTargetDAGCombine(ISD::XOR);
556 setTargetDAGCombine(ISD::SINT_TO_FP);
557 setTargetDAGCombine(ISD::UINT_TO_FP);
558
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000559 setTargetDAGCombine(ISD::FP_TO_SINT);
560 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000561 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000562
Tim Northover3b0846e2014-05-24 12:50:23 +0000563 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564
565 setTargetDAGCombine(ISD::ANY_EXTEND);
566 setTargetDAGCombine(ISD::ZERO_EXTEND);
567 setTargetDAGCombine(ISD::SIGN_EXTEND);
568 setTargetDAGCombine(ISD::BITCAST);
569 setTargetDAGCombine(ISD::CONCAT_VECTORS);
570 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000571 if (Subtarget->supportsAddressTopByteIgnored())
572 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000573
574 setTargetDAGCombine(ISD::MUL);
575
576 setTargetDAGCombine(ISD::SELECT);
577 setTargetDAGCombine(ISD::VSELECT);
578
579 setTargetDAGCombine(ISD::INTRINSIC_VOID);
580 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
581 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
582
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000583 setTargetDAGCombine(ISD::GlobalAddress);
584
Evandro Menezesf8425342018-05-29 15:58:50 +0000585 // In case of strict alignment, avoid an excessive number of byte wide stores.
586 MaxStoresPerMemsetOptSize = 8;
587 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
588 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000589
Evandro Menezesf8425342018-05-29 15:58:50 +0000590 MaxGluedStoresPerMemcpy = 4;
591 MaxStoresPerMemcpyOptSize = 4;
592 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
593 ? MaxStoresPerMemcpyOptSize : 16;
594
595 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000596
597 setStackPointerRegisterToSaveRestore(AArch64::SP);
598
599 setSchedulingPreference(Sched::Hybrid);
600
Quentin Colombet6843ac42015-03-31 20:52:32 +0000601 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000602
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000603 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000604 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000605 // Set preferred alignments.
606 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
607 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000608
Evandro Menezese45de8a2016-09-26 15:32:33 +0000609 // Only change the limit for entries in a jump table if specified by
610 // the subtarget, but not at the command line.
611 unsigned MaxJT = STI.getMaximumJumpTableSize();
612 if (MaxJT && getMaximumJumpTableSize() == 0)
613 setMaximumJumpTableSize(MaxJT);
614
Tim Northover3b0846e2014-05-24 12:50:23 +0000615 setHasExtractBitsInsn(true);
616
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000617 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
618
Tim Northover3b0846e2014-05-24 12:50:23 +0000619 if (Subtarget->hasNEON()) {
620 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
621 // silliness like this:
622 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
623 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
624 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
626 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
627 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
628 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
629 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
630 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
631 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
632 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
633 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
634 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
635 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
636 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
637 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
638 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
639 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
640 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
641 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
642 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
643 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
644 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
645 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
646 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
647
648 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
649 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
650 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
651 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
652 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
653
654 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
655
656 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
657 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000658 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
659 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
660 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
661 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000662 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
663 // -> v8f16 conversions.
Craig Toppera4f99972018-01-01 19:21:35 +0000664 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
665 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
666 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
667 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000668 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
669 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
670 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
671 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
672 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000673 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
674 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
675 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
676 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000677
Craig Topperc5551bf2016-04-26 05:26:51 +0000678 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
679 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
680
Craig Topper3b4842b2016-04-28 01:58:21 +0000681 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
682 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
683 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
684 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
685 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
686 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
687 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
688 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
689
Tim Northover3b0846e2014-05-24 12:50:23 +0000690 // AArch64 doesn't have MUL.2d:
691 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000692 // Custom handling for some quad-vector types to detect MULL.
693 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
694 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
695 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
696
Amara Emersonc9916d72017-05-16 21:29:22 +0000697 // Vector reductions
698 for (MVT VT : MVT::integer_valuetypes()) {
699 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
700 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
701 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
702 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
703 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
704 }
705 for (MVT VT : MVT::fp_valuetypes()) {
706 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
707 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
708 }
709
Tim Northover3b0846e2014-05-24 12:50:23 +0000710 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
711 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
712 // Likewise, narrowing and extending vector loads/stores aren't handled
713 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000714 for (MVT VT : MVT::vector_valuetypes()) {
715 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000716
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000717 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000718 setOperationAction(ISD::MULHS, VT, Legal);
719 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000720 } else {
721 setOperationAction(ISD::MULHS, VT, Expand);
722 setOperationAction(ISD::MULHU, VT, Expand);
723 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000724 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000725 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000726
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000727 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000728
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000729 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000730 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000731 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
732 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
733 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
734 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000735 }
736
737 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000738 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000739 setOperationAction(ISD::FFLOOR, Ty, Legal);
740 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
741 setOperationAction(ISD::FCEIL, Ty, Legal);
742 setOperationAction(ISD::FRINT, Ty, Legal);
743 setOperationAction(ISD::FTRUNC, Ty, Legal);
744 setOperationAction(ISD::FROUND, Ty, Legal);
745 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000746
747 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000748 }
James Molloyf089ab72014-08-06 10:42:18 +0000749
Matthias Braun651cff42016-06-02 18:03:53 +0000750 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000751}
752
Craig Topper18e69f42016-04-15 06:20:21 +0000753void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000754 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000755
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000756 if (VT.isFloatingPoint()) {
757 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
758 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
759 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000760 }
761
762 // Mark vector float intrinsics as expand.
763 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000764 setOperationAction(ISD::FSIN, VT, Expand);
765 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000766 setOperationAction(ISD::FPOW, VT, Expand);
767 setOperationAction(ISD::FLOG, VT, Expand);
768 setOperationAction(ISD::FLOG2, VT, Expand);
769 setOperationAction(ISD::FLOG10, VT, Expand);
770 setOperationAction(ISD::FEXP, VT, Expand);
771 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000772
773 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000774 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000775 }
776
Craig Topper18e69f42016-04-15 06:20:21 +0000777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
779 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
780 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
781 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
782 setOperationAction(ISD::SRA, VT, Custom);
783 setOperationAction(ISD::SRL, VT, Custom);
784 setOperationAction(ISD::SHL, VT, Custom);
785 setOperationAction(ISD::AND, VT, Custom);
786 setOperationAction(ISD::OR, VT, Custom);
787 setOperationAction(ISD::SETCC, VT, Custom);
788 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000789
Craig Topper18e69f42016-04-15 06:20:21 +0000790 setOperationAction(ISD::SELECT, VT, Expand);
791 setOperationAction(ISD::SELECT_CC, VT, Expand);
792 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000793 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000794 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000795
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000796 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000797 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000798 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000799
Craig Topper18e69f42016-04-15 06:20:21 +0000800 setOperationAction(ISD::UDIV, VT, Expand);
801 setOperationAction(ISD::SDIV, VT, Expand);
802 setOperationAction(ISD::UREM, VT, Expand);
803 setOperationAction(ISD::SREM, VT, Expand);
804 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000805
Craig Topper18e69f42016-04-15 06:20:21 +0000806 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
807 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000808
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000809 if (!VT.isFloatingPoint())
810 setOperationAction(ISD::ABS, VT, Legal);
811
Hal Finkelcd8664c2015-12-11 23:11:52 +0000812 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000813 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000814 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000815 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000816
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000817 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
818 if (VT.isFloatingPoint() &&
819 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000820 for (unsigned Opcode :
821 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000822 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000823
Tim Northover3b0846e2014-05-24 12:50:23 +0000824 if (Subtarget->isLittleEndian()) {
825 for (unsigned im = (unsigned)ISD::PRE_INC;
826 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000827 setIndexedLoadAction(im, VT, Legal);
828 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000829 }
830 }
831}
832
833void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
834 addRegisterClass(VT, &AArch64::FPR64RegClass);
835 addTypeForNEON(VT, MVT::v2i32);
836}
837
838void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
839 addRegisterClass(VT, &AArch64::FPR128RegClass);
840 addTypeForNEON(VT, MVT::v4i32);
841}
842
Mehdi Amini44ede332015-07-09 02:09:04 +0000843EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
844 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000845 if (!VT.isVector())
846 return MVT::i32;
847 return VT.changeVectorElementTypeToInteger();
848}
849
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000850static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
851 const APInt &Demanded,
852 TargetLowering::TargetLoweringOpt &TLO,
853 unsigned NewOpc) {
854 uint64_t OldImm = Imm, NewImm, Enc;
855 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
856
857 // Return if the immediate is already all zeros, all ones, a bimm32 or a
858 // bimm64.
859 if (Imm == 0 || Imm == Mask ||
860 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
861 return false;
862
863 unsigned EltSize = Size;
864 uint64_t DemandedBits = Demanded.getZExtValue();
865
866 // Clear bits that are not demanded.
867 Imm &= DemandedBits;
868
869 while (true) {
870 // The goal here is to set the non-demanded bits in a way that minimizes
871 // the number of switching between 0 and 1. In order to achieve this goal,
872 // we set the non-demanded bits to the value of the preceding demanded bits.
873 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
874 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
875 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
876 // The final result is 0b11000011.
877 uint64_t NonDemandedBits = ~DemandedBits;
878 uint64_t InvertedImm = ~Imm & DemandedBits;
879 uint64_t RotatedImm =
880 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
881 NonDemandedBits;
882 uint64_t Sum = RotatedImm + NonDemandedBits;
883 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
884 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
885 NewImm = (Imm | Ones) & Mask;
886
887 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
888 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
889 // we halve the element size and continue the search.
890 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
891 break;
892
893 // We cannot shrink the element size any further if it is 2-bits.
894 if (EltSize == 2)
895 return false;
896
897 EltSize /= 2;
898 Mask >>= EltSize;
899 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
900
901 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
902 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
903 return false;
904
905 // Merge the upper and lower halves of Imm and DemandedBits.
906 Imm |= Hi;
907 DemandedBits |= DemandedBitsHi;
908 }
909
910 ++NumOptimizedImms;
911
912 // Replicate the element across the register width.
913 while (EltSize < Size) {
914 NewImm |= NewImm << EltSize;
915 EltSize *= 2;
916 }
917
918 (void)OldImm;
919 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
920 "demanded bits should never be altered");
921 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
922
923 // Create the new constant immediate node.
924 EVT VT = Op.getValueType();
925 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000926 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000927
928 // If the new constant immediate is all-zeros or all-ones, let the target
929 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000930 if (NewImm == 0 || NewImm == OrigMask) {
931 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
932 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000933 // Otherwise, create a machine node so that target independent DAG combine
934 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000935 } else {
936 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
937 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
938 New = SDValue(
939 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
940 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000941
942 return TLO.CombineTo(Op, New);
943}
944
945bool AArch64TargetLowering::targetShrinkDemandedConstant(
946 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
947 // Delay this optimization to as late as possible.
948 if (!TLO.LegalOps)
949 return false;
950
951 if (!EnableOptimizeLogicalImm)
952 return false;
953
954 EVT VT = Op.getValueType();
955 if (VT.isVector())
956 return false;
957
958 unsigned Size = VT.getSizeInBits();
959 assert((Size == 32 || Size == 64) &&
960 "i32 or i64 is expected after legalization.");
961
962 // Exit early if we demand all bits.
963 if (Demanded.countPopulation() == Size)
964 return false;
965
966 unsigned NewOpc;
967 switch (Op.getOpcode()) {
968 default:
969 return false;
970 case ISD::AND:
971 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
972 break;
973 case ISD::OR:
974 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
975 break;
976 case ISD::XOR:
977 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
978 break;
979 }
980 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
981 if (!C)
982 return false;
983 uint64_t Imm = C->getZExtValue();
984 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
985}
986
Tim Northover3b0846e2014-05-24 12:50:23 +0000987/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000988/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000989void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000990 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000991 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000992 switch (Op.getOpcode()) {
993 default:
994 break;
995 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000996 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +0000997 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
998 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +0000999 Known.Zero &= Known2.Zero;
1000 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001001 break;
1002 }
1003 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001004 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001005 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1006 switch (IntID) {
1007 default: return;
1008 case Intrinsic::aarch64_ldaxr:
1009 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001010 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001011 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001012 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001013 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001014 return;
1015 }
1016 }
1017 break;
1018 }
1019 case ISD::INTRINSIC_WO_CHAIN:
1020 case ISD::INTRINSIC_VOID: {
1021 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1022 switch (IntNo) {
1023 default:
1024 break;
1025 case Intrinsic::aarch64_neon_umaxv:
1026 case Intrinsic::aarch64_neon_uminv: {
1027 // Figure out the datatype of the vector operand. The UMINV instruction
1028 // will zero extend the result, so we can mark as known zero all the
1029 // bits larger than the element datatype. 32-bit or larget doesn't need
1030 // this as those are legal types and will be handled by isel directly.
1031 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001032 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001033 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1034 assert(BitWidth >= 8 && "Unexpected width!");
1035 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001036 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001037 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1038 assert(BitWidth >= 16 && "Unexpected width!");
1039 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001040 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001041 }
1042 break;
1043 } break;
1044 }
1045 }
1046 }
1047}
1048
Mehdi Aminieaabc512015-07-09 15:12:23 +00001049MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1050 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001051 return MVT::i64;
1052}
1053
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001054bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1055 unsigned AddrSpace,
1056 unsigned Align,
1057 bool *Fast) const {
1058 if (Subtarget->requiresStrictAlign())
1059 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001060
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001061 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001062 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1063 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001064 // See comments in performSTORECombine() for more details about
1065 // these conditions.
1066
1067 // Code that uses clang vector extensions can mark that it
1068 // wants unaligned accesses to be treated as fast by
1069 // underspecifying alignment to be 1 or 2.
1070 Align <= 2 ||
1071
1072 // Disregard v2i64. Memcpy lowering produces those and splitting
1073 // them regresses performance on micro-benchmarks and olden/bh.
1074 VT == MVT::v2i64;
1075 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001076 return true;
1077}
1078
Tim Northover3b0846e2014-05-24 12:50:23 +00001079FastISel *
1080AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1081 const TargetLibraryInfo *libInfo) const {
1082 return AArch64::createFastISel(funcInfo, libInfo);
1083}
1084
1085const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001086 switch ((AArch64ISD::NodeType)Opcode) {
1087 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001088 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1089 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001090 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001091 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1092 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1093 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1094 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1095 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1096 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1097 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1098 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1099 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1100 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001101 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001102 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1103 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1104 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1105 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1106 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1107 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1108 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001109 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1110 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1111 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001112 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001113 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1114 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1115 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1116 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1117 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1118 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1119 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1120 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1121 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1122 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1123 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1124 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1125 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1126 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1127 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1128 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1129 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1130 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1131 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1132 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1133 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1134 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1135 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1136 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1137 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1138 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1139 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1140 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1141 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1142 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1143 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1144 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1145 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1146 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1147 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1148 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1149 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1150 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1151 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1152 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1153 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1154 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1155 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1156 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1157 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1158 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1159 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1160 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001161 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1162 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1163 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1164 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1165 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1166 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001167 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1168 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1169 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1170 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1171 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1172 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1173 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001174 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001175 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1176 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001177 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001178 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1179 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1180 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1181 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1182 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1183 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1184 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1185 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1186 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1187 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1188 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1189 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1190 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1191 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1192 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1193 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1194 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1195 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1196 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1197 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1198 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1199 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1200 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1201 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1202 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1203 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1204 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1205 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1206 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001207 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1208 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001209 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001210 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1211 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1212 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001213 }
Matthias Braund04893f2015-05-07 21:33:59 +00001214 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001215}
1216
1217MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001218AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001219 MachineBasicBlock *MBB) const {
1220 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1221 // phi node:
1222
1223 // OrigBB:
1224 // [... previous instrs leading to comparison ...]
1225 // b.ne TrueBB
1226 // b EndBB
1227 // TrueBB:
1228 // ; Fallthrough
1229 // EndBB:
1230 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1231
Tim Northover3b0846e2014-05-24 12:50:23 +00001232 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001233 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001234 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001235 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001236 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001237
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001238 unsigned DestReg = MI.getOperand(0).getReg();
1239 unsigned IfTrueReg = MI.getOperand(1).getReg();
1240 unsigned IfFalseReg = MI.getOperand(2).getReg();
1241 unsigned CondCode = MI.getOperand(3).getImm();
1242 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001243
1244 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1246 MF->insert(It, TrueBB);
1247 MF->insert(It, EndBB);
1248
1249 // Transfer rest of current basic-block to EndBB
1250 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1251 MBB->end());
1252 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1253
1254 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1255 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1256 MBB->addSuccessor(TrueBB);
1257 MBB->addSuccessor(EndBB);
1258
1259 // TrueBB falls through to the end.
1260 TrueBB->addSuccessor(EndBB);
1261
1262 if (!NZCVKilled) {
1263 TrueBB->addLiveIn(AArch64::NZCV);
1264 EndBB->addLiveIn(AArch64::NZCV);
1265 }
1266
1267 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1268 .addReg(IfTrueReg)
1269 .addMBB(TrueBB)
1270 .addReg(IfFalseReg)
1271 .addMBB(MBB);
1272
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001273 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001274 return EndBB;
1275}
1276
Eli Friedmanad1151c2018-11-09 23:33:30 +00001277MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1278 MachineInstr &MI, MachineBasicBlock *BB) const {
1279 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1280 BB->getParent()->getFunction().getPersonalityFn())) &&
1281 "SEH does not use catchret!");
1282 return BB;
1283}
1284
1285MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1286 MachineInstr &MI, MachineBasicBlock *BB) const {
1287 MI.eraseFromParent();
1288 return BB;
1289}
1290
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001291MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1292 MachineInstr &MI, MachineBasicBlock *BB) const {
1293 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001294 default:
1295#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001296 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001297#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001298 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001299
1300 case AArch64::F128CSEL:
1301 return EmitF128CSEL(MI, BB);
1302
1303 case TargetOpcode::STACKMAP:
1304 case TargetOpcode::PATCHPOINT:
1305 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001306
1307 case AArch64::CATCHRET:
1308 return EmitLoweredCatchRet(MI, BB);
1309 case AArch64::CATCHPAD:
1310 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001311 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001312}
1313
1314//===----------------------------------------------------------------------===//
1315// AArch64 Lowering private implementation.
1316//===----------------------------------------------------------------------===//
1317
1318//===----------------------------------------------------------------------===//
1319// Lowering Code
1320//===----------------------------------------------------------------------===//
1321
1322/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1323/// CC
1324static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1325 switch (CC) {
1326 default:
1327 llvm_unreachable("Unknown condition code!");
1328 case ISD::SETNE:
1329 return AArch64CC::NE;
1330 case ISD::SETEQ:
1331 return AArch64CC::EQ;
1332 case ISD::SETGT:
1333 return AArch64CC::GT;
1334 case ISD::SETGE:
1335 return AArch64CC::GE;
1336 case ISD::SETLT:
1337 return AArch64CC::LT;
1338 case ISD::SETLE:
1339 return AArch64CC::LE;
1340 case ISD::SETUGT:
1341 return AArch64CC::HI;
1342 case ISD::SETUGE:
1343 return AArch64CC::HS;
1344 case ISD::SETULT:
1345 return AArch64CC::LO;
1346 case ISD::SETULE:
1347 return AArch64CC::LS;
1348 }
1349}
1350
1351/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1352static void changeFPCCToAArch64CC(ISD::CondCode CC,
1353 AArch64CC::CondCode &CondCode,
1354 AArch64CC::CondCode &CondCode2) {
1355 CondCode2 = AArch64CC::AL;
1356 switch (CC) {
1357 default:
1358 llvm_unreachable("Unknown FP condition!");
1359 case ISD::SETEQ:
1360 case ISD::SETOEQ:
1361 CondCode = AArch64CC::EQ;
1362 break;
1363 case ISD::SETGT:
1364 case ISD::SETOGT:
1365 CondCode = AArch64CC::GT;
1366 break;
1367 case ISD::SETGE:
1368 case ISD::SETOGE:
1369 CondCode = AArch64CC::GE;
1370 break;
1371 case ISD::SETOLT:
1372 CondCode = AArch64CC::MI;
1373 break;
1374 case ISD::SETOLE:
1375 CondCode = AArch64CC::LS;
1376 break;
1377 case ISD::SETONE:
1378 CondCode = AArch64CC::MI;
1379 CondCode2 = AArch64CC::GT;
1380 break;
1381 case ISD::SETO:
1382 CondCode = AArch64CC::VC;
1383 break;
1384 case ISD::SETUO:
1385 CondCode = AArch64CC::VS;
1386 break;
1387 case ISD::SETUEQ:
1388 CondCode = AArch64CC::EQ;
1389 CondCode2 = AArch64CC::VS;
1390 break;
1391 case ISD::SETUGT:
1392 CondCode = AArch64CC::HI;
1393 break;
1394 case ISD::SETUGE:
1395 CondCode = AArch64CC::PL;
1396 break;
1397 case ISD::SETLT:
1398 case ISD::SETULT:
1399 CondCode = AArch64CC::LT;
1400 break;
1401 case ISD::SETLE:
1402 case ISD::SETULE:
1403 CondCode = AArch64CC::LE;
1404 break;
1405 case ISD::SETNE:
1406 case ISD::SETUNE:
1407 CondCode = AArch64CC::NE;
1408 break;
1409 }
1410}
1411
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001412/// Convert a DAG fp condition code to an AArch64 CC.
1413/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1414/// should be AND'ed instead of OR'ed.
1415static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1416 AArch64CC::CondCode &CondCode,
1417 AArch64CC::CondCode &CondCode2) {
1418 CondCode2 = AArch64CC::AL;
1419 switch (CC) {
1420 default:
1421 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1422 assert(CondCode2 == AArch64CC::AL);
1423 break;
1424 case ISD::SETONE:
1425 // (a one b)
1426 // == ((a olt b) || (a ogt b))
1427 // == ((a ord b) && (a une b))
1428 CondCode = AArch64CC::VC;
1429 CondCode2 = AArch64CC::NE;
1430 break;
1431 case ISD::SETUEQ:
1432 // (a ueq b)
1433 // == ((a uno b) || (a oeq b))
1434 // == ((a ule b) && (a uge b))
1435 CondCode = AArch64CC::PL;
1436 CondCode2 = AArch64CC::LE;
1437 break;
1438 }
1439}
1440
Tim Northover3b0846e2014-05-24 12:50:23 +00001441/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1442/// CC usable with the vector instructions. Fewer operations are available
1443/// without a real NZCV register, so we have to use less efficient combinations
1444/// to get the same effect.
1445static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1446 AArch64CC::CondCode &CondCode,
1447 AArch64CC::CondCode &CondCode2,
1448 bool &Invert) {
1449 Invert = false;
1450 switch (CC) {
1451 default:
1452 // Mostly the scalar mappings work fine.
1453 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1454 break;
1455 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001456 Invert = true;
1457 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001458 case ISD::SETO:
1459 CondCode = AArch64CC::MI;
1460 CondCode2 = AArch64CC::GE;
1461 break;
1462 case ISD::SETUEQ:
1463 case ISD::SETULT:
1464 case ISD::SETULE:
1465 case ISD::SETUGT:
1466 case ISD::SETUGE:
1467 // All of the compare-mask comparisons are ordered, but we can switch
1468 // between the two by a double inversion. E.g. ULE == !OGT.
1469 Invert = true;
1470 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1471 break;
1472 }
1473}
1474
1475static bool isLegalArithImmed(uint64_t C) {
1476 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001477 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001478 LLVM_DEBUG(dbgs() << "Is imm " << C
1479 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001480 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001481}
1482
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001483// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1484// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1485// can be set differently by this operation. It comes down to whether
1486// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1487// everything is fine. If not then the optimization is wrong. Thus general
1488// comparisons are only valid if op2 != 0.
1489//
1490// So, finally, the only LLVM-native comparisons that don't mention C and V
1491// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1492// the absence of information about op2.
1493static bool isCMN(SDValue Op, ISD::CondCode CC) {
1494 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1495 (CC == ISD::SETEQ || CC == ISD::SETNE);
1496}
1497
Tim Northover3b0846e2014-05-24 12:50:23 +00001498static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001499 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001500 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001501 const bool FullFP16 =
1502 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001503
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001504 if (VT.isFloatingPoint()) {
1505 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001506 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001507 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1508 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001509 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001510 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001511 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001512 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001513
1514 // The CMP instruction is just an alias for SUBS, and representing it as
1515 // SUBS means that it's possible to get CSE with subtract operations.
1516 // A later phase can perform the optimization of setting the destination
1517 // register to WZR/XZR if it ends up being unused.
1518 unsigned Opcode = AArch64ISD::SUBS;
1519
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001520 if (isCMN(RHS, CC)) {
1521 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001522 Opcode = AArch64ISD::ADDS;
1523 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001524 } else if (isCMN(LHS, CC)) {
1525 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1526 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1527 Opcode = AArch64ISD::ADDS;
1528 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001529 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001530 !isUnsignedIntSetCC(CC)) {
1531 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1532 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1533 // of the signed comparisons.
1534 Opcode = AArch64ISD::ANDS;
1535 RHS = LHS.getOperand(1);
1536 LHS = LHS.getOperand(0);
1537 }
1538
Matthias Braunaf7d7702015-07-16 20:02:37 +00001539 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001540 .getValue(1);
1541}
1542
Matthias Braunaf7d7702015-07-16 20:02:37 +00001543/// \defgroup AArch64CCMP CMP;CCMP matching
1544///
1545/// These functions deal with the formation of CMP;CCMP;... sequences.
1546/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1547/// a comparison. They set the NZCV flags to a predefined value if their
1548/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001549/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001550/// expressed as:
1551/// cmp A
1552/// ccmp B, inv(CB), CA
1553/// check for CB flags
1554///
Matthias Braund0412122018-12-06 01:40:23 +00001555/// This naturally lets us implement chains of AND operations with SETCC
1556/// operands. And we can even implement some other situations by transforming
1557/// them:
1558/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1559/// negating the flags used in a CCMP/FCCMP operations.
1560/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1561/// by negating the flags we test for afterwards. i.e.
1562/// NEG (CMP CCMP CCCMP ...) can be implemented.
1563/// - Note that we can only ever negate all previously processed results.
1564/// What we can not implement by flipping the flags to test is a negation
1565/// of two sub-trees (because the negation affects all sub-trees emitted so
1566/// far, so the 2nd sub-tree we emit would also affect the first).
1567/// With those tools we can implement some OR operations:
1568/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1569/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1570/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1571/// elimination rules from earlier to implement the whole thing as a
1572/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001573///
Matthias Braund0412122018-12-06 01:40:23 +00001574/// As complete example:
1575/// or (or (setCA (cmp A)) (setCB (cmp B)))
1576/// (and (setCC (cmp C)) (setCD (cmp D)))"
1577/// can be reassociated to:
1578/// or (and (setCC (cmp C)) setCD (cmp D))
1579// (or (setCA (cmp A)) (setCB (cmp B)))
1580/// can be transformed to:
1581/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1582/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1583/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001584/// cmp C
1585/// ccmp D, inv(CD), CC
1586/// ccmp A, CA, inv(CD)
1587/// ccmp B, CB, inv(CA)
1588/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001589///
1590/// A counterexample is "or (and A B) (and C D)" which translates to
1591/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1592/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001593/// @{
1594
Geoff Berrye41c2df2015-07-20 22:03:52 +00001595/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001596static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1597 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001598 AArch64CC::CondCode Predicate,
1599 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001600 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001601 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001602 const bool FullFP16 =
1603 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1604
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001605 if (LHS.getValueType().isFloatingPoint()) {
1606 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001607 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001608 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1609 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1610 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001611 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001612 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001613 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001614 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001615 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1616 Opcode = AArch64ISD::CCMN;
1617 RHS = RHS.getOperand(1);
1618 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001619 }
1620 if (Opcode == 0)
1621 Opcode = AArch64ISD::CCMP;
1622
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001623 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1624 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1625 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001626 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1627 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1628}
1629
Matthias Braun96d12512018-11-06 03:15:22 +00001630/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1631/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001632/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1633/// changing the conditions on the SETCC tests.
1634/// (this means we can call emitConjunctionRec() with
1635/// Negate==true on this sub-tree)
1636/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1637/// cannot do the negation naturally. We are required to
1638/// emit the subtree first in this case.
1639/// \param WillNegate Is true if are called when the result of this
1640/// subexpression must be negated. This happens when the
1641/// outer expression is an OR. We can use this fact to know
1642/// that we have a double negation (or (or ...) ...) that
1643/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001644static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001645 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001646 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001647 if (!Val.hasOneUse())
1648 return false;
1649 unsigned Opcode = Val->getOpcode();
1650 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001651 if (Val->getOperand(0).getValueType() == MVT::f128)
1652 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001653 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001654 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001655 return true;
1656 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001657 // Protect against exponential runtime and stack overflow.
1658 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001659 return false;
1660 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001661 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001662 SDValue O0 = Val->getOperand(0);
1663 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001664 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001665 bool MustBeFirstL;
1666 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001667 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001668 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001669 bool MustBeFirstR;
1670 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001671 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001672
Matthias Braund0412122018-12-06 01:40:23 +00001673 if (MustBeFirstL && MustBeFirstR)
1674 return false;
1675
1676 if (IsOR) {
1677 // For an OR expression we need to be able to naturally negate at least
1678 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001679 if (!CanNegateL && !CanNegateR)
1680 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001681 // If we the result of the OR will be negated and we can naturally negate
1682 // the leafs, then this sub-tree as a whole negates naturally.
1683 CanNegate = WillNegate && CanNegateL && CanNegateR;
1684 // If we cannot naturally negate the whole sub-tree, then this must be
1685 // emitted first.
1686 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001687 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001688 assert(Opcode == ISD::AND && "Must be OR or AND");
1689 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001690 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001691 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001692 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001693 return true;
1694 }
1695 return false;
1696}
1697
1698/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1699/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1700/// Tries to transform the given i1 producing node @p Val to a series compare
1701/// and conditional compare operations. @returns an NZCV flags producing node
1702/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1703/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001704/// \p Negate is true if we want this sub-tree being negated just by changing
1705/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001706static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001707 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001708 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001709 // We're at a tree leaf, produce a conditional comparison operation.
1710 unsigned Opcode = Val->getOpcode();
1711 if (Opcode == ISD::SETCC) {
1712 SDValue LHS = Val->getOperand(0);
1713 SDValue RHS = Val->getOperand(1);
1714 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1715 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001716 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001717 CC = getSetCCInverse(CC, isInteger);
1718 SDLoc DL(Val);
1719 // Determine OutCC and handle FP special case.
1720 if (isInteger) {
1721 OutCC = changeIntCCToAArch64CC(CC);
1722 } else {
1723 assert(LHS.getValueType().isFloatingPoint());
1724 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001725 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1726 // Some floating point conditions can't be tested with a single condition
1727 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001728 if (ExtraCC != AArch64CC::AL) {
1729 SDValue ExtraCmp;
1730 if (!CCOp.getNode())
1731 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001732 else
1733 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001734 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001735 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001736 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001737 }
1738 }
1739
1740 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001741 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001742 return emitComparison(LHS, RHS, CC, DL, DAG);
1743 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001744 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001745 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001746 }
Matthias Braund0412122018-12-06 01:40:23 +00001747 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001748
Matthias Braund0412122018-12-06 01:40:23 +00001749 bool IsOR = Opcode == ISD::OR;
1750
Matthias Braunaf7d7702015-07-16 20:02:37 +00001751 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001752 bool CanNegateL;
1753 bool MustBeFirstL;
1754 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1755 assert(ValidL && "Valid conjunction/disjunction tree");
1756 (void)ValidL;
1757
Matthias Braunaf7d7702015-07-16 20:02:37 +00001758 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001759 bool CanNegateR;
1760 bool MustBeFirstR;
1761 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1762 assert(ValidR && "Valid conjunction/disjunction tree");
1763 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001764
Matthias Braund0412122018-12-06 01:40:23 +00001765 // Swap sub-tree that must come first to the right side.
1766 if (MustBeFirstL) {
1767 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1768 std::swap(LHS, RHS);
1769 std::swap(CanNegateL, CanNegateR);
1770 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001771 }
1772
Matthias Braund0412122018-12-06 01:40:23 +00001773 bool NegateR;
1774 bool NegateAfterR;
1775 bool NegateL;
1776 bool NegateAfterAll;
1777 if (Opcode == ISD::OR) {
1778 // Swap the sub-tree that we can negate naturally to the left.
1779 if (!CanNegateL) {
1780 assert(CanNegateR && "at least one side must be negatable");
1781 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1782 assert(!Negate);
1783 std::swap(LHS, RHS);
1784 NegateR = false;
1785 NegateAfterR = true;
1786 } else {
1787 // Negate the left sub-tree if possible, otherwise negate the result.
1788 NegateR = CanNegateR;
1789 NegateAfterR = !CanNegateR;
1790 }
1791 NegateL = true;
1792 NegateAfterAll = !Negate;
1793 } else {
1794 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1795 assert(!Negate && "Valid conjunction/disjunction tree");
1796
1797 NegateL = false;
1798 NegateR = false;
1799 NegateAfterR = false;
1800 NegateAfterAll = false;
1801 }
1802
1803 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001804 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001805 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1806 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001807 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001808 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1809 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001810 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1811 return CmpL;
1812}
1813
Matthias Braun96d12512018-11-06 03:15:22 +00001814/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1815/// In some cases this is even possible with OR operations in the expression.
1816/// See \ref AArch64CCMP.
1817/// \see emitConjunctionRec().
1818static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1819 AArch64CC::CondCode &OutCC) {
1820 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001821 bool DummyMustBeFirst;
1822 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001823 return SDValue();
1824
Matthias Braun96d12512018-11-06 03:15:22 +00001825 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001826}
1827
Matthias Braunaf7d7702015-07-16 20:02:37 +00001828/// @}
1829
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001830/// Returns how profitable it is to fold a comparison's operand's shift and/or
1831/// extension operations.
1832static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1833 auto isSupportedExtend = [&](SDValue V) {
1834 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1835 return true;
1836
1837 if (V.getOpcode() == ISD::AND)
1838 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1839 uint64_t Mask = MaskCst->getZExtValue();
1840 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1841 }
1842
1843 return false;
1844 };
1845
1846 if (!Op.hasOneUse())
1847 return 0;
1848
1849 if (isSupportedExtend(Op))
1850 return 1;
1851
1852 unsigned Opc = Op.getOpcode();
1853 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1854 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1855 uint64_t Shift = ShiftCst->getZExtValue();
1856 if (isSupportedExtend(Op.getOperand(0)))
1857 return (Shift <= 4) ? 2 : 1;
1858 EVT VT = Op.getValueType();
1859 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1860 return 1;
1861 }
1862
1863 return 0;
1864}
1865
Tim Northover3b0846e2014-05-24 12:50:23 +00001866static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001867 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001868 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001869 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1870 EVT VT = RHS.getValueType();
1871 uint64_t C = RHSC->getZExtValue();
1872 if (!isLegalArithImmed(C)) {
1873 // Constant does not fit, try adjusting it by one?
1874 switch (CC) {
1875 default:
1876 break;
1877 case ISD::SETLT:
1878 case ISD::SETGE:
1879 if ((VT == MVT::i32 && C != 0x80000000 &&
1880 isLegalArithImmed((uint32_t)(C - 1))) ||
1881 (VT == MVT::i64 && C != 0x80000000ULL &&
1882 isLegalArithImmed(C - 1ULL))) {
1883 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1884 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001885 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001886 }
1887 break;
1888 case ISD::SETULT:
1889 case ISD::SETUGE:
1890 if ((VT == MVT::i32 && C != 0 &&
1891 isLegalArithImmed((uint32_t)(C - 1))) ||
1892 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1893 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1894 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001895 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001896 }
1897 break;
1898 case ISD::SETLE:
1899 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001900 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001901 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001902 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001903 isLegalArithImmed(C + 1ULL))) {
1904 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1905 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001906 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001907 }
1908 break;
1909 case ISD::SETULE:
1910 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001911 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001912 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001913 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001914 isLegalArithImmed(C + 1ULL))) {
1915 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1916 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001917 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001918 }
1919 break;
1920 }
1921 }
1922 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001923
1924 // Comparisons are canonicalized so that the RHS operand is simpler than the
1925 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1926 // can fold some shift+extend operations on the RHS operand, so swap the
1927 // operands if that can be done.
1928 //
1929 // For example:
1930 // lsl w13, w11, #1
1931 // cmp w13, w12
1932 // can be turned into:
1933 // cmp w12, w11, lsl #1
1934 if (!isa<ConstantSDNode>(RHS) ||
1935 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1936 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1937
1938 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1939 std::swap(LHS, RHS);
1940 CC = ISD::getSetCCSwappedOperands(CC);
1941 }
1942 }
1943
Matthias Braunaf7d7702015-07-16 20:02:37 +00001944 SDValue Cmp;
1945 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001946 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001947 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1948
1949 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1950 // For the i8 operand, the largest immediate is 255, so this can be easily
1951 // encoded in the compare instruction. For the i16 operand, however, the
1952 // largest immediate cannot be encoded in the compare.
1953 // Therefore, use a sign extending load and cmn to avoid materializing the
1954 // -1 constant. For example,
1955 // movz w1, #65535
1956 // ldrh w0, [x0, #0]
1957 // cmp w0, w1
1958 // >
1959 // ldrsh w0, [x0, #0]
1960 // cmn w0, #1
1961 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1962 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001963 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001964 // transformation is profitable.
1965 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1966 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1967 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1968 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1969 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1970 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1971 SDValue SExt =
1972 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1973 DAG.getValueType(MVT::i16));
1974 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1975 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001976 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001977 AArch64CC = changeIntCCToAArch64CC(CC);
1978 }
1979 }
1980
1981 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00001982 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001983 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1984 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001985 }
1986 }
1987 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001988
1989 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001990 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001991 AArch64CC = changeIntCCToAArch64CC(CC);
1992 }
1993 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001994 return Cmp;
1995}
1996
1997static std::pair<SDValue, SDValue>
1998getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1999 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2000 "Unsupported value type");
2001 SDValue Value, Overflow;
2002 SDLoc DL(Op);
2003 SDValue LHS = Op.getOperand(0);
2004 SDValue RHS = Op.getOperand(1);
2005 unsigned Opc = 0;
2006 switch (Op.getOpcode()) {
2007 default:
2008 llvm_unreachable("Unknown overflow instruction!");
2009 case ISD::SADDO:
2010 Opc = AArch64ISD::ADDS;
2011 CC = AArch64CC::VS;
2012 break;
2013 case ISD::UADDO:
2014 Opc = AArch64ISD::ADDS;
2015 CC = AArch64CC::HS;
2016 break;
2017 case ISD::SSUBO:
2018 Opc = AArch64ISD::SUBS;
2019 CC = AArch64CC::VS;
2020 break;
2021 case ISD::USUBO:
2022 Opc = AArch64ISD::SUBS;
2023 CC = AArch64CC::LO;
2024 break;
2025 // Multiply needs a little bit extra work.
2026 case ISD::SMULO:
2027 case ISD::UMULO: {
2028 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002029 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002030 if (Op.getValueType() == MVT::i32) {
2031 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2032 // For a 32 bit multiply with overflow check we want the instruction
2033 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2034 // need to generate the following pattern:
2035 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2036 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2037 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2038 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2039 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002040 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002041 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2042 // operation. We need to clear out the upper 32 bits, because we used a
2043 // widening multiply that wrote all 64 bits. In the end this should be a
2044 // noop.
2045 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2046 if (IsSigned) {
2047 // The signed overflow check requires more than just a simple check for
2048 // any bit set in the upper 32 bits of the result. These bits could be
2049 // just the sign bits of a negative number. To perform the overflow
2050 // check we have to arithmetic shift right the 32nd bit of the result by
2051 // 31 bits. Then we compare the result to the upper 32 bits.
2052 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002053 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002054 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2055 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002056 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002057 // It is important that LowerBits is last, otherwise the arithmetic
2058 // shift will not be folded into the compare (SUBS).
2059 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2060 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2061 .getValue(1);
2062 } else {
2063 // The overflow check for unsigned multiply is easy. We only need to
2064 // check if any of the upper 32 bits are set. This can be done with a
2065 // CMP (shifted register). For that we need to generate the following
2066 // pattern:
2067 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2068 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002069 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002070 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2071 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002072 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2073 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002074 UpperBits).getValue(1);
2075 }
2076 break;
2077 }
2078 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2079 // For the 64 bit multiply
2080 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2081 if (IsSigned) {
2082 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2083 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002084 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002085 // It is important that LowerBits is last, otherwise the arithmetic
2086 // shift will not be folded into the compare (SUBS).
2087 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2088 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2089 .getValue(1);
2090 } else {
2091 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2092 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2093 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002094 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2095 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002096 UpperBits).getValue(1);
2097 }
2098 break;
2099 }
2100 } // switch (...)
2101
2102 if (Opc) {
2103 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2104
2105 // Emit the AArch64 operation with overflow check.
2106 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2107 Overflow = Value.getValue(1);
2108 }
2109 return std::make_pair(Value, Overflow);
2110}
2111
2112SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2113 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002114 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002115 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002116}
2117
Amara Emerson24ca39c2017-10-09 15:15:09 +00002118// Returns true if the given Op is the overflow flag result of an overflow
2119// intrinsic operation.
2120static bool isOverflowIntrOpRes(SDValue Op) {
2121 unsigned Opc = Op.getOpcode();
2122 return (Op.getResNo() == 1 &&
2123 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2124 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2125}
2126
Tim Northover3b0846e2014-05-24 12:50:23 +00002127static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2128 SDValue Sel = Op.getOperand(0);
2129 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002130 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002131
Amara Emerson24ca39c2017-10-09 15:15:09 +00002132 // If the operand is an overflow checking operation, invert the condition
2133 // code and kill the Not operation. I.e., transform:
2134 // (xor (overflow_op_bool, 1))
2135 // -->
2136 // (csel 1, 0, invert(cc), overflow_op_bool)
2137 // ... which later gets transformed to just a cset instruction with an
2138 // inverted condition code, rather than a cset + eor sequence.
2139 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2140 // Only lower legal XALUO ops.
2141 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2142 return SDValue();
2143
2144 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2145 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2146 AArch64CC::CondCode CC;
2147 SDValue Value, Overflow;
2148 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2149 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2150 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2151 CCVal, Overflow);
2152 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002153 // If neither operand is a SELECT_CC, give up.
2154 if (Sel.getOpcode() != ISD::SELECT_CC)
2155 std::swap(Sel, Other);
2156 if (Sel.getOpcode() != ISD::SELECT_CC)
2157 return Op;
2158
2159 // The folding we want to perform is:
2160 // (xor x, (select_cc a, b, cc, 0, -1) )
2161 // -->
2162 // (csel x, (xor x, -1), cc ...)
2163 //
2164 // The latter will get matched to a CSINV instruction.
2165
2166 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2167 SDValue LHS = Sel.getOperand(0);
2168 SDValue RHS = Sel.getOperand(1);
2169 SDValue TVal = Sel.getOperand(2);
2170 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002171
2172 // FIXME: This could be generalized to non-integer comparisons.
2173 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2174 return Op;
2175
2176 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2177 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2178
Eric Christopher572e03a2015-06-19 01:53:21 +00002179 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002180 if (!CFVal || !CTVal)
2181 return Op;
2182
2183 // We can commute the SELECT_CC by inverting the condition. This
2184 // might be needed to make this fit into a CSINV pattern.
2185 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2186 std::swap(TVal, FVal);
2187 std::swap(CTVal, CFVal);
2188 CC = ISD::getSetCCInverse(CC, true);
2189 }
2190
2191 // If the constants line up, perform the transform!
2192 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2193 SDValue CCVal;
2194 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2195
2196 FVal = Other;
2197 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002198 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002199
2200 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2201 CCVal, Cmp);
2202 }
2203
2204 return Op;
2205}
2206
2207static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2208 EVT VT = Op.getValueType();
2209
2210 // Let legalize expand this if it isn't a legal type yet.
2211 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2212 return SDValue();
2213
2214 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2215
2216 unsigned Opc;
2217 bool ExtraOp = false;
2218 switch (Op.getOpcode()) {
2219 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002220 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002221 case ISD::ADDC:
2222 Opc = AArch64ISD::ADDS;
2223 break;
2224 case ISD::SUBC:
2225 Opc = AArch64ISD::SUBS;
2226 break;
2227 case ISD::ADDE:
2228 Opc = AArch64ISD::ADCS;
2229 ExtraOp = true;
2230 break;
2231 case ISD::SUBE:
2232 Opc = AArch64ISD::SBCS;
2233 ExtraOp = true;
2234 break;
2235 }
2236
2237 if (!ExtraOp)
2238 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2239 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2240 Op.getOperand(2));
2241}
2242
2243static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2244 // Let legalize expand this if it isn't a legal type yet.
2245 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2246 return SDValue();
2247
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002248 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002249 AArch64CC::CondCode CC;
2250 // The actual operation that sets the overflow or carry flag.
2251 SDValue Value, Overflow;
2252 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2253
2254 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002255 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2256 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002257
2258 // We use an inverted condition, because the conditional select is inverted
2259 // too. This will allow it to be selected to a single instruction:
2260 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002261 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2262 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002263 CCVal, Overflow);
2264
2265 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002266 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002267}
2268
2269// Prefetch operands are:
2270// 1: Address to prefetch
2271// 2: bool isWrite
2272// 3: int locality (0 = no locality ... 3 = extreme locality)
2273// 4: bool isDataCache
2274static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2275 SDLoc DL(Op);
2276 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2277 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002278 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002279
2280 bool IsStream = !Locality;
2281 // When the locality number is set
2282 if (Locality) {
2283 // The front-end should have filtered out the out-of-range values
2284 assert(Locality <= 3 && "Prefetch locality out-of-range");
2285 // The locality degree is the opposite of the cache speed.
2286 // Put the number the other way around.
2287 // The encoding starts at 0 for level 1
2288 Locality = 3 - Locality;
2289 }
2290
2291 // built the mask value encoding the expected behavior.
2292 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002293 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002294 (Locality << 1) | // Cache level bits
2295 (unsigned)IsStream; // Stream bit
2296 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002297 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002298}
2299
2300SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2301 SelectionDAG &DAG) const {
2302 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2303
2304 RTLIB::Libcall LC;
2305 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2306
2307 return LowerF128Call(Op, DAG, LC);
2308}
2309
2310SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2311 SelectionDAG &DAG) const {
2312 if (Op.getOperand(0).getValueType() != MVT::f128) {
2313 // It's legal except when f128 is involved
2314 return Op;
2315 }
2316
2317 RTLIB::Libcall LC;
2318 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2319
2320 // FP_ROUND node has a second operand indicating whether it is known to be
2321 // precise. That doesn't take part in the LibCall so we can't directly use
2322 // LowerF128Call.
2323 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002324 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2325 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002326}
2327
2328static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2329 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2330 // Any additional optimization in this function should be recorded
2331 // in the cost tables.
2332 EVT InVT = Op.getOperand(0).getValueType();
2333 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002334 unsigned NumElts = InVT.getVectorNumElements();
2335
2336 // f16 vectors are promoted to f32 before a conversion.
2337 if (InVT.getVectorElementType() == MVT::f16) {
2338 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2339 SDLoc dl(Op);
2340 return DAG.getNode(
2341 Op.getOpcode(), dl, Op.getValueType(),
2342 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2343 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002344
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002345 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002346 SDLoc dl(Op);
2347 SDValue Cv =
2348 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2349 Op.getOperand(0));
2350 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002351 }
2352
2353 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002354 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002355 MVT ExtVT =
2356 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2357 VT.getVectorNumElements());
2358 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002359 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2360 }
2361
2362 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002363 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002364}
2365
2366SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2367 SelectionDAG &DAG) const {
2368 if (Op.getOperand(0).getValueType().isVector())
2369 return LowerVectorFP_TO_INT(Op, DAG);
2370
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002371 // f16 conversions are promoted to f32 when full fp16 is not supported.
2372 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2373 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002374 SDLoc dl(Op);
2375 return DAG.getNode(
2376 Op.getOpcode(), dl, Op.getValueType(),
2377 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2378 }
2379
Tim Northover3b0846e2014-05-24 12:50:23 +00002380 if (Op.getOperand(0).getValueType() != MVT::f128) {
2381 // It's legal except when f128 is involved
2382 return Op;
2383 }
2384
2385 RTLIB::Libcall LC;
2386 if (Op.getOpcode() == ISD::FP_TO_SINT)
2387 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2388 else
2389 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2390
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002391 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002392 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002393}
2394
2395static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2396 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2397 // Any additional optimization in this function should be recorded
2398 // in the cost tables.
2399 EVT VT = Op.getValueType();
2400 SDLoc dl(Op);
2401 SDValue In = Op.getOperand(0);
2402 EVT InVT = In.getValueType();
2403
Tim Northoveref0d7602014-06-15 09:27:06 +00002404 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2405 MVT CastVT =
2406 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2407 InVT.getVectorNumElements());
2408 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002409 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002410 }
2411
Tim Northoveref0d7602014-06-15 09:27:06 +00002412 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2413 unsigned CastOpc =
2414 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2415 EVT CastVT = VT.changeVectorElementTypeToInteger();
2416 In = DAG.getNode(CastOpc, dl, CastVT, In);
2417 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002418 }
2419
Tim Northoveref0d7602014-06-15 09:27:06 +00002420 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002421}
2422
2423SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2424 SelectionDAG &DAG) const {
2425 if (Op.getValueType().isVector())
2426 return LowerVectorINT_TO_FP(Op, DAG);
2427
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002428 // f16 conversions are promoted to f32 when full fp16 is not supported.
2429 if (Op.getValueType() == MVT::f16 &&
2430 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002431 SDLoc dl(Op);
2432 return DAG.getNode(
2433 ISD::FP_ROUND, dl, MVT::f16,
2434 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002435 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002436 }
2437
Tim Northover3b0846e2014-05-24 12:50:23 +00002438 // i128 conversions are libcalls.
2439 if (Op.getOperand(0).getValueType() == MVT::i128)
2440 return SDValue();
2441
2442 // Other conversions are legal, unless it's to the completely software-based
2443 // fp128.
2444 if (Op.getValueType() != MVT::f128)
2445 return Op;
2446
2447 RTLIB::Libcall LC;
2448 if (Op.getOpcode() == ISD::SINT_TO_FP)
2449 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2450 else
2451 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2452
2453 return LowerF128Call(Op, DAG, LC);
2454}
2455
2456SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2457 SelectionDAG &DAG) const {
2458 // For iOS, we want to call an alternative entry point: __sincos_stret,
2459 // which returns the values in two S / D registers.
2460 SDLoc dl(Op);
2461 SDValue Arg = Op.getOperand(0);
2462 EVT ArgVT = Arg.getValueType();
2463 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2464
2465 ArgListTy Args;
2466 ArgListEntry Entry;
2467
2468 Entry.Node = Arg;
2469 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002470 Entry.IsSExt = false;
2471 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002472 Args.push_back(Entry);
2473
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002474 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2475 : RTLIB::SINCOS_STRET_F32;
2476 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002477 SDValue Callee =
2478 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002479
Serge Gueltone38003f2017-05-09 19:31:13 +00002480 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002481 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002482 CLI.setDebugLoc(dl)
2483 .setChain(DAG.getEntryNode())
2484 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002485
2486 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2487 return CallResult.first;
2488}
2489
Tim Northoverf8bfe212014-07-18 13:07:05 +00002490static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2491 if (Op.getValueType() != MVT::f16)
2492 return SDValue();
2493
2494 assert(Op.getOperand(0).getValueType() == MVT::i16);
2495 SDLoc DL(Op);
2496
2497 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2498 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2499 return SDValue(
2500 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002501 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002502 0);
2503}
2504
Chad Rosierd9d0f862014-10-08 02:31:24 +00002505static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2506 if (OrigVT.getSizeInBits() >= 64)
2507 return OrigVT;
2508
2509 assert(OrigVT.isSimple() && "Expecting a simple value type");
2510
2511 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2512 switch (OrigSimpleTy) {
2513 default: llvm_unreachable("Unexpected Vector Type");
2514 case MVT::v2i8:
2515 case MVT::v2i16:
2516 return MVT::v2i32;
2517 case MVT::v4i8:
2518 return MVT::v4i16;
2519 }
2520}
2521
2522static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2523 const EVT &OrigTy,
2524 const EVT &ExtTy,
2525 unsigned ExtOpcode) {
2526 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2527 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2528 // 64-bits we need to insert a new extension so that it will be 64-bits.
2529 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2530 if (OrigTy.getSizeInBits() >= 64)
2531 return N;
2532
2533 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2534 EVT NewVT = getExtensionTo64Bits(OrigTy);
2535
2536 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2537}
2538
2539static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2540 bool isSigned) {
2541 EVT VT = N->getValueType(0);
2542
2543 if (N->getOpcode() != ISD::BUILD_VECTOR)
2544 return false;
2545
Pete Cooper3af9a252015-06-26 18:17:36 +00002546 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002547 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002548 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002549 unsigned HalfSize = EltSize / 2;
2550 if (isSigned) {
2551 if (!isIntN(HalfSize, C->getSExtValue()))
2552 return false;
2553 } else {
2554 if (!isUIntN(HalfSize, C->getZExtValue()))
2555 return false;
2556 }
2557 continue;
2558 }
2559 return false;
2560 }
2561
2562 return true;
2563}
2564
2565static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2566 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2567 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2568 N->getOperand(0)->getValueType(0),
2569 N->getValueType(0),
2570 N->getOpcode());
2571
2572 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2573 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002574 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002575 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002576 unsigned NumElts = VT.getVectorNumElements();
2577 MVT TruncVT = MVT::getIntegerVT(EltSize);
2578 SmallVector<SDValue, 8> Ops;
2579 for (unsigned i = 0; i != NumElts; ++i) {
2580 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2581 const APInt &CInt = C->getAPIntValue();
2582 // Element types smaller than 32 bits are not legal, so use i32 elements.
2583 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002584 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002585 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002586 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002587}
2588
2589static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002590 return N->getOpcode() == ISD::SIGN_EXTEND ||
2591 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002592}
2593
2594static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002595 return N->getOpcode() == ISD::ZERO_EXTEND ||
2596 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002597}
2598
2599static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2600 unsigned Opcode = N->getOpcode();
2601 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2602 SDNode *N0 = N->getOperand(0).getNode();
2603 SDNode *N1 = N->getOperand(1).getNode();
2604 return N0->hasOneUse() && N1->hasOneUse() &&
2605 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2606 }
2607 return false;
2608}
2609
2610static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2611 unsigned Opcode = N->getOpcode();
2612 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2613 SDNode *N0 = N->getOperand(0).getNode();
2614 SDNode *N1 = N->getOperand(1).getNode();
2615 return N0->hasOneUse() && N1->hasOneUse() &&
2616 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2617 }
2618 return false;
2619}
2620
Tim Northover70666e72018-06-20 12:09:01 +00002621SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2622 SelectionDAG &DAG) const {
2623 // The rounding mode is in bits 23:22 of the FPSCR.
2624 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2625 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2626 // so that the shift + and get folded into a bitfield extract.
2627 SDLoc dl(Op);
2628
2629 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2630 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2631 MVT::i64));
2632 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2633 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2634 DAG.getConstant(1U << 22, dl, MVT::i32));
2635 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2636 DAG.getConstant(22, dl, MVT::i32));
2637 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2638 DAG.getConstant(3, dl, MVT::i32));
2639}
2640
Chad Rosierd9d0f862014-10-08 02:31:24 +00002641static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2642 // Multiplications are only custom-lowered for 128-bit vectors so that
2643 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2644 EVT VT = Op.getValueType();
2645 assert(VT.is128BitVector() && VT.isInteger() &&
2646 "unexpected type for custom-lowering ISD::MUL");
2647 SDNode *N0 = Op.getOperand(0).getNode();
2648 SDNode *N1 = Op.getOperand(1).getNode();
2649 unsigned NewOpc = 0;
2650 bool isMLA = false;
2651 bool isN0SExt = isSignExtended(N0, DAG);
2652 bool isN1SExt = isSignExtended(N1, DAG);
2653 if (isN0SExt && isN1SExt)
2654 NewOpc = AArch64ISD::SMULL;
2655 else {
2656 bool isN0ZExt = isZeroExtended(N0, DAG);
2657 bool isN1ZExt = isZeroExtended(N1, DAG);
2658 if (isN0ZExt && isN1ZExt)
2659 NewOpc = AArch64ISD::UMULL;
2660 else if (isN1SExt || isN1ZExt) {
2661 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2662 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2663 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2664 NewOpc = AArch64ISD::SMULL;
2665 isMLA = true;
2666 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2667 NewOpc = AArch64ISD::UMULL;
2668 isMLA = true;
2669 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2670 std::swap(N0, N1);
2671 NewOpc = AArch64ISD::UMULL;
2672 isMLA = true;
2673 }
2674 }
2675
2676 if (!NewOpc) {
2677 if (VT == MVT::v2i64)
2678 // Fall through to expand this. It is not legal.
2679 return SDValue();
2680 else
2681 // Other vector multiplications are legal.
2682 return Op;
2683 }
2684 }
2685
2686 // Legalize to a S/UMULL instruction
2687 SDLoc DL(Op);
2688 SDValue Op0;
2689 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2690 if (!isMLA) {
2691 Op0 = skipExtensionForVectorMULL(N0, DAG);
2692 assert(Op0.getValueType().is64BitVector() &&
2693 Op1.getValueType().is64BitVector() &&
2694 "unexpected types for extended operands to VMULL");
2695 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2696 }
2697 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2698 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2699 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2700 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2701 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2702 EVT Op1VT = Op1.getValueType();
2703 return DAG.getNode(N0->getOpcode(), DL, VT,
2704 DAG.getNode(NewOpc, DL, VT,
2705 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2706 DAG.getNode(NewOpc, DL, VT,
2707 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2708}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002709
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002710SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2711 SelectionDAG &DAG) const {
2712 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2713 SDLoc dl(Op);
2714 switch (IntNo) {
2715 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002716 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002717 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2718 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2719 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002720 case Intrinsic::aarch64_neon_abs: {
2721 EVT Ty = Op.getValueType();
2722 if (Ty == MVT::i64) {
2723 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2724 Op.getOperand(1));
2725 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2726 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2727 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2728 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2729 } else {
2730 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2731 }
2732 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002733 case Intrinsic::aarch64_neon_smax:
2734 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2735 Op.getOperand(1), Op.getOperand(2));
2736 case Intrinsic::aarch64_neon_umax:
2737 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2738 Op.getOperand(1), Op.getOperand(2));
2739 case Intrinsic::aarch64_neon_smin:
2740 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2741 Op.getOperand(1), Op.getOperand(2));
2742 case Intrinsic::aarch64_neon_umin:
2743 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2744 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002745
2746 case Intrinsic::localaddress: {
2747 // Returns one of the stack, base, or frame pointer registers, depending on
2748 // which is used to reference local variables.
2749 MachineFunction &MF = DAG.getMachineFunction();
2750 const AArch64RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2751 unsigned Reg;
2752 if (RegInfo->hasBasePointer(MF))
2753 Reg = RegInfo->getBaseRegister();
2754 else // This function handles the SP or FP case.
2755 Reg = RegInfo->getFrameRegister(MF);
2756 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2757 Op.getSimpleValueType());
2758 }
2759
2760 case Intrinsic::eh_recoverfp: {
2761 // FIXME: This needs to be implemented to correctly handle highly aligned
2762 // stack objects. For now we simply return the incoming FP. Refer D53541
2763 // for more details.
2764 SDValue FnOp = Op.getOperand(1);
2765 SDValue IncomingFPOp = Op.getOperand(2);
2766 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2767 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2768 if (!Fn)
2769 report_fatal_error(
2770 "llvm.eh.recoverfp must take a function as the first argument");
2771 return IncomingFPOp;
2772 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002773 }
2774}
2775
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002776// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2777static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2778 EVT VT, EVT MemVT,
2779 SelectionDAG &DAG) {
2780 assert(VT.isVector() && "VT should be a vector type");
2781 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2782
2783 SDValue Value = ST->getValue();
2784
2785 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2786 // the word lane which represent the v4i8 subvector. It optimizes the store
2787 // to:
2788 //
2789 // xtn v0.8b, v0.8h
2790 // str s0, [x0]
2791
2792 SDValue Undef = DAG.getUNDEF(MVT::i16);
2793 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2794 {Undef, Undef, Undef, Undef});
2795
2796 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2797 Value, UndefVec);
2798 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2799
2800 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2801 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2802 Trunc, DAG.getConstant(0, DL, MVT::i64));
2803
2804 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2805 ST->getBasePtr(), ST->getMemOperand());
2806}
2807
2808// Custom lowering for any store, vector or scalar and/or default or with
2809// a truncate operations. Currently only custom lower truncate operation
2810// from vector v4i16 to v4i8.
2811SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2812 SelectionDAG &DAG) const {
2813 SDLoc Dl(Op);
2814 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2815 assert (StoreNode && "Can only custom lower store nodes");
2816
2817 SDValue Value = StoreNode->getValue();
2818
2819 EVT VT = Value.getValueType();
2820 EVT MemVT = StoreNode->getMemoryVT();
2821
2822 assert (VT.isVector() && "Can only custom lower vector store types");
2823
2824 unsigned AS = StoreNode->getAddressSpace();
2825 unsigned Align = StoreNode->getAlignment();
2826 if (Align < MemVT.getStoreSize() &&
2827 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2828 return scalarizeVectorStore(StoreNode, DAG);
2829 }
2830
2831 if (StoreNode->isTruncatingStore()) {
2832 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2833 }
2834
2835 return SDValue();
2836}
2837
Tim Northover3b0846e2014-05-24 12:50:23 +00002838SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2839 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002840 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2841 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002842
Tim Northover3b0846e2014-05-24 12:50:23 +00002843 switch (Op.getOpcode()) {
2844 default:
2845 llvm_unreachable("unimplemented operand");
2846 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002847 case ISD::BITCAST:
2848 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002849 case ISD::GlobalAddress:
2850 return LowerGlobalAddress(Op, DAG);
2851 case ISD::GlobalTLSAddress:
2852 return LowerGlobalTLSAddress(Op, DAG);
2853 case ISD::SETCC:
2854 return LowerSETCC(Op, DAG);
2855 case ISD::BR_CC:
2856 return LowerBR_CC(Op, DAG);
2857 case ISD::SELECT:
2858 return LowerSELECT(Op, DAG);
2859 case ISD::SELECT_CC:
2860 return LowerSELECT_CC(Op, DAG);
2861 case ISD::JumpTable:
2862 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002863 case ISD::BR_JT:
2864 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002865 case ISD::ConstantPool:
2866 return LowerConstantPool(Op, DAG);
2867 case ISD::BlockAddress:
2868 return LowerBlockAddress(Op, DAG);
2869 case ISD::VASTART:
2870 return LowerVASTART(Op, DAG);
2871 case ISD::VACOPY:
2872 return LowerVACOPY(Op, DAG);
2873 case ISD::VAARG:
2874 return LowerVAARG(Op, DAG);
2875 case ISD::ADDC:
2876 case ISD::ADDE:
2877 case ISD::SUBC:
2878 case ISD::SUBE:
2879 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2880 case ISD::SADDO:
2881 case ISD::UADDO:
2882 case ISD::SSUBO:
2883 case ISD::USUBO:
2884 case ISD::SMULO:
2885 case ISD::UMULO:
2886 return LowerXALUO(Op, DAG);
2887 case ISD::FADD:
2888 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2889 case ISD::FSUB:
2890 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2891 case ISD::FMUL:
2892 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2893 case ISD::FDIV:
2894 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2895 case ISD::FP_ROUND:
2896 return LowerFP_ROUND(Op, DAG);
2897 case ISD::FP_EXTEND:
2898 return LowerFP_EXTEND(Op, DAG);
2899 case ISD::FRAMEADDR:
2900 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002901 case ISD::SPONENTRY:
2902 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002903 case ISD::RETURNADDR:
2904 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002905 case ISD::ADDROFRETURNADDR:
2906 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002907 case ISD::INSERT_VECTOR_ELT:
2908 return LowerINSERT_VECTOR_ELT(Op, DAG);
2909 case ISD::EXTRACT_VECTOR_ELT:
2910 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2911 case ISD::BUILD_VECTOR:
2912 return LowerBUILD_VECTOR(Op, DAG);
2913 case ISD::VECTOR_SHUFFLE:
2914 return LowerVECTOR_SHUFFLE(Op, DAG);
2915 case ISD::EXTRACT_SUBVECTOR:
2916 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2917 case ISD::SRA:
2918 case ISD::SRL:
2919 case ISD::SHL:
2920 return LowerVectorSRA_SRL_SHL(Op, DAG);
2921 case ISD::SHL_PARTS:
2922 return LowerShiftLeftParts(Op, DAG);
2923 case ISD::SRL_PARTS:
2924 case ISD::SRA_PARTS:
2925 return LowerShiftRightParts(Op, DAG);
2926 case ISD::CTPOP:
2927 return LowerCTPOP(Op, DAG);
2928 case ISD::FCOPYSIGN:
2929 return LowerFCOPYSIGN(Op, DAG);
2930 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002931 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002932 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002933 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002934 case ISD::XOR:
2935 return LowerXOR(Op, DAG);
2936 case ISD::PREFETCH:
2937 return LowerPREFETCH(Op, DAG);
2938 case ISD::SINT_TO_FP:
2939 case ISD::UINT_TO_FP:
2940 return LowerINT_TO_FP(Op, DAG);
2941 case ISD::FP_TO_SINT:
2942 case ISD::FP_TO_UINT:
2943 return LowerFP_TO_INT(Op, DAG);
2944 case ISD::FSINCOS:
2945 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002946 case ISD::FLT_ROUNDS_:
2947 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002948 case ISD::MUL:
2949 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002950 case ISD::INTRINSIC_WO_CHAIN:
2951 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002952 case ISD::STORE:
2953 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002954 case ISD::VECREDUCE_ADD:
2955 case ISD::VECREDUCE_SMAX:
2956 case ISD::VECREDUCE_SMIN:
2957 case ISD::VECREDUCE_UMAX:
2958 case ISD::VECREDUCE_UMIN:
2959 case ISD::VECREDUCE_FMAX:
2960 case ISD::VECREDUCE_FMIN:
2961 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002962 case ISD::ATOMIC_LOAD_SUB:
2963 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002964 case ISD::ATOMIC_LOAD_AND:
2965 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002966 case ISD::DYNAMIC_STACKALLOC:
2967 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002968 }
2969}
2970
Tim Northover3b0846e2014-05-24 12:50:23 +00002971//===----------------------------------------------------------------------===//
2972// Calling Convention Implementation
2973//===----------------------------------------------------------------------===//
2974
Robin Morisset039781e2014-08-29 21:53:01 +00002975/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002976CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2977 bool IsVarArg) const {
2978 switch (CC) {
2979 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002980 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002981 case CallingConv::WebKit_JS:
2982 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002983 case CallingConv::GHC:
2984 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002985 case CallingConv::C:
2986 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002987 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002988 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002989 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002990 if (Subtarget->isTargetWindows() && IsVarArg)
2991 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002992 if (!Subtarget->isTargetDarwin())
2993 return CC_AArch64_AAPCS;
2994 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002995 case CallingConv::Win64:
2996 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00002997 case CallingConv::AArch64_VectorCall:
2998 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002999 }
3000}
3001
Tim Northover406024a2016-08-10 21:44:01 +00003002CCAssignFn *
3003AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3004 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3005 : RetCC_AArch64_AAPCS;
3006}
3007
Tim Northover3b0846e2014-05-24 12:50:23 +00003008SDValue AArch64TargetLowering::LowerFormalArguments(
3009 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003010 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3011 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003012 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003013 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003014 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003015
3016 // Assign locations to all of the incoming arguments.
3017 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003018 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3019 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003020
3021 // At this point, Ins[].VT may already be promoted to i32. To correctly
3022 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3023 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3024 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3025 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3026 // LocVT.
3027 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003028 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003029 unsigned CurArgIdx = 0;
3030 for (unsigned i = 0; i != NumArgs; ++i) {
3031 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003032 if (Ins[i].isOrigArg()) {
3033 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3034 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003035
Andrew Trick05938a52015-02-16 18:10:47 +00003036 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003037 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3038 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003039 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3040 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3041 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3042 ValVT = MVT::i8;
3043 else if (ActualMVT == MVT::i16)
3044 ValVT = MVT::i16;
3045 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003046 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3047 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003048 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003049 assert(!Res && "Call operand has unhandled type");
3050 (void)Res;
3051 }
3052 assert(ArgLocs.size() == Ins.size());
3053 SmallVector<SDValue, 16> ArgValues;
3054 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3055 CCValAssign &VA = ArgLocs[i];
3056
3057 if (Ins[i].Flags.isByVal()) {
3058 // Byval is used for HFAs in the PCS, but the system should work in a
3059 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003060 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003061 int Size = Ins[i].Flags.getByValSize();
3062 unsigned NumRegs = (Size + 7) / 8;
3063
3064 // FIXME: This works on big-endian for composite byvals, which are the common
3065 // case. It should also work for fundamental types too.
3066 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003067 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003068 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003069 InVals.push_back(FrameIdxN);
3070
3071 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003072 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003073
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003074 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003075 // Arguments stored in registers.
3076 EVT RegVT = VA.getLocVT();
3077
3078 SDValue ArgValue;
3079 const TargetRegisterClass *RC;
3080
3081 if (RegVT == MVT::i32)
3082 RC = &AArch64::GPR32RegClass;
3083 else if (RegVT == MVT::i64)
3084 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003085 else if (RegVT == MVT::f16)
3086 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003087 else if (RegVT == MVT::f32)
3088 RC = &AArch64::FPR32RegClass;
3089 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3090 RC = &AArch64::FPR64RegClass;
3091 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3092 RC = &AArch64::FPR128RegClass;
3093 else
3094 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3095
3096 // Transform the arguments in physical registers into virtual ones.
3097 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3098 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3099
3100 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3101 // to 64 bits. Insert an assert[sz]ext to capture this, then
3102 // truncate to the right size.
3103 switch (VA.getLocInfo()) {
3104 default:
3105 llvm_unreachable("Unknown loc info!");
3106 case CCValAssign::Full:
3107 break;
3108 case CCValAssign::BCvt:
3109 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3110 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003111 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003112 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003113 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003114 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3115 // nodes after our lowering.
3116 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003117 break;
3118 }
3119
3120 InVals.push_back(ArgValue);
3121
3122 } else { // VA.isRegLoc()
3123 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3124 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003125 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003126
3127 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003128 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3129 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003130 BEAlign = 8 - ArgSize;
3131
Matthias Braun941a7052016-07-28 18:40:00 +00003132 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003133
3134 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003135 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003136 SDValue ArgValue;
3137
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003138 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003139 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003140 MVT MemVT = VA.getValVT();
3141
Tim Northover47e003c2014-05-26 17:21:53 +00003142 switch (VA.getLocInfo()) {
3143 default:
3144 break;
Tim Northover6890add2014-06-03 13:54:53 +00003145 case CCValAssign::BCvt:
3146 MemVT = VA.getLocVT();
3147 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003148 case CCValAssign::SExt:
3149 ExtType = ISD::SEXTLOAD;
3150 break;
3151 case CCValAssign::ZExt:
3152 ExtType = ISD::ZEXTLOAD;
3153 break;
3154 case CCValAssign::AExt:
3155 ExtType = ISD::EXTLOAD;
3156 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003157 }
3158
Alex Lorenze40c8a22015-08-11 23:09:45 +00003159 ArgValue = DAG.getExtLoad(
3160 ExtType, DL, VA.getLocVT(), Chain, FIN,
3161 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003162 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003163
Tim Northover3b0846e2014-05-24 12:50:23 +00003164 InVals.push_back(ArgValue);
3165 }
3166 }
3167
3168 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003169 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003170 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003171 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003172 // The AAPCS variadic function ABI is identical to the non-variadic
3173 // one. As a result there may be more arguments in registers and we should
3174 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003175 // Win64 variadic functions also pass arguments in registers, but all float
3176 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003177 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3178 }
3179
Tim Northover3b0846e2014-05-24 12:50:23 +00003180 // This will point to the next argument passed via stack.
3181 unsigned StackOffset = CCInfo.getNextStackOffset();
3182 // We currently pass all varargs at 8-byte alignment.
3183 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003184 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003185
3186 if (MFI.hasMustTailInVarArgFunc()) {
3187 SmallVector<MVT, 2> RegParmTypes;
3188 RegParmTypes.push_back(MVT::i64);
3189 RegParmTypes.push_back(MVT::f128);
3190 // Compute the set of forwarded registers. The rest are scratch.
3191 SmallVectorImpl<ForwardedRegister> &Forwards =
3192 FuncInfo->getForwardedMustTailRegParms();
3193 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3194 CC_AArch64_AAPCS);
3195 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003196 }
3197
Tim Northover3b0846e2014-05-24 12:50:23 +00003198 unsigned StackArgSize = CCInfo.getNextStackOffset();
3199 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3200 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3201 // This is a non-standard ABI so by fiat I say we're allowed to make full
3202 // use of the stack area to be popped, which must be aligned to 16 bytes in
3203 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003204 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003205
3206 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3207 // a multiple of 16.
3208 FuncInfo->setArgumentStackToRestore(StackArgSize);
3209
3210 // This realignment carries over to the available bytes below. Our own
3211 // callers will guarantee the space is free by giving an aligned value to
3212 // CALLSEQ_START.
3213 }
3214 // Even if we're not expected to free up the space, it's useful to know how
3215 // much is there while considering tail calls (because we can reuse it).
3216 FuncInfo->setBytesInStackArgArea(StackArgSize);
3217
Tri Vo6c47c622018-09-22 22:17:50 +00003218 if (Subtarget->hasCustomCallingConv())
3219 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3220
Tim Northover3b0846e2014-05-24 12:50:23 +00003221 return Chain;
3222}
3223
3224void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003225 SelectionDAG &DAG,
3226 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003227 SDValue &Chain) const {
3228 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003229 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003230 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003231 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003232 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003233
3234 SmallVector<SDValue, 8> MemOps;
3235
3236 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3237 AArch64::X3, AArch64::X4, AArch64::X5,
3238 AArch64::X6, AArch64::X7 };
3239 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003240 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003241
3242 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3243 int GPRIdx = 0;
3244 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003245 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003246 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003247 if (GPRSaveSize & 15)
3248 // The extra size here, if triggered, will always be 8.
3249 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3250 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003251 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003252
Mehdi Amini44ede332015-07-09 02:09:04 +00003253 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003254
3255 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3256 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3257 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003258 SDValue Store = DAG.getStore(
3259 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003260 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003261 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3262 GPRIdx,
3263 (i - FirstVariadicGPR) * 8)
3264 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003265 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003266 FIN =
3267 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003268 }
3269 }
3270 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3271 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3272
Martin Storsjo2f24e932017-07-17 20:05:19 +00003273 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003274 static const MCPhysReg FPRArgRegs[] = {
3275 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3276 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3277 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003278 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003279
3280 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3281 int FPRIdx = 0;
3282 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003283 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003284
Mehdi Amini44ede332015-07-09 02:09:04 +00003285 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003286
3287 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3288 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3289 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3290
Alex Lorenze40c8a22015-08-11 23:09:45 +00003291 SDValue Store = DAG.getStore(
3292 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003293 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003294 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003295 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3296 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003297 }
3298 }
3299 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3300 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3301 }
3302
3303 if (!MemOps.empty()) {
3304 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3305 }
3306}
3307
3308/// LowerCallResult - Lower the result values of a call into the
3309/// appropriate copies out of appropriate physical registers.
3310SDValue AArch64TargetLowering::LowerCallResult(
3311 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003312 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3313 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003314 SDValue ThisVal) const {
3315 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3316 ? RetCC_AArch64_WebKit_JS
3317 : RetCC_AArch64_AAPCS;
3318 // Assign locations to each value returned by this call.
3319 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003320 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3321 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003322 CCInfo.AnalyzeCallResult(Ins, RetCC);
3323
3324 // Copy all of the result registers out of their specified physreg.
3325 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3326 CCValAssign VA = RVLocs[i];
3327
3328 // Pass 'this' value directly from the argument to return value, to avoid
3329 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003330 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003331 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3332 "unexpected return calling convention register assignment");
3333 InVals.push_back(ThisVal);
3334 continue;
3335 }
3336
3337 SDValue Val =
3338 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3339 Chain = Val.getValue(1);
3340 InFlag = Val.getValue(2);
3341
3342 switch (VA.getLocInfo()) {
3343 default:
3344 llvm_unreachable("Unknown loc info!");
3345 case CCValAssign::Full:
3346 break;
3347 case CCValAssign::BCvt:
3348 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3349 break;
3350 }
3351
3352 InVals.push_back(Val);
3353 }
3354
3355 return Chain;
3356}
3357
Matthias Braun1af14142016-09-13 19:27:38 +00003358/// Return true if the calling convention is one that we can guarantee TCO for.
3359static bool canGuaranteeTCO(CallingConv::ID CC) {
3360 return CC == CallingConv::Fast;
3361}
3362
3363/// Return true if we might ever do TCO for calls with this calling convention.
3364static bool mayTailCallThisCC(CallingConv::ID CC) {
3365 switch (CC) {
3366 case CallingConv::C:
3367 case CallingConv::PreserveMost:
3368 case CallingConv::Swift:
3369 return true;
3370 default:
3371 return canGuaranteeTCO(CC);
3372 }
3373}
3374
Tim Northover3b0846e2014-05-24 12:50:23 +00003375bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3376 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003377 const SmallVectorImpl<ISD::OutputArg> &Outs,
3378 const SmallVectorImpl<SDValue> &OutVals,
3379 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003380 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003381 return false;
3382
Matthias Braun8d414362016-03-30 22:46:04 +00003383 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003384 const Function &CallerF = MF.getFunction();
3385 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003386 bool CCMatch = CallerCC == CalleeCC;
3387
3388 // Byval parameters hand the function a pointer directly into the stack area
3389 // we want to reuse during a tail call. Working around this *is* possible (see
3390 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003391 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3392 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003393 i != e; ++i)
3394 if (i->hasByValAttr())
3395 return false;
3396
Matthias Braun1af14142016-09-13 19:27:38 +00003397 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3398 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003399
Oliver Stannard12993dd2014-08-18 12:42:15 +00003400 // Externally-defined functions with weak linkage should not be
3401 // tail-called on AArch64 when the OS does not support dynamic
3402 // pre-emption of symbols, as the AAELF spec requires normal calls
3403 // to undefined weak functions to be replaced with a NOP or jump to the
3404 // next instruction. The behaviour of branch instructions in this
3405 // situation (as used for tail calls) is implementation-defined, so we
3406 // cannot rely on the linker replacing the tail call with a return.
3407 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3408 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003409 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003410 if (GV->hasExternalWeakLinkage() &&
3411 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003412 return false;
3413 }
3414
Tim Northover3b0846e2014-05-24 12:50:23 +00003415 // Now we search for cases where we can use a tail call without changing the
3416 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3417 // concept.
3418
3419 // I want anyone implementing a new calling convention to think long and hard
3420 // about this assert.
3421 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3422 "Unexpected variadic calling convention");
3423
Matthias Braun8d414362016-03-30 22:46:04 +00003424 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003425 if (isVarArg && !Outs.empty()) {
3426 // At least two cases here: if caller is fastcc then we can't have any
3427 // memory arguments (we'd be expected to clean up the stack afterwards). If
3428 // caller is C then we could potentially use its argument area.
3429
3430 // FIXME: for now we take the most conservative of these in both cases:
3431 // disallow all variadic memory operands.
3432 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003433 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003434
3435 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003436 for (const CCValAssign &ArgLoc : ArgLocs)
3437 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003438 return false;
3439 }
3440
Matthias Braun8d414362016-03-30 22:46:04 +00003441 // Check that the call results are passed in the same way.
3442 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3443 CCAssignFnForCall(CalleeCC, isVarArg),
3444 CCAssignFnForCall(CallerCC, isVarArg)))
3445 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003446 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003447 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3448 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003449 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003450 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003451 if (Subtarget->hasCustomCallingConv()) {
3452 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3453 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3454 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003455 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003456 return false;
3457 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003458
3459 // Nothing more to check if the callee is taking no arguments
3460 if (Outs.empty())
3461 return true;
3462
3463 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003464 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003465
3466 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3467
3468 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3469
Matthias Braun74a0bd32016-04-13 21:43:16 +00003470 // If the stack arguments for this call do not fit into our own save area then
3471 // the call cannot be made tail.
3472 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3473 return false;
3474
Matthias Braun46b0f032016-04-14 01:10:42 +00003475 const MachineRegisterInfo &MRI = MF.getRegInfo();
3476 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3477 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003478
3479 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003480}
3481
3482SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3483 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003484 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003485 int ClobberedFI) const {
3486 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003487 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3488 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003489
3490 // Include the original chain at the beginning of the list. When this is
3491 // used by target LowerCall hooks, this helps legalize find the
3492 // CALLSEQ_BEGIN node.
3493 ArgChains.push_back(Chain);
3494
3495 // Add a chain value for each stack argument corresponding
3496 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3497 UE = DAG.getEntryNode().getNode()->use_end();
3498 U != UE; ++U)
3499 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3500 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3501 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003502 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003503 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003504 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003505
3506 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3507 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3508 ArgChains.push_back(SDValue(L, 1));
3509 }
3510
3511 // Build a tokenfactor for all the chains.
3512 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3513}
3514
3515bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3516 bool TailCallOpt) const {
3517 return CallCC == CallingConv::Fast && TailCallOpt;
3518}
3519
Tim Northover3b0846e2014-05-24 12:50:23 +00003520/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3521/// and add input and output parameter nodes.
3522SDValue
3523AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3524 SmallVectorImpl<SDValue> &InVals) const {
3525 SelectionDAG &DAG = CLI.DAG;
3526 SDLoc &DL = CLI.DL;
3527 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3528 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3529 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3530 SDValue Chain = CLI.Chain;
3531 SDValue Callee = CLI.Callee;
3532 bool &IsTailCall = CLI.IsTailCall;
3533 CallingConv::ID CallConv = CLI.CallConv;
3534 bool IsVarArg = CLI.IsVarArg;
3535
3536 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003537 bool IsThisReturn = false;
3538
3539 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3540 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3541 bool IsSibCall = false;
3542
3543 if (IsTailCall) {
3544 // Check if it's really possible to do a tail call.
3545 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003546 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003547 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003548 report_fatal_error("failed to perform tail call elimination on a call "
3549 "site marked musttail");
3550
3551 // A sibling call is one where we're under the usual C ABI and not planning
3552 // to change that but can still do a tail call:
3553 if (!TailCallOpt && IsTailCall)
3554 IsSibCall = true;
3555
3556 if (IsTailCall)
3557 ++NumTailCalls;
3558 }
3559
3560 // Analyze operands of the call, assigning locations to each operand.
3561 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003562 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3563 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003564
3565 if (IsVarArg) {
3566 // Handle fixed and variable vector arguments differently.
3567 // Variable vector arguments always go into memory.
3568 unsigned NumArgs = Outs.size();
3569
3570 for (unsigned i = 0; i != NumArgs; ++i) {
3571 MVT ArgVT = Outs[i].VT;
3572 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3573 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3574 /*IsVarArg=*/ !Outs[i].IsFixed);
3575 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3576 assert(!Res && "Call operand has unhandled type");
3577 (void)Res;
3578 }
3579 } else {
3580 // At this point, Outs[].VT may already be promoted to i32. To correctly
3581 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3582 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3583 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3584 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3585 // LocVT.
3586 unsigned NumArgs = Outs.size();
3587 for (unsigned i = 0; i != NumArgs; ++i) {
3588 MVT ValVT = Outs[i].VT;
3589 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003590 EVT ActualVT = getValueType(DAG.getDataLayout(),
3591 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003592 /*AllowUnknown*/ true);
3593 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3594 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3595 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003596 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003597 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003598 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003599 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003600
3601 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003602 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003603 assert(!Res && "Call operand has unhandled type");
3604 (void)Res;
3605 }
3606 }
3607
3608 // Get a count of how many bytes are to be pushed on the stack.
3609 unsigned NumBytes = CCInfo.getNextStackOffset();
3610
3611 if (IsSibCall) {
3612 // Since we're not changing the ABI to make this a tail call, the memory
3613 // operands are already available in the caller's incoming argument space.
3614 NumBytes = 0;
3615 }
3616
3617 // FPDiff is the byte offset of the call's argument area from the callee's.
3618 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3619 // by this amount for a tail call. In a sibling call it must be 0 because the
3620 // caller will deallocate the entire stack and the callee still expects its
3621 // arguments to begin at SP+0. Completely unused for non-tail calls.
3622 int FPDiff = 0;
3623
3624 if (IsTailCall && !IsSibCall) {
3625 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3626
3627 // Since callee will pop argument stack as a tail call, we must keep the
3628 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003629 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003630
3631 // FPDiff will be negative if this tail call requires more space than we
3632 // would automatically have in our incoming argument space. Positive if we
3633 // can actually shrink the stack.
3634 FPDiff = NumReusableBytes - NumBytes;
3635
3636 // The stack pointer must be 16-byte aligned at all times it's used for a
3637 // memory operation, which in practice means at *all* times and in
3638 // particular across call boundaries. Therefore our own arguments started at
3639 // a 16-byte aligned SP and the delta applied for the tail call should
3640 // satisfy the same constraint.
3641 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3642 }
3643
3644 // Adjust the stack pointer for the new arguments...
3645 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003646 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003647 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003648
Mehdi Amini44ede332015-07-09 02:09:04 +00003649 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3650 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003651
3652 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3653 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003654 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003655
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003656 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3657 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3658 for (const auto &F : Forwards) {
3659 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3660 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3661 }
3662 }
3663
Tim Northover3b0846e2014-05-24 12:50:23 +00003664 // Walk the register/memloc assignments, inserting copies/loads.
3665 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3666 ++i, ++realArgIdx) {
3667 CCValAssign &VA = ArgLocs[i];
3668 SDValue Arg = OutVals[realArgIdx];
3669 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3670
3671 // Promote the value if needed.
3672 switch (VA.getLocInfo()) {
3673 default:
3674 llvm_unreachable("Unknown loc info!");
3675 case CCValAssign::Full:
3676 break;
3677 case CCValAssign::SExt:
3678 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3679 break;
3680 case CCValAssign::ZExt:
3681 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3682 break;
3683 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003684 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3685 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3686 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3687 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3688 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003689 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3690 break;
3691 case CCValAssign::BCvt:
3692 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3693 break;
3694 case CCValAssign::FPExt:
3695 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3696 break;
3697 }
3698
3699 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003700 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3701 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003702 assert(VA.getLocVT() == MVT::i64 &&
3703 "unexpected calling convention register assignment");
3704 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3705 "unexpected use of 'returned'");
3706 IsThisReturn = true;
3707 }
3708 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3709 } else {
3710 assert(VA.isMemLoc());
3711
3712 SDValue DstAddr;
3713 MachinePointerInfo DstInfo;
3714
3715 // FIXME: This works on big-endian for composite byvals, which are the
3716 // common case. It should also work for fundamental types too.
3717 uint32_t BEAlign = 0;
3718 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003719 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003720 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003721 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3722 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003723 if (OpSize < 8)
3724 BEAlign = 8 - OpSize;
3725 }
3726 unsigned LocMemOffset = VA.getLocMemOffset();
3727 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003728 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003729 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003730
3731 if (IsTailCall) {
3732 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003733 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003734
Mehdi Amini44ede332015-07-09 02:09:04 +00003735 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003736 DstInfo =
3737 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003738
3739 // Make sure any stack arguments overlapping with where we're storing
3740 // are loaded before this eventual operation. Otherwise they'll be
3741 // clobbered.
3742 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3743 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003744 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003745
Mehdi Amini44ede332015-07-09 02:09:04 +00003746 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003747 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3748 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003749 }
3750
3751 if (Outs[i].Flags.isByVal()) {
3752 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003753 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003754 SDValue Cpy = DAG.getMemcpy(
3755 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003756 /*isVol = */ false, /*AlwaysInline = */ false,
3757 /*isTailCall = */ false,
3758 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003759
3760 MemOpChains.push_back(Cpy);
3761 } else {
3762 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3763 // promoted to a legal register type i32, we should truncate Arg back to
3764 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003765 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3766 VA.getValVT() == MVT::i16)
3767 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003768
Justin Lebar9c375812016-07-15 18:27:10 +00003769 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003770 MemOpChains.push_back(Store);
3771 }
3772 }
3773 }
3774
3775 if (!MemOpChains.empty())
3776 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3777
3778 // Build a sequence of copy-to-reg nodes chained together with token chain
3779 // and flag operands which copy the outgoing args into the appropriate regs.
3780 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003781 for (auto &RegToPass : RegsToPass) {
3782 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3783 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003784 InFlag = Chain.getValue(1);
3785 }
3786
3787 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3788 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3789 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003790 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3791 auto GV = G->getGlobal();
3792 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3793 AArch64II::MO_GOT) {
3794 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3795 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003796 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3797 assert(Subtarget->isTargetWindows() &&
3798 "Windows is the only supported COFF target");
3799 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003800 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003801 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003802 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3803 }
3804 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3805 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3806 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003807 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003808 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3809 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003810 } else {
3811 const char *Sym = S->getSymbol();
3812 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003813 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003814 }
3815
3816 // We don't usually want to end the call-sequence here because we would tidy
3817 // the frame up *after* the call, however in the ABI-changing tail-call case
3818 // we've carefully laid out the parameters so that when sp is reset they'll be
3819 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003820 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003821 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3822 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003823 InFlag = Chain.getValue(1);
3824 }
3825
3826 std::vector<SDValue> Ops;
3827 Ops.push_back(Chain);
3828 Ops.push_back(Callee);
3829
3830 if (IsTailCall) {
3831 // Each tail call may have to adjust the stack by a different amount, so
3832 // this information must travel along with the operation for eventual
3833 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003834 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003835 }
3836
3837 // Add argument registers to the end of the list so that they are known live
3838 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003839 for (auto &RegToPass : RegsToPass)
3840 Ops.push_back(DAG.getRegister(RegToPass.first,
3841 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003842
3843 // Add a register mask operand representing the call-preserved registers.
3844 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003845 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003846 if (IsThisReturn) {
3847 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003848 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003849 if (!Mask) {
3850 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003851 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003852 }
3853 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003854 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003855
Tri Vo6c47c622018-09-22 22:17:50 +00003856 if (Subtarget->hasCustomCallingConv())
3857 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3858
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003859 if (TRI->isAnyArgRegReserved(MF))
3860 TRI->emitReservedArgRegCallError(MF);
3861
Tim Northover3b0846e2014-05-24 12:50:23 +00003862 assert(Mask && "Missing call preserved mask for calling convention");
3863 Ops.push_back(DAG.getRegisterMask(Mask));
3864
3865 if (InFlag.getNode())
3866 Ops.push_back(InFlag);
3867
3868 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3869
3870 // If we're doing a tall call, use a TC_RETURN here rather than an
3871 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003872 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003873 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003874 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003875 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003876
3877 // Returns a chain and a flag for retval copy to use.
3878 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3879 InFlag = Chain.getValue(1);
3880
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003881 uint64_t CalleePopBytes =
3882 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003883
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003884 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3885 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3886 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003887 if (!Ins.empty())
3888 InFlag = Chain.getValue(1);
3889
3890 // Handle result values, copying them out of physregs into vregs that we
3891 // return.
3892 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3893 InVals, IsThisReturn,
3894 IsThisReturn ? OutVals[0] : SDValue());
3895}
3896
3897bool AArch64TargetLowering::CanLowerReturn(
3898 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3899 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3900 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3901 ? RetCC_AArch64_WebKit_JS
3902 : RetCC_AArch64_AAPCS;
3903 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003904 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003905 return CCInfo.CheckReturn(Outs, RetCC);
3906}
3907
3908SDValue
3909AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3910 bool isVarArg,
3911 const SmallVectorImpl<ISD::OutputArg> &Outs,
3912 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003913 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003914 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3915 ? RetCC_AArch64_WebKit_JS
3916 : RetCC_AArch64_AAPCS;
3917 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003918 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3919 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003920 CCInfo.AnalyzeReturn(Outs, RetCC);
3921
3922 // Copy the result values into the output registers.
3923 SDValue Flag;
3924 SmallVector<SDValue, 4> RetOps(1, Chain);
3925 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3926 ++i, ++realRVLocIdx) {
3927 CCValAssign &VA = RVLocs[i];
3928 assert(VA.isRegLoc() && "Can only return in registers!");
3929 SDValue Arg = OutVals[realRVLocIdx];
3930
3931 switch (VA.getLocInfo()) {
3932 default:
3933 llvm_unreachable("Unknown loc info!");
3934 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003935 if (Outs[i].ArgVT == MVT::i1) {
3936 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3937 // value. This is strictly redundant on Darwin (which uses "zeroext
3938 // i1"), but will be optimised out before ISel.
3939 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3940 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3941 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003942 break;
3943 case CCValAssign::BCvt:
3944 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3945 break;
3946 }
3947
3948 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3949 Flag = Chain.getValue(1);
3950 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3951 }
Manman Rencbe4f942015-12-16 21:04:19 +00003952 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3953 const MCPhysReg *I =
3954 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3955 if (I) {
3956 for (; *I; ++I) {
3957 if (AArch64::GPR64RegClass.contains(*I))
3958 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3959 else if (AArch64::FPR64RegClass.contains(*I))
3960 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3961 else
3962 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3963 }
3964 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003965
3966 RetOps[0] = Chain; // Update chain.
3967
3968 // Add the flag if we have it.
3969 if (Flag.getNode())
3970 RetOps.push_back(Flag);
3971
3972 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3973}
3974
3975//===----------------------------------------------------------------------===//
3976// Other Lowering Code
3977//===----------------------------------------------------------------------===//
3978
Joel Jonesa7c4a522017-04-21 17:31:03 +00003979SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3980 SelectionDAG &DAG,
3981 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003982 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3983 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003984}
3985
3986SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3987 SelectionDAG &DAG,
3988 unsigned Flag) const {
3989 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3990}
3991
3992SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3993 SelectionDAG &DAG,
3994 unsigned Flag) const {
3995 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3996 N->getOffset(), Flag);
3997}
3998
3999SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4000 SelectionDAG &DAG,
4001 unsigned Flag) const {
4002 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4003}
4004
4005// (loadGOT sym)
4006template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004007SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4008 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004009 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004010 SDLoc DL(N);
4011 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004012 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004013 // FIXME: Once remat is capable of dealing with instructions with register
4014 // operands, expand this into two nodes instead of using a wrapper node.
4015 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4016}
4017
4018// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4019template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004020SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4021 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004022 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004023 SDLoc DL(N);
4024 EVT Ty = getPointerTy(DAG.getDataLayout());
4025 const unsigned char MO_NC = AArch64II::MO_NC;
4026 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004027 AArch64ISD::WrapperLarge, DL, Ty,
4028 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4029 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4030 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4031 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004032}
4033
4034// (addlow (adrp %hi(sym)) %lo(sym))
4035template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004036SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4037 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004038 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004039 SDLoc DL(N);
4040 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004041 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004042 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004043 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004044 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4045 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4046}
4047
David Green9dd1d452018-08-22 11:31:39 +00004048// (adr sym)
4049template <class NodeTy>
4050SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4051 unsigned Flags) const {
4052 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4053 SDLoc DL(N);
4054 EVT Ty = getPointerTy(DAG.getDataLayout());
4055 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4056 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4057}
4058
Tim Northover3b0846e2014-05-24 12:50:23 +00004059SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4060 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004061 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004062 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004063 unsigned char OpFlags =
4064 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004065
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004066 if (OpFlags != AArch64II::MO_NO_FLAG)
4067 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4068 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004069
David Green9dd1d452018-08-22 11:31:39 +00004070 // This also catches the large code model case for Darwin, and tiny code
4071 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004072 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004073 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004074 }
4075
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004076 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004077 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004078 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004079 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004080 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004081 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004082 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004083 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004084 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4085 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004086 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004087 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4088 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4089 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004090}
4091
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004092/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004093/// and calls to compute the variable's address (for Darwin, currently) and
4094/// return an SDValue containing the final node.
4095
4096/// Darwin only has one TLS scheme which must be capable of dealing with the
4097/// fully general situation, in the worst case. This means:
4098/// + "extern __thread" declaration.
4099/// + Defined in a possibly unknown dynamic library.
4100///
4101/// The general system is that each __thread variable has a [3 x i64] descriptor
4102/// which contains information used by the runtime to calculate the address. The
4103/// only part of this the compiler needs to know about is the first xword, which
4104/// contains a function pointer that must be called with the address of the
4105/// entire descriptor in "x0".
4106///
4107/// Since this descriptor may be in a different unit, in general even the
4108/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4109/// is:
4110/// adrp x0, _var@TLVPPAGE
4111/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4112/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4113/// ; the function pointer
4114/// blr x1 ; Uses descriptor address in x0
4115/// ; Address of _var is now in x0.
4116///
4117/// If the address of _var's descriptor *is* known to the linker, then it can
4118/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4119/// a slight efficiency gain.
4120SDValue
4121AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4122 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004123 assert(Subtarget->isTargetDarwin() &&
4124 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004125
4126 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004127 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004128 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4129
4130 SDValue TLVPAddr =
4131 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4132 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4133
4134 // The first entry in the descriptor is a function pointer that we must call
4135 // to obtain the address of the variable.
4136 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004137 SDValue FuncTLVGet = DAG.getLoad(
4138 MVT::i64, DL, Chain, DescAddr,
4139 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4140 /* Alignment = */ 8,
4141 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4142 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004143 Chain = FuncTLVGet.getValue(1);
4144
Matthias Braun941a7052016-07-28 18:40:00 +00004145 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4146 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004147
4148 // TLS calls preserve all registers except those that absolutely must be
4149 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4150 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004151 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4152 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4153 if (Subtarget->hasCustomCallingConv())
4154 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004155
4156 // Finally, we can make the call. This is just a degenerate version of a
4157 // normal AArch64 call node: x0 takes the address of the descriptor, and
4158 // returns the address of the variable in this thread.
4159 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4160 Chain =
4161 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4162 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4163 DAG.getRegisterMask(Mask), Chain.getValue(1));
4164 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4165}
4166
4167/// When accessing thread-local variables under either the general-dynamic or
4168/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4169/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004170/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004171///
Kristof Beylsaea84612015-03-04 09:12:08 +00004172/// The sequence is:
4173/// adrp x0, :tlsdesc:var
4174/// ldr x1, [x0, #:tlsdesc_lo12:var]
4175/// add x0, x0, #:tlsdesc_lo12:var
4176/// .tlsdesccall var
4177/// blr x1
4178/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004179///
Kristof Beylsaea84612015-03-04 09:12:08 +00004180/// The above sequence must be produced unscheduled, to enable the linker to
4181/// optimize/relax this sequence.
4182/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4183/// above sequence, and expanded really late in the compilation flow, to ensure
4184/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004185SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4186 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004187 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004188 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004189
Kristof Beylsaea84612015-03-04 09:12:08 +00004190 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004191 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004192
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004193 Chain =
4194 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004195 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004196
4197 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4198}
4199
4200SDValue
4201AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4202 SelectionDAG &DAG) const {
4203 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004204 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4205 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004206 // Different choices can be made for the maximum size of the TLS area for a
4207 // module. For the small address model, the default TLS size is 16MiB and the
4208 // maximum TLS size is 4GiB.
4209 // FIXME: add -mtls-size command line option and make it control the 16MiB
4210 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004211 // FIXME: add tiny codemodel support. We currently generate the same code as
4212 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004213 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4214
4215 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004216
Kristof Beylsaea84612015-03-04 09:12:08 +00004217 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4218 if (Model == TLSModel::LocalDynamic)
4219 Model = TLSModel::GeneralDynamic;
4220 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004221
4222 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004223 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004224 SDLoc DL(Op);
4225 const GlobalValue *GV = GA->getGlobal();
4226
4227 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4228
4229 if (Model == TLSModel::LocalExec) {
4230 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004231 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004232 SDValue LoVar = DAG.getTargetGlobalAddress(
4233 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004234 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004235
Kristof Beylsaea84612015-03-04 09:12:08 +00004236 SDValue TPWithOff_lo =
4237 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004238 HiVar,
4239 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004240 0);
4241 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004242 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4243 LoVar,
4244 DAG.getTargetConstant(0, DL, MVT::i32)),
4245 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004246 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004247 } else if (Model == TLSModel::InitialExec) {
4248 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4249 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4250 } else if (Model == TLSModel::LocalDynamic) {
4251 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4252 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4253 // the beginning of the module's TLS region, followed by a DTPREL offset
4254 // calculation.
4255
4256 // These accesses will need deduplicating if there's more than one.
4257 AArch64FunctionInfo *MFI =
4258 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4259 MFI->incNumLocalDynamicTLSAccesses();
4260
Tim Northover3b0846e2014-05-24 12:50:23 +00004261 // The call needs a relocation too for linker relaxation. It doesn't make
4262 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4263 // the address.
4264 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4265 AArch64II::MO_TLS);
4266
4267 // Now we can calculate the offset from TPIDR_EL0 to this module's
4268 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004269 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004270
4271 // Now use :dtprel_whatever: operations to calculate this variable's offset
4272 // in its thread-storage area.
4273 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004274 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004275 SDValue LoVar = DAG.getTargetGlobalAddress(
4276 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004277 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4278
Kristof Beylsaea84612015-03-04 09:12:08 +00004279 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004280 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004281 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004282 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4283 DAG.getTargetConstant(0, DL, MVT::i32)),
4284 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004285 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004286 // The call needs a relocation too for linker relaxation. It doesn't make
4287 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4288 // the address.
4289 SDValue SymAddr =
4290 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4291
4292 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004293 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004294 } else
4295 llvm_unreachable("Unsupported ELF TLS access model");
4296
4297 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4298}
4299
Martin Storsjocc240962018-03-10 19:05:21 +00004300SDValue
4301AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4302 SelectionDAG &DAG) const {
4303 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4304
4305 SDValue Chain = DAG.getEntryNode();
4306 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4307 SDLoc DL(Op);
4308
4309 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4310
4311 // Load the ThreadLocalStoragePointer from the TEB
4312 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4313 SDValue TLSArray =
4314 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4315 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4316 Chain = TLSArray.getValue(1);
4317
4318 // Load the TLS index from the C runtime;
4319 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4320 // This also does the same as LOADgot, but using a generic i32 load,
4321 // while LOADgot only loads i64.
4322 SDValue TLSIndexHi =
4323 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4324 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4325 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4326 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4327 SDValue TLSIndex =
4328 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4329 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4330 Chain = TLSIndex.getValue(1);
4331
4332 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4333 // offset into the TLSArray.
4334 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4335 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4336 DAG.getConstant(3, DL, PtrVT));
4337 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4338 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4339 MachinePointerInfo());
4340 Chain = TLS.getValue(1);
4341
4342 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4343 const GlobalValue *GV = GA->getGlobal();
4344 SDValue TGAHi = DAG.getTargetGlobalAddress(
4345 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4346 SDValue TGALo = DAG.getTargetGlobalAddress(
4347 GV, DL, PtrVT, 0,
4348 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4349
4350 // Add the offset from the start of the .tls section (section base).
4351 SDValue Addr =
4352 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4353 DAG.getTargetConstant(0, DL, MVT::i32)),
4354 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004355 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004356 return Addr;
4357}
4358
Tim Northover3b0846e2014-05-24 12:50:23 +00004359SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4360 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004361 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004362 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004363 return LowerToTLSEmulatedModel(GA, DAG);
4364
Tim Northover3b0846e2014-05-24 12:50:23 +00004365 if (Subtarget->isTargetDarwin())
4366 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004367 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004368 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004369 if (Subtarget->isTargetWindows())
4370 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004371
4372 llvm_unreachable("Unexpected platform trying to use TLS");
4373}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004374
Tim Northover3b0846e2014-05-24 12:50:23 +00004375SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4376 SDValue Chain = Op.getOperand(0);
4377 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4378 SDValue LHS = Op.getOperand(2);
4379 SDValue RHS = Op.getOperand(3);
4380 SDValue Dest = Op.getOperand(4);
4381 SDLoc dl(Op);
4382
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004383 MachineFunction &MF = DAG.getMachineFunction();
4384 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4385 // will not be produced, as they are conditional branch instructions that do
4386 // not set flags.
4387 bool ProduceNonFlagSettingCondBr =
4388 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4389
Tim Northover3b0846e2014-05-24 12:50:23 +00004390 // Handle f128 first, since lowering it will result in comparing the return
4391 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4392 // is expecting to deal with.
4393 if (LHS.getValueType() == MVT::f128) {
4394 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4395
4396 // If softenSetCCOperands returned a scalar, we need to compare the result
4397 // against zero to select between true and false values.
4398 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004399 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004400 CC = ISD::SETNE;
4401 }
4402 }
4403
4404 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4405 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004406 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4407 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004408 // Only lower legal XALUO ops.
4409 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4410 return SDValue();
4411
4412 // The actual operation with overflow check.
4413 AArch64CC::CondCode OFCC;
4414 SDValue Value, Overflow;
4415 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4416
4417 if (CC == ISD::SETNE)
4418 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004419 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004420
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004421 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4422 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004423 }
4424
4425 if (LHS.getValueType().isInteger()) {
4426 assert((LHS.getValueType() == RHS.getValueType()) &&
4427 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4428
4429 // If the RHS of the comparison is zero, we can potentially fold this
4430 // to a specialized branch.
4431 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004432 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004433 if (CC == ISD::SETEQ) {
4434 // See if we can use a TBZ to fold in an AND as well.
4435 // TBZ has a smaller branch displacement than CBZ. If the offset is
4436 // out of bounds, a late MI-layer pass rewrites branches.
4437 // 403.gcc is an example that hits this case.
4438 if (LHS.getOpcode() == ISD::AND &&
4439 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4440 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4441 SDValue Test = LHS.getOperand(0);
4442 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004443 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004444 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4445 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004446 }
4447
4448 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4449 } else if (CC == ISD::SETNE) {
4450 // See if we can use a TBZ to fold in an AND as well.
4451 // TBZ has a smaller branch displacement than CBZ. If the offset is
4452 // out of bounds, a late MI-layer pass rewrites branches.
4453 // 403.gcc is an example that hits this case.
4454 if (LHS.getOpcode() == ISD::AND &&
4455 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4456 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4457 SDValue Test = LHS.getOperand(0);
4458 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004459 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004460 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4461 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004462 }
4463
4464 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004465 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4466 // Don't combine AND since emitComparison converts the AND to an ANDS
4467 // (a.k.a. TST) and the test in the test bit and branch instruction
4468 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004469 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004470 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004471 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004472 }
4473 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004474 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004475 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004476 // Don't combine AND since emitComparison converts the AND to an ANDS
4477 // (a.k.a. TST) and the test in the test bit and branch instruction
4478 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004479 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004480 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004481 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004482 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004483
4484 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004485 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004486 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4487 Cmp);
4488 }
4489
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004490 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4491 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004492
4493 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4494 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004495 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004496 AArch64CC::CondCode CC1, CC2;
4497 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004498 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004499 SDValue BR1 =
4500 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4501 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004502 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004503 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4504 Cmp);
4505 }
4506
4507 return BR1;
4508}
4509
4510SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4511 SelectionDAG &DAG) const {
4512 EVT VT = Op.getValueType();
4513 SDLoc DL(Op);
4514
4515 SDValue In1 = Op.getOperand(0);
4516 SDValue In2 = Op.getOperand(1);
4517 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004518
4519 if (SrcVT.bitsLT(VT))
4520 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4521 else if (SrcVT.bitsGT(VT))
4522 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004523
4524 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004525 uint64_t EltMask;
4526 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004527
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004528 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004529 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004530 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004531 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004532 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004533 DAG.getUNDEF(VecVT), In2);
4534 } else {
4535 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4536 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4537 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004538 };
4539
4540 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4541 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4542 EltMask = 0x80000000ULL;
4543 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004544 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004545 VecVT = MVT::v2i64;
4546
Eric Christopher572e03a2015-06-19 01:53:21 +00004547 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004548 // immediate moves cannot materialize that in a single instruction for
4549 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004550 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004551
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004552 setVecVal(AArch64::dsub);
4553 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4554 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4555 EltMask = 0x8000ULL;
4556 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004557 } else {
4558 llvm_unreachable("Invalid type for copysign!");
4559 }
4560
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004561 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004562
4563 // If we couldn't materialize the mask above, then the mask vector will be
4564 // the zero vector, and we need to negate it here.
4565 if (VT == MVT::f64 || VT == MVT::v2f64) {
4566 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4567 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4568 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4569 }
4570
4571 SDValue Sel =
4572 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4573
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004574 if (VT == MVT::f16)
4575 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004576 if (VT == MVT::f32)
4577 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4578 else if (VT == MVT::f64)
4579 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4580 else
4581 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4582}
4583
4584SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004585 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004586 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004587 return SDValue();
4588
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004589 if (!Subtarget->hasNEON())
4590 return SDValue();
4591
Tim Northover3b0846e2014-05-24 12:50:23 +00004592 // While there is no integer popcount instruction, it can
4593 // be more efficiently lowered to the following sequence that uses
4594 // AdvSIMD registers/instructions as long as the copies to/from
4595 // the AdvSIMD registers are cheap.
4596 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4597 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4598 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4599 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4600 SDValue Val = Op.getOperand(0);
4601 SDLoc DL(Op);
4602 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004603
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004604 if (VT == MVT::i32 || VT == MVT::i64) {
4605 if (VT == MVT::i32)
4606 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4607 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004608
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004609 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4610 SDValue UaddLV = DAG.getNode(
4611 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4612 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004613
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004614 if (VT == MVT::i64)
4615 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4616 return UaddLV;
4617 }
4618
4619 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4620 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4621 "Unexpected type for custom ctpop lowering");
4622
4623 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4624 Val = DAG.getBitcast(VT8Bit, Val);
4625 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4626
4627 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4628 unsigned EltSize = 8;
4629 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4630 while (EltSize != VT.getScalarSizeInBits()) {
4631 EltSize *= 2;
4632 NumElts /= 2;
4633 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4634 Val = DAG.getNode(
4635 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4636 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4637 }
4638
4639 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004640}
4641
4642SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4643
4644 if (Op.getValueType().isVector())
4645 return LowerVSETCC(Op, DAG);
4646
4647 SDValue LHS = Op.getOperand(0);
4648 SDValue RHS = Op.getOperand(1);
4649 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4650 SDLoc dl(Op);
4651
4652 // We chose ZeroOrOneBooleanContents, so use zero and one.
4653 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004654 SDValue TVal = DAG.getConstant(1, dl, VT);
4655 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004656
4657 // Handle f128 first, since one possible outcome is a normal integer
4658 // comparison which gets picked up by the next if statement.
4659 if (LHS.getValueType() == MVT::f128) {
4660 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4661
4662 // If softenSetCCOperands returned a scalar, use it.
4663 if (!RHS.getNode()) {
4664 assert(LHS.getValueType() == Op.getValueType() &&
4665 "Unexpected setcc expansion!");
4666 return LHS;
4667 }
4668 }
4669
4670 if (LHS.getValueType().isInteger()) {
4671 SDValue CCVal;
4672 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004673 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004674
4675 // Note that we inverted the condition above, so we reverse the order of
4676 // the true and false operands here. This will allow the setcc to be
4677 // matched to a single CSINC instruction.
4678 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4679 }
4680
4681 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004682 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4683 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004684
4685 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4686 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004687 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004688
4689 AArch64CC::CondCode CC1, CC2;
4690 changeFPCCToAArch64CC(CC, CC1, CC2);
4691 if (CC2 == AArch64CC::AL) {
4692 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004693 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004694
4695 // Note that we inverted the condition above, so we reverse the order of
4696 // the true and false operands here. This will allow the setcc to be
4697 // matched to a single CSINC instruction.
4698 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4699 } else {
4700 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4701 // totally clean. Some of them require two CSELs to implement. As is in
4702 // this case, we emit the first CSEL and then emit a second using the output
4703 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4704
4705 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004706 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004707 SDValue CS1 =
4708 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4709
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004710 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004711 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4712 }
4713}
4714
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004715SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4716 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004717 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004718 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004719 // Handle f128 first, because it will result in a comparison of some RTLIB
4720 // call result against zero.
4721 if (LHS.getValueType() == MVT::f128) {
4722 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4723
4724 // If softenSetCCOperands returned a scalar, we need to compare the result
4725 // against zero to select between true and false values.
4726 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004727 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004728 CC = ISD::SETNE;
4729 }
4730 }
4731
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004732 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004733 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004734 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4735 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4736 }
4737
4738 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004739 if (LHS.getValueType().isInteger()) {
4740 assert((LHS.getValueType() == RHS.getValueType()) &&
4741 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4742
4743 unsigned Opcode = AArch64ISD::CSEL;
4744
4745 // If both the TVal and the FVal are constants, see if we can swap them in
4746 // order to for a CSINV or CSINC out of them.
4747 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4748 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4749
4750 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4751 std::swap(TVal, FVal);
4752 std::swap(CTVal, CFVal);
4753 CC = ISD::getSetCCInverse(CC, true);
4754 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4755 std::swap(TVal, FVal);
4756 std::swap(CTVal, CFVal);
4757 CC = ISD::getSetCCInverse(CC, true);
4758 } else if (TVal.getOpcode() == ISD::XOR) {
4759 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4760 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004761 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004762 std::swap(TVal, FVal);
4763 std::swap(CTVal, CFVal);
4764 CC = ISD::getSetCCInverse(CC, true);
4765 }
4766 } else if (TVal.getOpcode() == ISD::SUB) {
4767 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4768 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004769 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004770 std::swap(TVal, FVal);
4771 std::swap(CTVal, CFVal);
4772 CC = ISD::getSetCCInverse(CC, true);
4773 }
4774 } else if (CTVal && CFVal) {
4775 const int64_t TrueVal = CTVal->getSExtValue();
4776 const int64_t FalseVal = CFVal->getSExtValue();
4777 bool Swap = false;
4778
4779 // If both TVal and FVal are constants, see if FVal is the
4780 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4781 // instead of a CSEL in that case.
4782 if (TrueVal == ~FalseVal) {
4783 Opcode = AArch64ISD::CSINV;
4784 } else if (TrueVal == -FalseVal) {
4785 Opcode = AArch64ISD::CSNEG;
4786 } else if (TVal.getValueType() == MVT::i32) {
4787 // If our operands are only 32-bit wide, make sure we use 32-bit
4788 // arithmetic for the check whether we can use CSINC. This ensures that
4789 // the addition in the check will wrap around properly in case there is
4790 // an overflow (which would not be the case if we do the check with
4791 // 64-bit arithmetic).
4792 const uint32_t TrueVal32 = CTVal->getZExtValue();
4793 const uint32_t FalseVal32 = CFVal->getZExtValue();
4794
4795 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4796 Opcode = AArch64ISD::CSINC;
4797
4798 if (TrueVal32 > FalseVal32) {
4799 Swap = true;
4800 }
4801 }
4802 // 64-bit check whether we can use CSINC.
4803 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4804 Opcode = AArch64ISD::CSINC;
4805
4806 if (TrueVal > FalseVal) {
4807 Swap = true;
4808 }
4809 }
4810
4811 // Swap TVal and FVal if necessary.
4812 if (Swap) {
4813 std::swap(TVal, FVal);
4814 std::swap(CTVal, CFVal);
4815 CC = ISD::getSetCCInverse(CC, true);
4816 }
4817
4818 if (Opcode != AArch64ISD::CSEL) {
4819 // Drop FVal since we can get its value by simply inverting/negating
4820 // TVal.
4821 FVal = TVal;
4822 }
4823 }
4824
Chad Rosier58f505b2016-08-26 18:05:50 +00004825 // Avoid materializing a constant when possible by reusing a known value in
4826 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004827 // is one, zero or negative one in the case of a CSEL. We can always
4828 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4829 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004830 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4831 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4832 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4833 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4834 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4835 // "a != C ? x : a" to avoid materializing C.
4836 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4837 TVal = LHS;
4838 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4839 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004840 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4841 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4842 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4843 // avoid materializing C.
4844 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4845 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4846 Opcode = AArch64ISD::CSINV;
4847 TVal = LHS;
4848 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4849 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004850 }
4851
Tim Northover3b0846e2014-05-24 12:50:23 +00004852 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004853 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004854 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004855 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4856 }
4857
4858 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004859 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4860 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004861 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004862 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004863 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004864
4865 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4866 // clean. Some of them require two CSELs to implement.
4867 AArch64CC::CondCode CC1, CC2;
4868 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004869
4870 if (DAG.getTarget().Options.UnsafeFPMath) {
4871 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4872 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4873 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4874 if (RHSVal && RHSVal->isZero()) {
4875 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4876 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4877
4878 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004879 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004880 TVal = LHS;
4881 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004882 CFVal && CFVal->isZero() &&
4883 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004884 FVal = LHS;
4885 }
4886 }
4887
4888 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004889 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004890 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4891
4892 // If we need a second CSEL, emit it, using the output of the first as the
4893 // RHS. We're effectively OR'ing the two CC's together.
4894 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004895 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004896 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4897 }
4898
4899 // Otherwise, return the output of the first CSEL.
4900 return CS1;
4901}
4902
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004903SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4904 SelectionDAG &DAG) const {
4905 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4906 SDValue LHS = Op.getOperand(0);
4907 SDValue RHS = Op.getOperand(1);
4908 SDValue TVal = Op.getOperand(2);
4909 SDValue FVal = Op.getOperand(3);
4910 SDLoc DL(Op);
4911 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4912}
4913
4914SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4915 SelectionDAG &DAG) const {
4916 SDValue CCVal = Op->getOperand(0);
4917 SDValue TVal = Op->getOperand(1);
4918 SDValue FVal = Op->getOperand(2);
4919 SDLoc DL(Op);
4920
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004921 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4922 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004923 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004924 // Only lower legal XALUO ops.
4925 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4926 return SDValue();
4927
4928 AArch64CC::CondCode OFCC;
4929 SDValue Value, Overflow;
4930 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004931 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004932
4933 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4934 CCVal, Overflow);
4935 }
4936
4937 // Lower it the same way as we would lower a SELECT_CC node.
4938 ISD::CondCode CC;
4939 SDValue LHS, RHS;
4940 if (CCVal.getOpcode() == ISD::SETCC) {
4941 LHS = CCVal.getOperand(0);
4942 RHS = CCVal.getOperand(1);
4943 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4944 } else {
4945 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004946 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004947 CC = ISD::SETNE;
4948 }
4949 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4950}
4951
Tim Northover3b0846e2014-05-24 12:50:23 +00004952SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4953 SelectionDAG &DAG) const {
4954 // Jump table entries as PC relative offsets. No additional tweaking
4955 // is necessary here. Just get the address of the jump table.
4956 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004957
4958 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4959 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004960 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004961 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4962 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004963 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004964 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004965}
4966
Tim Northover1c353412018-10-24 20:19:09 +00004967SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4968 SelectionDAG &DAG) const {
4969 // Jump table entries as PC relative offsets. No additional tweaking
4970 // is necessary here. Just get the address of the jump table.
4971 SDLoc DL(Op);
4972 SDValue JT = Op.getOperand(1);
4973 SDValue Entry = Op.getOperand(2);
4974 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4975
4976 SDNode *Dest =
4977 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4978 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4979 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4980 SDValue(Dest, 0));
4981}
4982
Tim Northover3b0846e2014-05-24 12:50:23 +00004983SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4984 SelectionDAG &DAG) const {
4985 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004986
4987 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4988 // Use the GOT for the large code model on iOS.
4989 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004990 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004991 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004992 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004993 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4994 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004995 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004996 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004997 }
4998}
4999
5000SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5001 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005002 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005003 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5004 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005005 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005006 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5007 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005008 }
David Green9dd1d452018-08-22 11:31:39 +00005009 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005010}
5011
5012SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5013 SelectionDAG &DAG) const {
5014 AArch64FunctionInfo *FuncInfo =
5015 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5016
5017 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005018 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5019 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005020 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5021 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005022 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005023}
5024
Martin Storsjo68266fa2017-07-13 17:03:12 +00005025SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5026 SelectionDAG &DAG) const {
5027 AArch64FunctionInfo *FuncInfo =
5028 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5029
5030 SDLoc DL(Op);
5031 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5032 ? FuncInfo->getVarArgsGPRIndex()
5033 : FuncInfo->getVarArgsStackIndex(),
5034 getPointerTy(DAG.getDataLayout()));
5035 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5036 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5037 MachinePointerInfo(SV));
5038}
5039
Tim Northover3b0846e2014-05-24 12:50:23 +00005040SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5041 SelectionDAG &DAG) const {
5042 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5043 // Standard, section B.3.
5044 MachineFunction &MF = DAG.getMachineFunction();
5045 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005046 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005047 SDLoc DL(Op);
5048
5049 SDValue Chain = Op.getOperand(0);
5050 SDValue VAList = Op.getOperand(1);
5051 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5052 SmallVector<SDValue, 4> MemOps;
5053
5054 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005055 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005056 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005057 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005058
5059 // void *__gr_top at offset 8
5060 int GPRSize = FuncInfo->getVarArgsGPRSize();
5061 if (GPRSize > 0) {
5062 SDValue GRTop, GRTopAddr;
5063
Mehdi Amini44ede332015-07-09 02:09:04 +00005064 GRTopAddr =
5065 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005066
Mehdi Amini44ede332015-07-09 02:09:04 +00005067 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5068 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5069 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005070
5071 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005072 MachinePointerInfo(SV, 8),
5073 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005074 }
5075
5076 // void *__vr_top at offset 16
5077 int FPRSize = FuncInfo->getVarArgsFPRSize();
5078 if (FPRSize > 0) {
5079 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005080 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5081 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005082
Mehdi Amini44ede332015-07-09 02:09:04 +00005083 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5084 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5085 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005086
5087 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005088 MachinePointerInfo(SV, 16),
5089 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005090 }
5091
5092 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005093 SDValue GROffsAddr =
5094 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005095 MemOps.push_back(DAG.getStore(
5096 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5097 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005098
5099 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005100 SDValue VROffsAddr =
5101 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005102 MemOps.push_back(DAG.getStore(
5103 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5104 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005105
5106 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5107}
5108
5109SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5110 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005111 MachineFunction &MF = DAG.getMachineFunction();
5112
Matthias Braunf1caa282017-12-15 22:22:58 +00005113 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005114 return LowerWin64_VASTART(Op, DAG);
5115 else if (Subtarget->isTargetDarwin())
5116 return LowerDarwin_VASTART(Op, DAG);
5117 else
5118 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005119}
5120
5121SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5122 SelectionDAG &DAG) const {
5123 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5124 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005125 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005126 unsigned VaListSize =
5127 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005128 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5129 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5130
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005131 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5132 Op.getOperand(2),
5133 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005134 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005135 MachinePointerInfo(SrcSV));
5136}
5137
5138SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5139 assert(Subtarget->isTargetDarwin() &&
5140 "automatic va_arg instruction only works on Darwin");
5141
5142 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5143 EVT VT = Op.getValueType();
5144 SDLoc DL(Op);
5145 SDValue Chain = Op.getOperand(0);
5146 SDValue Addr = Op.getOperand(1);
5147 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005148 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005149
Justin Lebar9c375812016-07-15 18:27:10 +00005150 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005151 Chain = VAList.getValue(1);
5152
5153 if (Align > 8) {
5154 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005155 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5156 DAG.getConstant(Align - 1, DL, PtrVT));
5157 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5158 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005159 }
5160
5161 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005162 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005163
5164 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5165 // up to 64 bits. At the very least, we have to increase the striding of the
5166 // vaargs list to match this, and for FP values we need to introduce
5167 // FP_ROUND nodes as well.
5168 if (VT.isInteger() && !VT.isVector())
5169 ArgSize = 8;
5170 bool NeedFPTrunc = false;
5171 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5172 ArgSize = 8;
5173 NeedFPTrunc = true;
5174 }
5175
5176 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005177 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5178 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005179 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005180 SDValue APStore =
5181 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005182
5183 // Load the actual argument out of the pointer VAList
5184 if (NeedFPTrunc) {
5185 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005186 SDValue WideFP =
5187 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005188 // Round the value down to an f32.
5189 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005190 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005191 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5192 // Merge the rounded value with the chain output of the load.
5193 return DAG.getMergeValues(Ops, DL);
5194 }
5195
Justin Lebar9c375812016-07-15 18:27:10 +00005196 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005197}
5198
5199SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5200 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005201 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5202 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005203
5204 EVT VT = Op.getValueType();
5205 SDLoc DL(Op);
5206 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5207 SDValue FrameAddr =
5208 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5209 while (Depth--)
5210 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005211 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005212 return FrameAddr;
5213}
5214
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005215SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5216 SelectionDAG &DAG) const {
5217 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5218
5219 EVT VT = getPointerTy(DAG.getDataLayout());
5220 SDLoc DL(Op);
5221 int FI = MFI.CreateFixedObject(4, 0, false);
5222 return DAG.getFrameIndex(FI, VT);
5223}
5224
Tim Northover3b0846e2014-05-24 12:50:23 +00005225// FIXME? Maybe this could be a TableGen attribute on some registers and
5226// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005227unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5228 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005229 unsigned Reg = StringSwitch<unsigned>(RegName)
5230 .Case("sp", AArch64::SP)
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005231 .Case("x1", AArch64::X1)
5232 .Case("w1", AArch64::W1)
5233 .Case("x2", AArch64::X2)
5234 .Case("w2", AArch64::W2)
5235 .Case("x3", AArch64::X3)
5236 .Case("w3", AArch64::W3)
5237 .Case("x4", AArch64::X4)
5238 .Case("w4", AArch64::W4)
5239 .Case("x5", AArch64::X5)
5240 .Case("w5", AArch64::W5)
5241 .Case("x6", AArch64::X6)
5242 .Case("w6", AArch64::W6)
5243 .Case("x7", AArch64::X7)
5244 .Case("w7", AArch64::W7)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005245 .Case("x18", AArch64::X18)
5246 .Case("w18", AArch64::W18)
Petr Hosek72509082018-06-12 20:00:50 +00005247 .Case("x20", AArch64::X20)
5248 .Case("w20", AArch64::W20)
Tim Northover3b0846e2014-05-24 12:50:23 +00005249 .Default(0);
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005250 if (((Reg == AArch64::X1 || Reg == AArch64::W1) &&
5251 !Subtarget->isXRegisterReserved(1)) ||
5252 ((Reg == AArch64::X2 || Reg == AArch64::W2) &&
5253 !Subtarget->isXRegisterReserved(2)) ||
5254 ((Reg == AArch64::X3 || Reg == AArch64::W3) &&
5255 !Subtarget->isXRegisterReserved(3)) ||
5256 ((Reg == AArch64::X4 || Reg == AArch64::W4) &&
5257 !Subtarget->isXRegisterReserved(4)) ||
5258 ((Reg == AArch64::X5 || Reg == AArch64::W5) &&
5259 !Subtarget->isXRegisterReserved(5)) ||
5260 ((Reg == AArch64::X6 || Reg == AArch64::W6) &&
5261 !Subtarget->isXRegisterReserved(6)) ||
5262 ((Reg == AArch64::X7 || Reg == AArch64::W7) &&
5263 !Subtarget->isXRegisterReserved(7)) ||
5264 ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
5265 !Subtarget->isXRegisterReserved(18)) ||
Petr Hosek72509082018-06-12 20:00:50 +00005266 ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005267 !Subtarget->isXRegisterReserved(20)))
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005268 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00005269 if (Reg)
5270 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005271 report_fatal_error(Twine("Invalid register name \""
5272 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005273}
5274
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005275SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5276 SelectionDAG &DAG) const {
5277 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5278
5279 EVT VT = Op.getValueType();
5280 SDLoc DL(Op);
5281
5282 SDValue FrameAddr =
5283 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5284 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5285
5286 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5287}
5288
Tim Northover3b0846e2014-05-24 12:50:23 +00005289SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5290 SelectionDAG &DAG) const {
5291 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005292 MachineFrameInfo &MFI = MF.getFrameInfo();
5293 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005294
5295 EVT VT = Op.getValueType();
5296 SDLoc DL(Op);
5297 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5298 if (Depth) {
5299 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005300 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005301 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5302 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005303 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005304 }
5305
5306 // Return LR, which contains the return address. Mark it an implicit live-in.
5307 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5308 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5309}
5310
5311/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5312/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5313SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5314 SelectionDAG &DAG) const {
5315 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5316 EVT VT = Op.getValueType();
5317 unsigned VTBits = VT.getSizeInBits();
5318 SDLoc dl(Op);
5319 SDValue ShOpLo = Op.getOperand(0);
5320 SDValue ShOpHi = Op.getOperand(1);
5321 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005322 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5323
5324 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5325
5326 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005327 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005328 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5329
5330 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5331 // is "undef". We wanted 0, so CSEL it directly.
5332 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5333 ISD::SETEQ, dl, DAG);
5334 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5335 HiBitsForLo =
5336 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5337 HiBitsForLo, CCVal, Cmp);
5338
Tim Northover3b0846e2014-05-24 12:50:23 +00005339 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005340 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005341
Tim Northoverf3be9d52015-12-02 00:33:54 +00005342 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5343 SDValue LoForNormalShift =
5344 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005345
Tim Northoverf3be9d52015-12-02 00:33:54 +00005346 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5347 dl, DAG);
5348 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5349 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5350 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5351 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005352
5353 // AArch64 shifts larger than the register width are wrapped rather than
5354 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005355 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5356 SDValue HiForBigShift =
5357 Opc == ISD::SRA
5358 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5359 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5360 : DAG.getConstant(0, dl, VT);
5361 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5362 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005363
5364 SDValue Ops[2] = { Lo, Hi };
5365 return DAG.getMergeValues(Ops, dl);
5366}
5367
5368/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5369/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5370SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005371 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005372 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5373 EVT VT = Op.getValueType();
5374 unsigned VTBits = VT.getSizeInBits();
5375 SDLoc dl(Op);
5376 SDValue ShOpLo = Op.getOperand(0);
5377 SDValue ShOpHi = Op.getOperand(1);
5378 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005379
5380 assert(Op.getOpcode() == ISD::SHL_PARTS);
5381 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005382 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005383 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5384
5385 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5386 // is "undef". We wanted 0, so CSEL it directly.
5387 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5388 ISD::SETEQ, dl, DAG);
5389 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5390 LoBitsForHi =
5391 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5392 LoBitsForHi, CCVal, Cmp);
5393
Tim Northover3b0846e2014-05-24 12:50:23 +00005394 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005395 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005396 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5397 SDValue HiForNormalShift =
5398 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005399
Tim Northoverf3be9d52015-12-02 00:33:54 +00005400 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005401
Tim Northoverf3be9d52015-12-02 00:33:54 +00005402 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5403 dl, DAG);
5404 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5405 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5406 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005407
5408 // AArch64 shifts of larger than register sizes are wrapped rather than
5409 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005410 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5411 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5412 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5413 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005414
5415 SDValue Ops[2] = { Lo, Hi };
5416 return DAG.getMergeValues(Ops, dl);
5417}
5418
5419bool AArch64TargetLowering::isOffsetFoldingLegal(
5420 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005421 // Offsets are folded in the DAG combine rather than here so that we can
5422 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005423 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005424}
5425
5426bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005427 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005428 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5429 // 16-bit case when target has full fp16 support.
5430 // FIXME: We should be able to handle f128 as well with a clever lowering.
5431 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005432 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005433 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005434 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005435 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005436 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005437 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5438 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5439 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005440
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005441 // If we can not materialize in immediate field for fmov, check if the
5442 // value can be encoded as the immediate operand of a logical instruction.
5443 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5444 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32))
5445 IsLegal = AArch64_AM::isAnyMOVWMovAlias(ImmInt.getZExtValue(),
5446 VT.getSizeInBits());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005447
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005448 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5449 << " imm value: "; Imm.dump(););
5450 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005451}
5452
5453//===----------------------------------------------------------------------===//
5454// AArch64 Optimization Hooks
5455//===----------------------------------------------------------------------===//
5456
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005457static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5458 SDValue Operand, SelectionDAG &DAG,
5459 int &ExtraSteps) {
5460 EVT VT = Operand.getValueType();
5461 if (ST->hasNEON() &&
5462 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5463 VT == MVT::f32 || VT == MVT::v1f32 ||
5464 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5465 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5466 // For the reciprocal estimates, convergence is quadratic, so the number
5467 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5468 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5469 // the result for float (23 mantissa bits) is 2 and for double (52
5470 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005471 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005472
5473 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5474 }
5475
5476 return SDValue();
5477}
5478
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005479SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5480 SelectionDAG &DAG, int Enabled,
5481 int &ExtraSteps,
5482 bool &UseOneConst,
5483 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005484 if (Enabled == ReciprocalEstimate::Enabled ||
5485 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5486 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5487 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005488 SDLoc DL(Operand);
5489 EVT VT = Operand.getValueType();
5490
5491 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005492 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005493
5494 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5495 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5496 for (int i = ExtraSteps; i > 0; --i) {
5497 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005498 Flags);
5499 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5500 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005501 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005502 if (!Reciprocal) {
5503 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5504 VT);
5505 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5506 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5507
Amara Emersond28f0cd42017-05-01 15:17:51 +00005508 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005509 // Correct the result if the operand is 0.0.
5510 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5511 VT, Eq, Operand, Estimate);
5512 }
5513
5514 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005515 return Estimate;
5516 }
5517
5518 return SDValue();
5519}
5520
5521SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5522 SelectionDAG &DAG, int Enabled,
5523 int &ExtraSteps) const {
5524 if (Enabled == ReciprocalEstimate::Enabled)
5525 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005526 DAG, ExtraSteps)) {
5527 SDLoc DL(Operand);
5528 EVT VT = Operand.getValueType();
5529
5530 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005531 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005532
5533 // Newton reciprocal iteration: E * (2 - X * E)
5534 // AArch64 reciprocal iteration instruction: (2 - M * N)
5535 for (int i = ExtraSteps; i > 0; --i) {
5536 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005537 Estimate, Flags);
5538 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005539 }
5540
5541 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005542 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005543 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005544
5545 return SDValue();
5546}
5547
Tim Northover3b0846e2014-05-24 12:50:23 +00005548//===----------------------------------------------------------------------===//
5549// AArch64 Inline Assembly Support
5550//===----------------------------------------------------------------------===//
5551
5552// Table of Constraints
5553// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005554// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005555//
5556// r - A general register
5557// w - An FP/SIMD register of some size in the range v0-v31
5558// x - An FP/SIMD register of some size in the range v0-v15
5559// I - Constant that can be used with an ADD instruction
5560// J - Constant that can be used with a SUB instruction
5561// K - Constant that can be used with a 32-bit logical instruction
5562// L - Constant that can be used with a 64-bit logical instruction
5563// M - Constant that can be used as a 32-bit MOV immediate
5564// N - Constant that can be used as a 64-bit MOV immediate
5565// Q - A memory reference with base register and no offset
5566// S - A symbolic address
5567// Y - Floating point constant zero
5568// Z - Integer constant zero
5569//
5570// Note that general register operands will be output using their 64-bit x
5571// register name, whatever the size of the variable, unless the asm operand
5572// is prefixed by the %w modifier. Floating-point and SIMD register operands
5573// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5574// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005575const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5576 // At this point, we have to lower this constraint to something else, so we
5577 // lower it to an "r" or "w". However, by doing this we will force the result
5578 // to be in register, while the X constraint is much more permissive.
5579 //
5580 // Although we are correct (we are free to emit anything, without
5581 // constraints), we might break use cases that would expect us to be more
5582 // efficient and emit something else.
5583 if (!Subtarget->hasFPARMv8())
5584 return "r";
5585
5586 if (ConstraintVT.isFloatingPoint())
5587 return "w";
5588
5589 if (ConstraintVT.isVector() &&
5590 (ConstraintVT.getSizeInBits() == 64 ||
5591 ConstraintVT.getSizeInBits() == 128))
5592 return "w";
5593
5594 return "r";
5595}
Tim Northover3b0846e2014-05-24 12:50:23 +00005596
5597/// getConstraintType - Given a constraint letter, return the type of
5598/// constraint it is for this target.
5599AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005600AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005601 if (Constraint.size() == 1) {
5602 switch (Constraint[0]) {
5603 default:
5604 break;
5605 case 'z':
5606 return C_Other;
5607 case 'x':
5608 case 'w':
5609 return C_RegisterClass;
5610 // An address with a single base register. Due to the way we
5611 // currently handle addresses it is the same as 'r'.
5612 case 'Q':
5613 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005614 case 'S': // A symbolic address
5615 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005616 }
5617 }
5618 return TargetLowering::getConstraintType(Constraint);
5619}
5620
5621/// Examine constraint type and operand type and determine a weight value.
5622/// This object must already have been set up with the operand type
5623/// and the current alternative constraint selected.
5624TargetLowering::ConstraintWeight
5625AArch64TargetLowering::getSingleConstraintMatchWeight(
5626 AsmOperandInfo &info, const char *constraint) const {
5627 ConstraintWeight weight = CW_Invalid;
5628 Value *CallOperandVal = info.CallOperandVal;
5629 // If we don't have a value, we can't do a match,
5630 // but allow it at the lowest weight.
5631 if (!CallOperandVal)
5632 return CW_Default;
5633 Type *type = CallOperandVal->getType();
5634 // Look at the constraint type.
5635 switch (*constraint) {
5636 default:
5637 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5638 break;
5639 case 'x':
5640 case 'w':
5641 if (type->isFloatingPointTy() || type->isVectorTy())
5642 weight = CW_Register;
5643 break;
5644 case 'z':
5645 weight = CW_Constant;
5646 break;
5647 }
5648 return weight;
5649}
5650
5651std::pair<unsigned, const TargetRegisterClass *>
5652AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005653 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005654 if (Constraint.size() == 1) {
5655 switch (Constraint[0]) {
5656 case 'r':
5657 if (VT.getSizeInBits() == 64)
5658 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5659 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5660 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005661 if (!Subtarget->hasFPARMv8())
5662 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005663 if (VT.getSizeInBits() == 16)
5664 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005665 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005666 return std::make_pair(0U, &AArch64::FPR32RegClass);
5667 if (VT.getSizeInBits() == 64)
5668 return std::make_pair(0U, &AArch64::FPR64RegClass);
5669 if (VT.getSizeInBits() == 128)
5670 return std::make_pair(0U, &AArch64::FPR128RegClass);
5671 break;
5672 // The instructions that this constraint is designed for can
5673 // only take 128-bit registers so just use that regclass.
5674 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005675 if (!Subtarget->hasFPARMv8())
5676 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005677 if (VT.getSizeInBits() == 128)
5678 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5679 break;
5680 }
5681 }
5682 if (StringRef("{cc}").equals_lower(Constraint))
5683 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5684
5685 // Use the default implementation in TargetLowering to convert the register
5686 // constraint into a member of a register class.
5687 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005688 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005689
5690 // Not found as a standard register?
5691 if (!Res.second) {
5692 unsigned Size = Constraint.size();
5693 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5694 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005695 int RegNo;
5696 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5697 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005698 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005699 // By default we'll emit v0-v31 for this unless there's a modifier where
5700 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005701 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5702 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5703 Res.second = &AArch64::FPR64RegClass;
5704 } else {
5705 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5706 Res.second = &AArch64::FPR128RegClass;
5707 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005708 }
5709 }
5710 }
5711
Eli Friedman071203b2018-08-24 19:12:13 +00005712 if (Res.second && !Subtarget->hasFPARMv8() &&
5713 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5714 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5715 return std::make_pair(0U, nullptr);
5716
Tim Northover3b0846e2014-05-24 12:50:23 +00005717 return Res;
5718}
5719
5720/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5721/// vector. If it is invalid, don't add anything to Ops.
5722void AArch64TargetLowering::LowerAsmOperandForConstraint(
5723 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5724 SelectionDAG &DAG) const {
5725 SDValue Result;
5726
5727 // Currently only support length 1 constraints.
5728 if (Constraint.length() != 1)
5729 return;
5730
5731 char ConstraintLetter = Constraint[0];
5732 switch (ConstraintLetter) {
5733 default:
5734 break;
5735
5736 // This set of constraints deal with valid constants for various instructions.
5737 // Validate and return a target constant for them if we can.
5738 case 'z': {
5739 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005740 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005741 return;
5742
5743 if (Op.getValueType() == MVT::i64)
5744 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5745 else
5746 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5747 break;
5748 }
Peter Smithc8117582018-05-16 09:33:25 +00005749 case 'S': {
5750 // An absolute symbolic address or label reference.
5751 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5752 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5753 GA->getValueType(0));
5754 } else if (const BlockAddressSDNode *BA =
5755 dyn_cast<BlockAddressSDNode>(Op)) {
5756 Result =
5757 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5758 } else if (const ExternalSymbolSDNode *ES =
5759 dyn_cast<ExternalSymbolSDNode>(Op)) {
5760 Result =
5761 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5762 } else
5763 return;
5764 break;
5765 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005766
5767 case 'I':
5768 case 'J':
5769 case 'K':
5770 case 'L':
5771 case 'M':
5772 case 'N':
5773 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5774 if (!C)
5775 return;
5776
5777 // Grab the value and do some validation.
5778 uint64_t CVal = C->getZExtValue();
5779 switch (ConstraintLetter) {
5780 // The I constraint applies only to simple ADD or SUB immediate operands:
5781 // i.e. 0 to 4095 with optional shift by 12
5782 // The J constraint applies only to ADD or SUB immediates that would be
5783 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5784 // instruction [or vice versa], in other words -1 to -4095 with optional
5785 // left shift by 12.
5786 case 'I':
5787 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5788 break;
5789 return;
5790 case 'J': {
5791 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005792 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5793 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005794 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005795 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005796 return;
5797 }
5798 // The K and L constraints apply *only* to logical immediates, including
5799 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5800 // been removed and MOV should be used). So these constraints have to
5801 // distinguish between bit patterns that are valid 32-bit or 64-bit
5802 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5803 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5804 // versa.
5805 case 'K':
5806 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5807 break;
5808 return;
5809 case 'L':
5810 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5811 break;
5812 return;
5813 // The M and N constraints are a superset of K and L respectively, for use
5814 // with the MOV (immediate) alias. As well as the logical immediates they
5815 // also match 32 or 64-bit immediates that can be loaded either using a
5816 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5817 // (M) or 64-bit 0x1234000000000000 (N) etc.
5818 // As a note some of this code is liberally stolen from the asm parser.
5819 case 'M': {
5820 if (!isUInt<32>(CVal))
5821 return;
5822 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5823 break;
5824 if ((CVal & 0xFFFF) == CVal)
5825 break;
5826 if ((CVal & 0xFFFF0000ULL) == CVal)
5827 break;
5828 uint64_t NCVal = ~(uint32_t)CVal;
5829 if ((NCVal & 0xFFFFULL) == NCVal)
5830 break;
5831 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5832 break;
5833 return;
5834 }
5835 case 'N': {
5836 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5837 break;
5838 if ((CVal & 0xFFFFULL) == CVal)
5839 break;
5840 if ((CVal & 0xFFFF0000ULL) == CVal)
5841 break;
5842 if ((CVal & 0xFFFF00000000ULL) == CVal)
5843 break;
5844 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5845 break;
5846 uint64_t NCVal = ~CVal;
5847 if ((NCVal & 0xFFFFULL) == NCVal)
5848 break;
5849 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5850 break;
5851 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5852 break;
5853 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5854 break;
5855 return;
5856 }
5857 default:
5858 return;
5859 }
5860
5861 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005862 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005863 break;
5864 }
5865
5866 if (Result.getNode()) {
5867 Ops.push_back(Result);
5868 return;
5869 }
5870
5871 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5872}
5873
5874//===----------------------------------------------------------------------===//
5875// AArch64 Advanced SIMD Support
5876//===----------------------------------------------------------------------===//
5877
5878/// WidenVector - Given a value in the V64 register class, produce the
5879/// equivalent value in the V128 register class.
5880static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5881 EVT VT = V64Reg.getValueType();
5882 unsigned NarrowSize = VT.getVectorNumElements();
5883 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5884 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5885 SDLoc DL(V64Reg);
5886
5887 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005888 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005889}
5890
5891/// getExtFactor - Determine the adjustment factor for the position when
5892/// generating an "extract from vector registers" instruction.
5893static unsigned getExtFactor(SDValue &V) {
5894 EVT EltType = V.getValueType().getVectorElementType();
5895 return EltType.getSizeInBits() / 8;
5896}
5897
5898/// NarrowVector - Given a value in the V128 register class, produce the
5899/// equivalent value in the V64 register class.
5900static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5901 EVT VT = V128Reg.getValueType();
5902 unsigned WideSize = VT.getVectorNumElements();
5903 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5904 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5905 SDLoc DL(V128Reg);
5906
5907 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5908}
5909
5910// Gather data to see if the operation can be modelled as a
5911// shuffle in combination with VEXTs.
5912SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5913 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005914 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005915 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005916 SDLoc dl(Op);
5917 EVT VT = Op.getValueType();
5918 unsigned NumElts = VT.getVectorNumElements();
5919
Tim Northover7324e842014-07-24 15:39:55 +00005920 struct ShuffleSourceInfo {
5921 SDValue Vec;
5922 unsigned MinElt;
5923 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005924
Tim Northover7324e842014-07-24 15:39:55 +00005925 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5926 // be compatible with the shuffle we intend to construct. As a result
5927 // ShuffleVec will be some sliding window into the original Vec.
5928 SDValue ShuffleVec;
5929
5930 // Code should guarantee that element i in Vec starts at element "WindowBase
5931 // + i * WindowScale in ShuffleVec".
5932 int WindowBase;
5933 int WindowScale;
5934
Tim Northover7324e842014-07-24 15:39:55 +00005935 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005936 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5937 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5938
5939 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005940 };
5941
5942 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5943 // node.
5944 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005945 for (unsigned i = 0; i < NumElts; ++i) {
5946 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005947 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005948 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005949 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5950 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005951 LLVM_DEBUG(
5952 dbgs() << "Reshuffle failed: "
5953 "a shuffle can only come from building a vector from "
5954 "various elements of other vectors, provided their "
5955 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005956 return SDValue();
5957 }
5958
Tim Northover7324e842014-07-24 15:39:55 +00005959 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005960 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005961 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005962 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005963 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005964
Tim Northover7324e842014-07-24 15:39:55 +00005965 // Update the minimum and maximum lane number seen.
5966 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5967 Source->MinElt = std::min(Source->MinElt, EltNo);
5968 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005969 }
5970
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005971 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005972 LLVM_DEBUG(
5973 dbgs() << "Reshuffle failed: currently only do something sane when at "
5974 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005975 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005976 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005977
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005978 // Find out the smallest element size among result and two sources, and use
5979 // it as element size to build the shuffle_vector.
5980 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005981 for (auto &Source : Sources) {
5982 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005983 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5984 SmallestEltTy = SrcEltTy;
5985 }
5986 }
5987 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005988 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005989 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5990 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005991
Tim Northover7324e842014-07-24 15:39:55 +00005992 // If the source vector is too wide or too narrow, we may nevertheless be able
5993 // to construct a compatible shuffle either by concatenating it with UNDEF or
5994 // extracting a suitable range of elements.
5995 for (auto &Src : Sources) {
5996 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005997
Tim Northover7324e842014-07-24 15:39:55 +00005998 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005999 continue;
Tim Northover7324e842014-07-24 15:39:55 +00006000
6001 // This stage of the search produces a source with the same element type as
6002 // the original, but with a total width matching the BUILD_VECTOR output.
6003 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00006004 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6005 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00006006
6007 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6008 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006009 // We can pad out the smaller vector for free, so if it's part of a
6010 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00006011 Src.ShuffleVec =
6012 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6013 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00006014 continue;
6015 }
6016
Tim Northover7324e842014-07-24 15:39:55 +00006017 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006018
James Molloyf497d552014-10-17 17:06:31 +00006019 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006020 LLVM_DEBUG(
6021 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006022 return SDValue();
6023 }
6024
James Molloyf497d552014-10-17 17:06:31 +00006025 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006026 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00006027 Src.ShuffleVec =
6028 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006029 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00006030 Src.WindowBase = -NumSrcElts;
6031 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006032 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006033 Src.ShuffleVec =
6034 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006035 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006036 } else {
6037 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006038 SDValue VEXTSrc1 =
6039 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006040 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006041 SDValue VEXTSrc2 =
6042 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006043 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006044 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6045
6046 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006047 VEXTSrc2,
6048 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006049 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006050 }
6051 }
6052
Tim Northover7324e842014-07-24 15:39:55 +00006053 // Another possible incompatibility occurs from the vector element types. We
6054 // can fix this by bitcasting the source vectors to the same type we intend
6055 // for the shuffle.
6056 for (auto &Src : Sources) {
6057 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6058 if (SrcEltTy == SmallestEltTy)
6059 continue;
6060 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6061 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6062 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6063 Src.WindowBase *= Src.WindowScale;
6064 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006065
Tim Northover7324e842014-07-24 15:39:55 +00006066 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006067 LLVM_DEBUG(for (auto Src
6068 : Sources)
6069 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006070
6071 // The stars all align, our next step is to produce the mask for the shuffle.
6072 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006073 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006074 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006075 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006076 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006077 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006078
David Majnemer0d955d02016-08-11 22:21:41 +00006079 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006080 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6081
6082 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6083 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6084 // segment.
6085 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006086 int BitsDefined =
6087 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006088 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6089
6090 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6091 // starting at the appropriate offset.
6092 int *LaneMask = &Mask[i * ResMultiplier];
6093
6094 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6095 ExtractBase += NumElts * (Src - Sources.begin());
6096 for (int j = 0; j < LanesDefined; ++j)
6097 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006098 }
6099
6100 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006101 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006102 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006103 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006104 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006105
Tim Northover7324e842014-07-24 15:39:55 +00006106 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6107 for (unsigned i = 0; i < Sources.size(); ++i)
6108 ShuffleOps[i] = Sources[i].ShuffleVec;
6109
6110 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006111 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006112 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6113
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006114 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6115 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006116
6117 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006118}
6119
6120// check if an EXT instruction can handle the shuffle mask when the
6121// vector sources of the shuffle are the same.
6122static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6123 unsigned NumElts = VT.getVectorNumElements();
6124
6125 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6126 if (M[0] < 0)
6127 return false;
6128
6129 Imm = M[0];
6130
6131 // If this is a VEXT shuffle, the immediate value is the index of the first
6132 // element. The other shuffle indices must be the successive elements after
6133 // the first one.
6134 unsigned ExpectedElt = Imm;
6135 for (unsigned i = 1; i < NumElts; ++i) {
6136 // Increment the expected index. If it wraps around, just follow it
6137 // back to index zero and keep going.
6138 ++ExpectedElt;
6139 if (ExpectedElt == NumElts)
6140 ExpectedElt = 0;
6141
6142 if (M[i] < 0)
6143 continue; // ignore UNDEF indices
6144 if (ExpectedElt != static_cast<unsigned>(M[i]))
6145 return false;
6146 }
6147
6148 return true;
6149}
6150
6151// check if an EXT instruction can handle the shuffle mask when the
6152// vector sources of the shuffle are different.
6153static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6154 unsigned &Imm) {
6155 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006156 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006157
6158 // Benefit form APInt to handle overflow when calculating expected element.
6159 unsigned NumElts = VT.getVectorNumElements();
6160 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6161 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6162 // The following shuffle indices must be the successive elements after the
6163 // first real element.
6164 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6165 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6166 if (FirstWrongElt != M.end())
6167 return false;
6168
6169 // The index of an EXT is the first element if it is not UNDEF.
6170 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006171 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006172 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6173 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6174 // ExpectedElt is the last mask index plus 1.
6175 Imm = ExpectedElt.getZExtValue();
6176
6177 // There are two difference cases requiring to reverse input vectors.
6178 // For example, for vector <4 x i32> we have the following cases,
6179 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6180 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6181 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6182 // to reverse two input vectors.
6183 if (Imm < NumElts)
6184 ReverseEXT = true;
6185 else
6186 Imm -= NumElts;
6187
6188 return true;
6189}
6190
6191/// isREVMask - Check if a vector shuffle corresponds to a REV
6192/// instruction with the specified blocksize. (The order of the elements
6193/// within each block of the vector is reversed.)
6194static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6195 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6196 "Only possible block sizes for REV are: 16, 32, 64");
6197
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006198 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006199 if (EltSz == 64)
6200 return false;
6201
6202 unsigned NumElts = VT.getVectorNumElements();
6203 unsigned BlockElts = M[0] + 1;
6204 // If the first shuffle index is UNDEF, be optimistic.
6205 if (M[0] < 0)
6206 BlockElts = BlockSize / EltSz;
6207
6208 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6209 return false;
6210
6211 for (unsigned i = 0; i < NumElts; ++i) {
6212 if (M[i] < 0)
6213 continue; // ignore UNDEF indices
6214 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6215 return false;
6216 }
6217
6218 return true;
6219}
6220
6221static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6222 unsigned NumElts = VT.getVectorNumElements();
6223 WhichResult = (M[0] == 0 ? 0 : 1);
6224 unsigned Idx = WhichResult * NumElts / 2;
6225 for (unsigned i = 0; i != NumElts; i += 2) {
6226 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6227 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6228 return false;
6229 Idx += 1;
6230 }
6231
6232 return true;
6233}
6234
6235static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6236 unsigned NumElts = VT.getVectorNumElements();
6237 WhichResult = (M[0] == 0 ? 0 : 1);
6238 for (unsigned i = 0; i != NumElts; ++i) {
6239 if (M[i] < 0)
6240 continue; // ignore UNDEF indices
6241 if ((unsigned)M[i] != 2 * i + WhichResult)
6242 return false;
6243 }
6244
6245 return true;
6246}
6247
6248static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6249 unsigned NumElts = VT.getVectorNumElements();
6250 WhichResult = (M[0] == 0 ? 0 : 1);
6251 for (unsigned i = 0; i < NumElts; i += 2) {
6252 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6253 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6254 return false;
6255 }
6256 return true;
6257}
6258
6259/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6260/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6261/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6262static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6263 unsigned NumElts = VT.getVectorNumElements();
6264 WhichResult = (M[0] == 0 ? 0 : 1);
6265 unsigned Idx = WhichResult * NumElts / 2;
6266 for (unsigned i = 0; i != NumElts; i += 2) {
6267 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6268 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6269 return false;
6270 Idx += 1;
6271 }
6272
6273 return true;
6274}
6275
6276/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6277/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6278/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6279static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6280 unsigned Half = VT.getVectorNumElements() / 2;
6281 WhichResult = (M[0] == 0 ? 0 : 1);
6282 for (unsigned j = 0; j != 2; ++j) {
6283 unsigned Idx = WhichResult;
6284 for (unsigned i = 0; i != Half; ++i) {
6285 int MIdx = M[i + j * Half];
6286 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6287 return false;
6288 Idx += 2;
6289 }
6290 }
6291
6292 return true;
6293}
6294
6295/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6296/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6297/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6298static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6299 unsigned NumElts = VT.getVectorNumElements();
6300 WhichResult = (M[0] == 0 ? 0 : 1);
6301 for (unsigned i = 0; i < NumElts; i += 2) {
6302 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6303 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6304 return false;
6305 }
6306 return true;
6307}
6308
6309static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6310 bool &DstIsLeft, int &Anomaly) {
6311 if (M.size() != static_cast<size_t>(NumInputElements))
6312 return false;
6313
6314 int NumLHSMatch = 0, NumRHSMatch = 0;
6315 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6316
6317 for (int i = 0; i < NumInputElements; ++i) {
6318 if (M[i] == -1) {
6319 ++NumLHSMatch;
6320 ++NumRHSMatch;
6321 continue;
6322 }
6323
6324 if (M[i] == i)
6325 ++NumLHSMatch;
6326 else
6327 LastLHSMismatch = i;
6328
6329 if (M[i] == i + NumInputElements)
6330 ++NumRHSMatch;
6331 else
6332 LastRHSMismatch = i;
6333 }
6334
6335 if (NumLHSMatch == NumInputElements - 1) {
6336 DstIsLeft = true;
6337 Anomaly = LastLHSMismatch;
6338 return true;
6339 } else if (NumRHSMatch == NumInputElements - 1) {
6340 DstIsLeft = false;
6341 Anomaly = LastRHSMismatch;
6342 return true;
6343 }
6344
6345 return false;
6346}
6347
6348static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6349 if (VT.getSizeInBits() != 128)
6350 return false;
6351
6352 unsigned NumElts = VT.getVectorNumElements();
6353
6354 for (int I = 0, E = NumElts / 2; I != E; I++) {
6355 if (Mask[I] != I)
6356 return false;
6357 }
6358
6359 int Offset = NumElts / 2;
6360 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6361 if (Mask[I] != I + SplitLHS * Offset)
6362 return false;
6363 }
6364
6365 return true;
6366}
6367
6368static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6369 SDLoc DL(Op);
6370 EVT VT = Op.getValueType();
6371 SDValue V0 = Op.getOperand(0);
6372 SDValue V1 = Op.getOperand(1);
6373 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6374
6375 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6376 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6377 return SDValue();
6378
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006379 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006380
6381 if (!isConcatMask(Mask, VT, SplitV0))
6382 return SDValue();
6383
6384 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6385 VT.getVectorNumElements() / 2);
6386 if (SplitV0) {
6387 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006388 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006389 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006390 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006391 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006392 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006393 }
6394 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6395}
6396
6397/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6398/// the specified operations to build the shuffle.
6399static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6400 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006401 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006402 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6403 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6404 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6405
6406 enum {
6407 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6408 OP_VREV,
6409 OP_VDUP0,
6410 OP_VDUP1,
6411 OP_VDUP2,
6412 OP_VDUP3,
6413 OP_VEXT1,
6414 OP_VEXT2,
6415 OP_VEXT3,
6416 OP_VUZPL, // VUZP, left result
6417 OP_VUZPR, // VUZP, right result
6418 OP_VZIPL, // VZIP, left result
6419 OP_VZIPR, // VZIP, right result
6420 OP_VTRNL, // VTRN, left result
6421 OP_VTRNR // VTRN, right result
6422 };
6423
6424 if (OpNum == OP_COPY) {
6425 if (LHSID == (1 * 9 + 2) * 9 + 3)
6426 return LHS;
6427 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6428 return RHS;
6429 }
6430
6431 SDValue OpLHS, OpRHS;
6432 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6433 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6434 EVT VT = OpLHS.getValueType();
6435
6436 switch (OpNum) {
6437 default:
6438 llvm_unreachable("Unknown shuffle opcode!");
6439 case OP_VREV:
6440 // VREV divides the vector in half and swaps within the half.
6441 if (VT.getVectorElementType() == MVT::i32 ||
6442 VT.getVectorElementType() == MVT::f32)
6443 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6444 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006445 if (VT.getVectorElementType() == MVT::i16 ||
6446 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006447 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6448 // vrev <4 x i8> -> REV16
6449 assert(VT.getVectorElementType() == MVT::i8);
6450 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6451 case OP_VDUP0:
6452 case OP_VDUP1:
6453 case OP_VDUP2:
6454 case OP_VDUP3: {
6455 EVT EltTy = VT.getVectorElementType();
6456 unsigned Opcode;
6457 if (EltTy == MVT::i8)
6458 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006459 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006460 Opcode = AArch64ISD::DUPLANE16;
6461 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6462 Opcode = AArch64ISD::DUPLANE32;
6463 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6464 Opcode = AArch64ISD::DUPLANE64;
6465 else
6466 llvm_unreachable("Invalid vector element type?");
6467
6468 if (VT.getSizeInBits() == 64)
6469 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006470 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006471 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6472 }
6473 case OP_VEXT1:
6474 case OP_VEXT2:
6475 case OP_VEXT3: {
6476 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6477 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006478 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006479 }
6480 case OP_VUZPL:
6481 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6482 OpRHS);
6483 case OP_VUZPR:
6484 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6485 OpRHS);
6486 case OP_VZIPL:
6487 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6488 OpRHS);
6489 case OP_VZIPR:
6490 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6491 OpRHS);
6492 case OP_VTRNL:
6493 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6494 OpRHS);
6495 case OP_VTRNR:
6496 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6497 OpRHS);
6498 }
6499}
6500
6501static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6502 SelectionDAG &DAG) {
6503 // Check to see if we can use the TBL instruction.
6504 SDValue V1 = Op.getOperand(0);
6505 SDValue V2 = Op.getOperand(1);
6506 SDLoc DL(Op);
6507
6508 EVT EltVT = Op.getValueType().getVectorElementType();
6509 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6510
6511 SmallVector<SDValue, 8> TBLMask;
6512 for (int Val : ShuffleMask) {
6513 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6514 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006515 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006516 }
6517 }
6518
6519 MVT IndexVT = MVT::v8i8;
6520 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006521 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006522 IndexVT = MVT::v16i8;
6523 IndexLen = 16;
6524 }
6525
6526 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6527 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6528
6529 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006530 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006531 if (IndexLen == 8)
6532 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6533 Shuffle = DAG.getNode(
6534 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006535 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006536 DAG.getBuildVector(IndexVT, DL,
6537 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006538 } else {
6539 if (IndexLen == 8) {
6540 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6541 Shuffle = DAG.getNode(
6542 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006543 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006544 DAG.getBuildVector(IndexVT, DL,
6545 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006546 } else {
6547 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6548 // cannot currently represent the register constraints on the input
6549 // table registers.
6550 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006551 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6552 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006553 Shuffle = DAG.getNode(
6554 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006555 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6556 V2Cst, DAG.getBuildVector(IndexVT, DL,
6557 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006558 }
6559 }
6560 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6561}
6562
6563static unsigned getDUPLANEOp(EVT EltType) {
6564 if (EltType == MVT::i8)
6565 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006566 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006567 return AArch64ISD::DUPLANE16;
6568 if (EltType == MVT::i32 || EltType == MVT::f32)
6569 return AArch64ISD::DUPLANE32;
6570 if (EltType == MVT::i64 || EltType == MVT::f64)
6571 return AArch64ISD::DUPLANE64;
6572
6573 llvm_unreachable("Invalid vector element type?");
6574}
6575
6576SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6577 SelectionDAG &DAG) const {
6578 SDLoc dl(Op);
6579 EVT VT = Op.getValueType();
6580
6581 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6582
6583 // Convert shuffles that are directly supported on NEON to target-specific
6584 // DAG nodes, instead of keeping them as shuffles and matching them again
6585 // during code selection. This is more efficient and avoids the possibility
6586 // of inconsistencies between legalization and selection.
6587 ArrayRef<int> ShuffleMask = SVN->getMask();
6588
6589 SDValue V1 = Op.getOperand(0);
6590 SDValue V2 = Op.getOperand(1);
6591
Craig Topperbc56e3b2016-06-30 04:38:51 +00006592 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006593 int Lane = SVN->getSplatIndex();
6594 // If this is undef splat, generate it via "just" vdup, if possible.
6595 if (Lane == -1)
6596 Lane = 0;
6597
6598 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6599 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6600 V1.getOperand(0));
6601 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6602 // constant. If so, we can just reference the lane's definition directly.
6603 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6604 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6605 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6606
6607 // Otherwise, duplicate from the lane of the input vector.
6608 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6609
6610 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6611 // to make a vector of the same size as this SHUFFLE. We can ignore the
6612 // extract entirely, and canonicalise the concat using WidenVector.
6613 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6614 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6615 V1 = V1.getOperand(0);
6616 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6617 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6618 Lane -= Idx * VT.getVectorNumElements() / 2;
6619 V1 = WidenVector(V1.getOperand(Idx), DAG);
6620 } else if (VT.getSizeInBits() == 64)
6621 V1 = WidenVector(V1, DAG);
6622
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006623 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006624 }
6625
6626 if (isREVMask(ShuffleMask, VT, 64))
6627 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6628 if (isREVMask(ShuffleMask, VT, 32))
6629 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6630 if (isREVMask(ShuffleMask, VT, 16))
6631 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6632
6633 bool ReverseEXT = false;
6634 unsigned Imm;
6635 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6636 if (ReverseEXT)
6637 std::swap(V1, V2);
6638 Imm *= getExtFactor(V1);
6639 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006640 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006641 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006642 Imm *= getExtFactor(V1);
6643 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006644 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006645 }
6646
6647 unsigned WhichResult;
6648 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6649 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6650 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6651 }
6652 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6653 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6654 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6655 }
6656 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6657 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6658 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6659 }
6660
6661 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6662 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6663 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6664 }
6665 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6666 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6667 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6668 }
6669 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6670 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6671 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6672 }
6673
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006674 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006675 return Concat;
6676
6677 bool DstIsLeft;
6678 int Anomaly;
6679 int NumInputElements = V1.getValueType().getVectorNumElements();
6680 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6681 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006682 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006683
6684 SDValue SrcVec = V1;
6685 int SrcLane = ShuffleMask[Anomaly];
6686 if (SrcLane >= NumInputElements) {
6687 SrcVec = V2;
6688 SrcLane -= VT.getVectorNumElements();
6689 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006690 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006691
6692 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006693
6694 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006695 ScalarVT = MVT::i32;
6696
6697 return DAG.getNode(
6698 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6699 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6700 DstLaneV);
6701 }
6702
6703 // If the shuffle is not directly supported and it has 4 elements, use
6704 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6705 unsigned NumElts = VT.getVectorNumElements();
6706 if (NumElts == 4) {
6707 unsigned PFIndexes[4];
6708 for (unsigned i = 0; i != 4; ++i) {
6709 if (ShuffleMask[i] < 0)
6710 PFIndexes[i] = 8;
6711 else
6712 PFIndexes[i] = ShuffleMask[i];
6713 }
6714
6715 // Compute the index in the perfect shuffle table.
6716 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6717 PFIndexes[2] * 9 + PFIndexes[3];
6718 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6719 unsigned Cost = (PFEntry >> 30);
6720
6721 if (Cost <= 4)
6722 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6723 }
6724
6725 return GenerateTBL(Op, ShuffleMask, DAG);
6726}
6727
6728static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6729 APInt &UndefBits) {
6730 EVT VT = BVN->getValueType(0);
6731 APInt SplatBits, SplatUndef;
6732 unsigned SplatBitSize;
6733 bool HasAnyUndefs;
6734 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6735 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6736
6737 for (unsigned i = 0; i < NumSplats; ++i) {
6738 CnstBits <<= SplatBitSize;
6739 UndefBits <<= SplatBitSize;
6740 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6741 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6742 }
6743
6744 return true;
6745 }
6746
6747 return false;
6748}
6749
Evandro Menezes72f39832018-02-20 20:31:45 +00006750// Try 64-bit splatted SIMD immediate.
6751static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6752 const APInt &Bits) {
6753 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6754 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6755 EVT VT = Op.getValueType();
6756 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6757
6758 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6759 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6760
6761 SDLoc dl(Op);
6762 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6763 DAG.getConstant(Value, dl, MVT::i32));
6764 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6765 }
6766 }
6767
6768 return SDValue();
6769}
6770
6771// Try 32-bit splatted SIMD immediate.
6772static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6773 const APInt &Bits,
6774 const SDValue *LHS = nullptr) {
6775 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6776 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6777 EVT VT = Op.getValueType();
6778 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6779 bool isAdvSIMDModImm = false;
6780 uint64_t Shift;
6781
6782 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6783 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6784 Shift = 0;
6785 }
6786 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6787 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6788 Shift = 8;
6789 }
6790 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6791 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6792 Shift = 16;
6793 }
6794 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6795 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6796 Shift = 24;
6797 }
6798
6799 if (isAdvSIMDModImm) {
6800 SDLoc dl(Op);
6801 SDValue Mov;
6802
6803 if (LHS)
6804 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6805 DAG.getConstant(Value, dl, MVT::i32),
6806 DAG.getConstant(Shift, dl, MVT::i32));
6807 else
6808 Mov = DAG.getNode(NewOp, dl, MovTy,
6809 DAG.getConstant(Value, dl, MVT::i32),
6810 DAG.getConstant(Shift, dl, MVT::i32));
6811
6812 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6813 }
6814 }
6815
6816 return SDValue();
6817}
6818
6819// Try 16-bit splatted SIMD immediate.
6820static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6821 const APInt &Bits,
6822 const SDValue *LHS = nullptr) {
6823 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6824 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6825 EVT VT = Op.getValueType();
6826 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6827 bool isAdvSIMDModImm = false;
6828 uint64_t Shift;
6829
6830 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6831 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6832 Shift = 0;
6833 }
6834 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6835 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6836 Shift = 8;
6837 }
6838
6839 if (isAdvSIMDModImm) {
6840 SDLoc dl(Op);
6841 SDValue Mov;
6842
6843 if (LHS)
6844 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006845 DAG.getConstant(Value, dl, MVT::i32),
6846 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006847 else
6848 Mov = DAG.getNode(NewOp, dl, MovTy,
6849 DAG.getConstant(Value, dl, MVT::i32),
6850 DAG.getConstant(Shift, dl, MVT::i32));
6851
6852 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6853 }
6854 }
6855
6856 return SDValue();
6857}
6858
6859// Try 32-bit splatted SIMD immediate with shifted ones.
6860static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6861 SelectionDAG &DAG, const APInt &Bits) {
6862 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6863 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6864 EVT VT = Op.getValueType();
6865 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6866 bool isAdvSIMDModImm = false;
6867 uint64_t Shift;
6868
6869 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6870 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6871 Shift = 264;
6872 }
6873 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6874 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6875 Shift = 272;
6876 }
6877
6878 if (isAdvSIMDModImm) {
6879 SDLoc dl(Op);
6880 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6881 DAG.getConstant(Value, dl, MVT::i32),
6882 DAG.getConstant(Shift, dl, MVT::i32));
6883 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6884 }
6885 }
6886
6887 return SDValue();
6888}
6889
6890// Try 8-bit splatted SIMD immediate.
6891static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6892 const APInt &Bits) {
6893 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6894 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6895 EVT VT = Op.getValueType();
6896 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6897
6898 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6899 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6900
6901 SDLoc dl(Op);
6902 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6903 DAG.getConstant(Value, dl, MVT::i32));
6904 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6905 }
6906 }
6907
6908 return SDValue();
6909}
6910
6911// Try FP splatted SIMD immediate.
6912static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6913 const APInt &Bits) {
6914 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6915 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6916 EVT VT = Op.getValueType();
6917 bool isWide = (VT.getSizeInBits() == 128);
6918 MVT MovTy;
6919 bool isAdvSIMDModImm = false;
6920
6921 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6922 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6923 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6924 }
6925 else if (isWide &&
6926 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6927 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6928 MovTy = MVT::v2f64;
6929 }
6930
6931 if (isAdvSIMDModImm) {
6932 SDLoc dl(Op);
6933 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6934 DAG.getConstant(Value, dl, MVT::i32));
6935 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6936 }
6937 }
6938
6939 return SDValue();
6940}
6941
Tim Northover3b0846e2014-05-24 12:50:23 +00006942SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6943 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006944 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006945 EVT VT = Op.getValueType();
6946
Evandro Menezes72f39832018-02-20 20:31:45 +00006947 BuildVectorSDNode *BVN =
6948 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6949 if (!BVN) {
6950 // AND commutes, so try swapping the operands.
6951 LHS = Op.getOperand(1);
6952 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6953 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006954 if (!BVN)
6955 return Op;
6956
Evandro Menezes72f39832018-02-20 20:31:45 +00006957 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006958 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006959 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6960 SDValue NewOp;
6961
Tim Northover3b0846e2014-05-24 12:50:23 +00006962 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006963 DefBits = ~DefBits;
6964 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6965 DefBits, &LHS)) ||
6966 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6967 DefBits, &LHS)))
6968 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006969
6970 UndefBits = ~UndefBits;
6971 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6972 UndefBits, &LHS)) ||
6973 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6974 UndefBits, &LHS)))
6975 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006976 }
6977
Evandro Menezes72f39832018-02-20 20:31:45 +00006978 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006979 return Op;
6980}
6981
6982// Specialized code to quickly find if PotentialBVec is a BuildVector that
6983// consists of only the same constant int value, returned in reference arg
6984// ConstVal
6985static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6986 uint64_t &ConstVal) {
6987 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6988 if (!Bvec)
6989 return false;
6990 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6991 if (!FirstElt)
6992 return false;
6993 EVT VT = Bvec->getValueType(0);
6994 unsigned NumElts = VT.getVectorNumElements();
6995 for (unsigned i = 1; i < NumElts; ++i)
6996 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6997 return false;
6998 ConstVal = FirstElt->getZExtValue();
6999 return true;
7000}
7001
7002static unsigned getIntrinsicID(const SDNode *N) {
7003 unsigned Opcode = N->getOpcode();
7004 switch (Opcode) {
7005 default:
7006 return Intrinsic::not_intrinsic;
7007 case ISD::INTRINSIC_WO_CHAIN: {
7008 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7009 if (IID < Intrinsic::num_intrinsics)
7010 return IID;
7011 return Intrinsic::not_intrinsic;
7012 }
7013 }
7014}
7015
7016// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7017// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7018// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7019// Also, logical shift right -> sri, with the same structure.
7020static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7021 EVT VT = N->getValueType(0);
7022
7023 if (!VT.isVector())
7024 return SDValue();
7025
7026 SDLoc DL(N);
7027
7028 // Is the first op an AND?
7029 const SDValue And = N->getOperand(0);
7030 if (And.getOpcode() != ISD::AND)
7031 return SDValue();
7032
7033 // Is the second op an shl or lshr?
7034 SDValue Shift = N->getOperand(1);
7035 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7036 // or AArch64ISD::VLSHR vector, #shift
7037 unsigned ShiftOpc = Shift.getOpcode();
7038 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7039 return SDValue();
7040 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7041
7042 // Is the shift amount constant?
7043 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7044 if (!C2node)
7045 return SDValue();
7046
7047 // Is the and mask vector all constant?
7048 uint64_t C1;
7049 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7050 return SDValue();
7051
7052 // Is C1 == ~C2, taking into account how much one can shift elements of a
7053 // particular size?
7054 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007055 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007056 if (C2 > ElemSizeInBits)
7057 return SDValue();
7058 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7059 if ((C1 & ElemMask) != (~C2 & ElemMask))
7060 return SDValue();
7061
7062 SDValue X = And.getOperand(0);
7063 SDValue Y = Shift.getOperand(0);
7064
7065 unsigned Intrin =
7066 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7067 SDValue ResultSLI =
7068 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007069 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7070 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007071
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007072 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7073 LLVM_DEBUG(N->dump(&DAG));
7074 LLVM_DEBUG(dbgs() << "into: \n");
7075 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007076
7077 ++NumShiftInserts;
7078 return ResultSLI;
7079}
7080
7081SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7082 SelectionDAG &DAG) const {
7083 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7084 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007085 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007086 return Res;
7087 }
7088
Tim Northover3b0846e2014-05-24 12:50:23 +00007089 EVT VT = Op.getValueType();
7090
Evandro Menezescd855f72018-03-05 17:02:47 +00007091 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007092 BuildVectorSDNode *BVN =
7093 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007094 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007095 // OR commutes, so try swapping the operands.
7096 LHS = Op.getOperand(1);
7097 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007098 }
7099 if (!BVN)
7100 return Op;
7101
Evandro Menezes72f39832018-02-20 20:31:45 +00007102 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007103 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007104 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7105 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007106
Evandro Menezes72f39832018-02-20 20:31:45 +00007107 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7108 DefBits, &LHS)) ||
7109 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7110 DefBits, &LHS)))
7111 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007112
7113 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7114 UndefBits, &LHS)) ||
7115 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7116 UndefBits, &LHS)))
7117 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007118 }
7119
Evandro Menezes72f39832018-02-20 20:31:45 +00007120 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007121 return Op;
7122}
7123
Kevin Qin4473c192014-07-07 02:45:40 +00007124// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7125// be truncated to fit element width.
7126static SDValue NormalizeBuildVector(SDValue Op,
7127 SelectionDAG &DAG) {
7128 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007129 SDLoc dl(Op);
7130 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007131 EVT EltTy= VT.getVectorElementType();
7132
7133 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7134 return Op;
7135
7136 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007137 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007138 // For integer vectors, type legalization would have promoted the
7139 // operands already. Otherwise, if Op is a floating-point splat
7140 // (with operands cast to integers), then the only possibilities
7141 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007142 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007143 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007144 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007145 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007146 } else if (Lane.getNode()->isUndef()) {
7147 Lane = DAG.getUNDEF(MVT::i32);
7148 } else {
7149 assert(Lane.getValueType() == MVT::i32 &&
7150 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007151 }
7152 Ops.push_back(Lane);
7153 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007154 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007155}
7156
Evandro Menezescd855f72018-03-05 17:02:47 +00007157static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007158 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007159
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 Menezescd855f72018-03-05 17:02:47 +00007162 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007163 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007164 SDValue NewOp;
7165 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7166 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7167 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7168 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7169 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7170 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7171 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007172
Evandro Menezes72f39832018-02-20 20:31:45 +00007173 DefBits = ~DefBits;
7174 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7175 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7176 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7177 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007178
Evandro Menezes72f39832018-02-20 20:31:45 +00007179 DefBits = UndefBits;
7180 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7181 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7182 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7183 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7184 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7185 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7186 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007187
Evandro Menezes72f39832018-02-20 20:31:45 +00007188 DefBits = ~UndefBits;
7189 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7190 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7191 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7192 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007193 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007194
Evandro Menezescd855f72018-03-05 17:02:47 +00007195 return SDValue();
7196}
7197
7198SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7199 SelectionDAG &DAG) const {
7200 EVT VT = Op.getValueType();
7201
7202 // Try to build a simple constant vector.
7203 Op = NormalizeBuildVector(Op, DAG);
7204 if (VT.isInteger()) {
7205 // Certain vector constants, used to express things like logical NOT and
7206 // arithmetic NEG, are passed through unmodified. This allows special
7207 // patterns for these operations to match, which will lower these constants
7208 // to whatever is proven necessary.
7209 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7210 if (BVN->isConstant())
7211 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7212 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7213 APInt Val(BitSize,
7214 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7215 if (Val.isNullValue() || Val.isAllOnesValue())
7216 return Op;
7217 }
7218 }
7219
7220 if (SDValue V = ConstantBuildVector(Op, DAG))
7221 return V;
7222
Tim Northover3b0846e2014-05-24 12:50:23 +00007223 // Scan through the operands to find some interesting properties we can
7224 // exploit:
7225 // 1) If only one value is used, we can use a DUP, or
7226 // 2) if only the low element is not undef, we can just insert that, or
7227 // 3) if only one constant value is used (w/ some non-constant lanes),
7228 // we can splat the constant value into the whole vector then fill
7229 // in the non-constant lanes.
7230 // 4) FIXME: If different constant values are used, but we can intelligently
7231 // select the values we'll be overwriting for the non-constant
7232 // lanes such that we can directly materialize the vector
7233 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007234 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007235 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007236 unsigned NumElts = VT.getVectorNumElements();
7237 bool isOnlyLowElement = true;
7238 bool usesOnlyOneValue = true;
7239 bool usesOnlyOneConstantValue = true;
7240 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007241 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007242 unsigned NumConstantLanes = 0;
7243 SDValue Value;
7244 SDValue ConstantValue;
7245 for (unsigned i = 0; i < NumElts; ++i) {
7246 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007247 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7248 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007249 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007250 continue;
7251 if (i > 0)
7252 isOnlyLowElement = false;
7253 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7254 isConstant = false;
7255
7256 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7257 ++NumConstantLanes;
7258 if (!ConstantValue.getNode())
7259 ConstantValue = V;
7260 else if (ConstantValue != V)
7261 usesOnlyOneConstantValue = false;
7262 }
7263
7264 if (!Value.getNode())
7265 Value = V;
7266 else if (V != Value)
7267 usesOnlyOneValue = false;
7268 }
7269
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007270 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007271 LLVM_DEBUG(
7272 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007273 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007274 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007275
John Brawnd6e0ebe2018-11-22 11:45:23 +00007276 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7277 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7278 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7279 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007280 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7281 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007282 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007283 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007284
Sebastian Popc33af712018-03-01 15:47:39 +00007285 if (AllLanesExtractElt) {
7286 SDNode *Vector = nullptr;
7287 bool Even = false;
7288 bool Odd = false;
7289 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7290 // the Odd pattern <1,3,5,...>.
7291 for (unsigned i = 0; i < NumElts; ++i) {
7292 SDValue V = Op.getOperand(i);
7293 const SDNode *N = V.getNode();
7294 if (!isa<ConstantSDNode>(N->getOperand(1)))
7295 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007296 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007297
7298 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007299 if (!Vector) {
7300 Vector = N0.getNode();
7301 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7302 // BUILD_VECTOR.
7303 if (VT.getVectorElementType() !=
7304 N0.getValueType().getVectorElementType())
7305 break;
7306 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007307 Odd = false;
7308 Even = false;
7309 break;
7310 }
7311
7312 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7313 // indices <1,3,5,...>.
7314 uint64_t Val = N->getConstantOperandVal(1);
7315 if (Val == 2 * i) {
7316 Even = true;
7317 continue;
7318 }
7319 if (Val - 1 == 2 * i) {
7320 Odd = true;
7321 continue;
7322 }
7323
7324 // Something does not match: abort.
7325 Odd = false;
7326 Even = false;
7327 break;
7328 }
7329 if (Even || Odd) {
7330 SDValue LHS =
7331 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7332 DAG.getConstant(0, dl, MVT::i64));
7333 SDValue RHS =
7334 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7335 DAG.getConstant(NumElts, dl, MVT::i64));
7336
7337 if (Even && !Odd)
7338 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7339 RHS);
7340 if (Odd && !Even)
7341 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7342 RHS);
7343 }
7344 }
7345
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007346 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007347 // i32 and try again.
7348 if (usesOnlyOneValue) {
7349 if (!isConstant) {
7350 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007351 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007352 LLVM_DEBUG(
7353 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007354 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007355 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007356
7357 // This is actually a DUPLANExx operation, which keeps everything vectory.
7358
Tim Northover3b0846e2014-05-24 12:50:23 +00007359 SDValue Lane = Value.getOperand(1);
7360 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007361 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007362 LLVM_DEBUG(
7363 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7364 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007365 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007366 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007367
7368 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7369 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7370 }
7371
7372 if (VT.getVectorElementType().isFloatingPoint()) {
7373 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007374 EVT EltTy = VT.getVectorElementType();
7375 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7376 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007377 LLVM_DEBUG(
7378 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7379 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007380 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007381 for (unsigned i = 0; i < NumElts; ++i)
7382 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7383 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007384 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007385 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7386 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007387 Val = LowerBUILD_VECTOR(Val, DAG);
7388 if (Val.getNode())
7389 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7390 }
7391 }
7392
7393 // If there was only one constant value used and for more than one lane,
7394 // start by splatting that value, then replace the non-constant lanes. This
7395 // is better than the default, which will perform a separate initialization
7396 // for each lane.
7397 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007398 // Firstly, try to materialize the splat constant.
7399 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7400 Val = ConstantBuildVector(Vec, DAG);
7401 if (!Val) {
7402 // Otherwise, materialize the constant and splat it.
7403 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7404 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7405 }
7406
Tim Northover3b0846e2014-05-24 12:50:23 +00007407 // Now insert the non-constant lanes.
7408 for (unsigned i = 0; i < NumElts; ++i) {
7409 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007410 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007411 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007412 // Note that type legalization likely mucked about with the VT of the
7413 // source operand, so we may have to convert it here before inserting.
7414 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007415 }
7416 return Val;
7417 }
7418
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007419 // This will generate a load from the constant pool.
7420 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007421 LLVM_DEBUG(
7422 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7423 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007424 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007425 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007426
7427 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7428 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007429 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007430 return shuffle;
7431 }
7432
7433 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7434 // know the default expansion would otherwise fall back on something even
7435 // worse. For a vector with one or two non-undef values, that's
7436 // scalar_to_vector for the elements followed by a shuffle (provided the
7437 // shuffle is valid for the target) and materialization element by element
7438 // on the stack followed by a load for everything else.
7439 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007440 LLVM_DEBUG(
7441 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7442 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007443
Tim Northover3b0846e2014-05-24 12:50:23 +00007444 SDValue Vec = DAG.getUNDEF(VT);
7445 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007446 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007447
7448 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007449 // a) Avoid a RMW dependency on the full vector register, and
7450 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007451 // value is already in an S or D register, and we're forced to emit an
7452 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007453 //
7454 // We also allow types like i8 and i16 which are illegal scalar but legal
7455 // vector element types. After type-legalization the inserted value is
7456 // extended (i32) and it is safe to cast them to the vector type by ignoring
7457 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7458 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007459 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007460 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007461 ++i;
7462 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007463 LLVM_DEBUG(if (i < NumElts) dbgs()
7464 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007465 for (; i < NumElts; ++i) {
7466 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007467 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007468 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007469 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007470 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7471 }
7472 return Vec;
7473 }
7474
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007475 LLVM_DEBUG(
7476 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7477 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007478 return SDValue();
7479}
7480
7481SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7482 SelectionDAG &DAG) const {
7483 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7484
Tim Northovere4b8e132014-07-15 10:00:26 +00007485 // Check for non-constant or out of range lane.
7486 EVT VT = Op.getOperand(0).getValueType();
7487 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7488 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007489 return SDValue();
7490
Tim Northover3b0846e2014-05-24 12:50:23 +00007491
7492 // Insertion/extraction are legal for V128 types.
7493 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007494 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7495 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007496 return Op;
7497
7498 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007499 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007500 return SDValue();
7501
7502 // For V64 types, we perform insertion by expanding the value
7503 // to a V128 type and perform the insertion on that.
7504 SDLoc DL(Op);
7505 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7506 EVT WideTy = WideVec.getValueType();
7507
7508 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7509 Op.getOperand(1), Op.getOperand(2));
7510 // Re-narrow the resultant vector.
7511 return NarrowVector(Node, DAG);
7512}
7513
7514SDValue
7515AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7516 SelectionDAG &DAG) const {
7517 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7518
Tim Northovere4b8e132014-07-15 10:00:26 +00007519 // Check for non-constant or out of range lane.
7520 EVT VT = Op.getOperand(0).getValueType();
7521 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7522 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007523 return SDValue();
7524
Tim Northover3b0846e2014-05-24 12:50:23 +00007525
7526 // Insertion/extraction are legal for V128 types.
7527 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007528 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7529 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007530 return Op;
7531
7532 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007533 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007534 return SDValue();
7535
7536 // For V64 types, we perform extraction by expanding the value
7537 // to a V128 type and perform the extraction on that.
7538 SDLoc DL(Op);
7539 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7540 EVT WideTy = WideVec.getValueType();
7541
7542 EVT ExtrTy = WideTy.getVectorElementType();
7543 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7544 ExtrTy = MVT::i32;
7545
7546 // For extractions, we just return the result directly.
7547 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7548 Op.getOperand(1));
7549}
7550
7551SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7552 SelectionDAG &DAG) const {
7553 EVT VT = Op.getOperand(0).getValueType();
7554 SDLoc dl(Op);
7555 // Just in case...
7556 if (!VT.isVector())
7557 return SDValue();
7558
7559 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7560 if (!Cst)
7561 return SDValue();
7562 unsigned Val = Cst->getZExtValue();
7563
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007564 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007565
7566 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7567 if (Val == 0)
7568 return Op;
7569
Tim Northover3b0846e2014-05-24 12:50:23 +00007570 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7571 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007572 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007573 return Op;
7574
7575 return SDValue();
7576}
7577
Zvi Rackover1b736822017-07-26 08:06:58 +00007578bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007579 if (VT.getVectorNumElements() == 4 &&
7580 (VT.is128BitVector() || VT.is64BitVector())) {
7581 unsigned PFIndexes[4];
7582 for (unsigned i = 0; i != 4; ++i) {
7583 if (M[i] < 0)
7584 PFIndexes[i] = 8;
7585 else
7586 PFIndexes[i] = M[i];
7587 }
7588
7589 // Compute the index in the perfect shuffle table.
7590 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7591 PFIndexes[2] * 9 + PFIndexes[3];
7592 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7593 unsigned Cost = (PFEntry >> 30);
7594
7595 if (Cost <= 4)
7596 return true;
7597 }
7598
7599 bool DummyBool;
7600 int DummyInt;
7601 unsigned DummyUnsigned;
7602
7603 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7604 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7605 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7606 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7607 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7608 isZIPMask(M, VT, DummyUnsigned) ||
7609 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7610 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7611 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7612 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7613 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7614}
7615
7616/// getVShiftImm - Check if this is a valid build_vector for the immediate
7617/// operand of a vector shift operation, where all the elements of the
7618/// build_vector must have the same constant integer value.
7619static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7620 // Ignore bit_converts.
7621 while (Op.getOpcode() == ISD::BITCAST)
7622 Op = Op.getOperand(0);
7623 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7624 APInt SplatBits, SplatUndef;
7625 unsigned SplatBitSize;
7626 bool HasAnyUndefs;
7627 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7628 HasAnyUndefs, ElementBits) ||
7629 SplatBitSize > ElementBits)
7630 return false;
7631 Cnt = SplatBits.getSExtValue();
7632 return true;
7633}
7634
7635/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7636/// operand of a vector shift left operation. That value must be in the range:
7637/// 0 <= Value < ElementBits for a left shift; or
7638/// 0 <= Value <= ElementBits for a long left shift.
7639static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7640 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007641 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007642 if (!getVShiftImm(Op, ElementBits, Cnt))
7643 return false;
7644 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7645}
7646
7647/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007648/// operand of a vector shift right operation. The value must be in the range:
7649/// 1 <= Value <= ElementBits for a right shift; or
7650static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007651 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007652 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007653 if (!getVShiftImm(Op, ElementBits, Cnt))
7654 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007655 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7656}
7657
7658SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7659 SelectionDAG &DAG) const {
7660 EVT VT = Op.getValueType();
7661 SDLoc DL(Op);
7662 int64_t Cnt;
7663
7664 if (!Op.getOperand(1).getValueType().isVector())
7665 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007666 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007667
7668 switch (Op.getOpcode()) {
7669 default:
7670 llvm_unreachable("unexpected shift opcode");
7671
7672 case ISD::SHL:
7673 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007674 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7675 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007676 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007677 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7678 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007679 Op.getOperand(0), Op.getOperand(1));
7680 case ISD::SRA:
7681 case ISD::SRL:
7682 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007683 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007684 unsigned Opc =
7685 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007686 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7687 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007688 }
7689
7690 // Right shift register. Note, there is not a shift right register
7691 // instruction, but the shift left register instruction takes a signed
7692 // value, where negative numbers specify a right shift.
7693 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7694 : Intrinsic::aarch64_neon_ushl;
7695 // negate the shift amount
7696 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7697 SDValue NegShiftLeft =
7698 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007699 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7700 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007701 return NegShiftLeft;
7702 }
7703
7704 return SDValue();
7705}
7706
7707static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7708 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007709 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007710 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007711 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7712 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007713
7714 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7715 APInt CnstBits(VT.getSizeInBits(), 0);
7716 APInt UndefBits(VT.getSizeInBits(), 0);
7717 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7718 bool IsZero = IsCnst && (CnstBits == 0);
7719
7720 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7721 switch (CC) {
7722 default:
7723 return SDValue();
7724 case AArch64CC::NE: {
7725 SDValue Fcmeq;
7726 if (IsZero)
7727 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7728 else
7729 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7730 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7731 }
7732 case AArch64CC::EQ:
7733 if (IsZero)
7734 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7735 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7736 case AArch64CC::GE:
7737 if (IsZero)
7738 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7739 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7740 case AArch64CC::GT:
7741 if (IsZero)
7742 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7743 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7744 case AArch64CC::LS:
7745 if (IsZero)
7746 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7747 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7748 case AArch64CC::LT:
7749 if (!NoNans)
7750 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007751 // If we ignore NaNs then we can use to the MI implementation.
7752 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007753 case AArch64CC::MI:
7754 if (IsZero)
7755 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7756 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7757 }
7758 }
7759
7760 switch (CC) {
7761 default:
7762 return SDValue();
7763 case AArch64CC::NE: {
7764 SDValue Cmeq;
7765 if (IsZero)
7766 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7767 else
7768 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7769 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7770 }
7771 case AArch64CC::EQ:
7772 if (IsZero)
7773 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7774 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7775 case AArch64CC::GE:
7776 if (IsZero)
7777 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7778 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7779 case AArch64CC::GT:
7780 if (IsZero)
7781 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7782 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7783 case AArch64CC::LE:
7784 if (IsZero)
7785 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7786 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7787 case AArch64CC::LS:
7788 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7789 case AArch64CC::LO:
7790 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7791 case AArch64CC::LT:
7792 if (IsZero)
7793 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7794 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7795 case AArch64CC::HI:
7796 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7797 case AArch64CC::HS:
7798 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7799 }
7800}
7801
7802SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7803 SelectionDAG &DAG) const {
7804 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7805 SDValue LHS = Op.getOperand(0);
7806 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007807 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007808 SDLoc dl(Op);
7809
7810 if (LHS.getValueType().getVectorElementType().isInteger()) {
7811 assert(LHS.getValueType() == RHS.getValueType());
7812 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007813 SDValue Cmp =
7814 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7815 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007816 }
7817
Carey Williamsda15b5b2018-01-22 14:16:11 +00007818 const bool FullFP16 =
7819 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7820
7821 // Make v4f16 (only) fcmp operations utilise vector instructions
7822 // v8f16 support will be a litle more complicated
7823 if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7824 if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7825 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7826 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7827 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7828 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7829 CmpVT = MVT::v4i32;
7830 } else
7831 return SDValue();
7832 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007833
Tim Northover3b0846e2014-05-24 12:50:23 +00007834 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7835 LHS.getValueType().getVectorElementType() == MVT::f64);
7836
7837 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7838 // clean. Some of them require two branches to implement.
7839 AArch64CC::CondCode CC1, CC2;
7840 bool ShouldInvert;
7841 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7842
7843 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7844 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007845 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007846 if (!Cmp.getNode())
7847 return SDValue();
7848
7849 if (CC2 != AArch64CC::AL) {
7850 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007851 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007852 if (!Cmp2.getNode())
7853 return SDValue();
7854
Tim Northover45aa89c2015-02-08 00:50:47 +00007855 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007856 }
7857
Tim Northover45aa89c2015-02-08 00:50:47 +00007858 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7859
Tim Northover3b0846e2014-05-24 12:50:23 +00007860 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007861 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007862
7863 return Cmp;
7864}
7865
Amara Emersonc9916d72017-05-16 21:29:22 +00007866static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7867 SelectionDAG &DAG) {
7868 SDValue VecOp = ScalarOp.getOperand(0);
7869 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7870 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7871 DAG.getConstant(0, DL, MVT::i64));
7872}
7873
7874SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7875 SelectionDAG &DAG) const {
7876 SDLoc dl(Op);
7877 switch (Op.getOpcode()) {
7878 case ISD::VECREDUCE_ADD:
7879 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7880 case ISD::VECREDUCE_SMAX:
7881 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7882 case ISD::VECREDUCE_SMIN:
7883 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7884 case ISD::VECREDUCE_UMAX:
7885 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7886 case ISD::VECREDUCE_UMIN:
7887 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7888 case ISD::VECREDUCE_FMAX: {
7889 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7890 return DAG.getNode(
7891 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7892 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7893 Op.getOperand(0));
7894 }
7895 case ISD::VECREDUCE_FMIN: {
7896 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7897 return DAG.getNode(
7898 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7899 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7900 Op.getOperand(0));
7901 }
7902 default:
7903 llvm_unreachable("Unhandled reduction");
7904 }
7905}
7906
Oliver Stannard42699172018-02-12 14:22:03 +00007907SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7908 SelectionDAG &DAG) const {
7909 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7910 if (!Subtarget.hasLSE())
7911 return SDValue();
7912
7913 // LSE has an atomic load-add instruction, but not a load-sub.
7914 SDLoc dl(Op);
7915 MVT VT = Op.getSimpleValueType();
7916 SDValue RHS = Op.getOperand(2);
7917 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7918 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7919 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7920 Op.getOperand(0), Op.getOperand(1), RHS,
7921 AN->getMemOperand());
7922}
7923
Oliver Stannard02f08c92018-02-12 17:03:11 +00007924SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7925 SelectionDAG &DAG) const {
7926 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7927 if (!Subtarget.hasLSE())
7928 return SDValue();
7929
7930 // LSE has an atomic load-clear instruction, but not a load-and.
7931 SDLoc dl(Op);
7932 MVT VT = Op.getSimpleValueType();
7933 SDValue RHS = Op.getOperand(2);
7934 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7935 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7936 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7937 Op.getOperand(0), Op.getOperand(1), RHS,
7938 AN->getMemOperand());
7939}
7940
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007941SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7942 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7943 SDLoc dl(Op);
7944 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7945 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7946
Tri Vo6c47c622018-09-22 22:17:50 +00007947 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7948 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7949 if (Subtarget->hasCustomCallingConv())
7950 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007951
7952 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7953 DAG.getConstant(4, dl, MVT::i64));
7954 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7955 Chain =
7956 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7957 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7958 DAG.getRegisterMask(Mask), Chain.getValue(1));
7959 // To match the actual intent better, we should read the output from X15 here
7960 // again (instead of potentially spilling it to the stack), but rereading Size
7961 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7962 // here.
7963
7964 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7965 DAG.getConstant(4, dl, MVT::i64));
7966 return Chain;
7967}
7968
7969SDValue
7970AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7971 SelectionDAG &DAG) const {
7972 assert(Subtarget->isTargetWindows() &&
7973 "Only Windows alloca probing supported");
7974 SDLoc dl(Op);
7975 // Get the inputs.
7976 SDNode *Node = Op.getNode();
7977 SDValue Chain = Op.getOperand(0);
7978 SDValue Size = Op.getOperand(1);
7979 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7980 EVT VT = Node->getValueType(0);
7981
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007982 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7983 "no-stack-arg-probe")) {
7984 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7985 Chain = SP.getValue(1);
7986 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7987 if (Align)
7988 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7989 DAG.getConstant(-(uint64_t)Align, dl, VT));
7990 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7991 SDValue Ops[2] = {SP, Chain};
7992 return DAG.getMergeValues(Ops, dl);
7993 }
7994
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007995 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7996
7997 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7998
7999 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8000 Chain = SP.getValue(1);
8001 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00008002 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008003 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8004 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00008005 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008006
8007 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8008 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8009
8010 SDValue Ops[2] = {SP, Chain};
8011 return DAG.getMergeValues(Ops, dl);
8012}
8013
Tim Northover3b0846e2014-05-24 12:50:23 +00008014/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8015/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8016/// specified in the intrinsic calls.
8017bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8018 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00008019 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00008020 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008021 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00008022 switch (Intrinsic) {
8023 case Intrinsic::aarch64_neon_ld2:
8024 case Intrinsic::aarch64_neon_ld3:
8025 case Intrinsic::aarch64_neon_ld4:
8026 case Intrinsic::aarch64_neon_ld1x2:
8027 case Intrinsic::aarch64_neon_ld1x3:
8028 case Intrinsic::aarch64_neon_ld1x4:
8029 case Intrinsic::aarch64_neon_ld2lane:
8030 case Intrinsic::aarch64_neon_ld3lane:
8031 case Intrinsic::aarch64_neon_ld4lane:
8032 case Intrinsic::aarch64_neon_ld2r:
8033 case Intrinsic::aarch64_neon_ld3r:
8034 case Intrinsic::aarch64_neon_ld4r: {
8035 Info.opc = ISD::INTRINSIC_W_CHAIN;
8036 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008037 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008038 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8039 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8040 Info.offset = 0;
8041 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008042 // volatile loads with NEON intrinsics not supported
8043 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008044 return true;
8045 }
8046 case Intrinsic::aarch64_neon_st2:
8047 case Intrinsic::aarch64_neon_st3:
8048 case Intrinsic::aarch64_neon_st4:
8049 case Intrinsic::aarch64_neon_st1x2:
8050 case Intrinsic::aarch64_neon_st1x3:
8051 case Intrinsic::aarch64_neon_st1x4:
8052 case Intrinsic::aarch64_neon_st2lane:
8053 case Intrinsic::aarch64_neon_st3lane:
8054 case Intrinsic::aarch64_neon_st4lane: {
8055 Info.opc = ISD::INTRINSIC_VOID;
8056 // Conservatively set memVT to the entire set of vectors stored.
8057 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008058 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008059 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8060 if (!ArgTy->isVectorTy())
8061 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008062 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008063 }
8064 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8065 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8066 Info.offset = 0;
8067 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008068 // volatile stores with NEON intrinsics not supported
8069 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008070 return true;
8071 }
8072 case Intrinsic::aarch64_ldaxr:
8073 case Intrinsic::aarch64_ldxr: {
8074 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8075 Info.opc = ISD::INTRINSIC_W_CHAIN;
8076 Info.memVT = MVT::getVT(PtrTy->getElementType());
8077 Info.ptrVal = I.getArgOperand(0);
8078 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008079 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008080 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008081 return true;
8082 }
8083 case Intrinsic::aarch64_stlxr:
8084 case Intrinsic::aarch64_stxr: {
8085 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8086 Info.opc = ISD::INTRINSIC_W_CHAIN;
8087 Info.memVT = MVT::getVT(PtrTy->getElementType());
8088 Info.ptrVal = I.getArgOperand(1);
8089 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008090 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008091 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008092 return true;
8093 }
8094 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008095 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008096 Info.opc = ISD::INTRINSIC_W_CHAIN;
8097 Info.memVT = MVT::i128;
8098 Info.ptrVal = I.getArgOperand(0);
8099 Info.offset = 0;
8100 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008101 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008102 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008103 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008104 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008105 Info.opc = ISD::INTRINSIC_W_CHAIN;
8106 Info.memVT = MVT::i128;
8107 Info.ptrVal = I.getArgOperand(2);
8108 Info.offset = 0;
8109 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008110 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008111 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008112 default:
8113 break;
8114 }
8115
8116 return false;
8117}
8118
John Brawne3b44f92018-03-23 14:47:07 +00008119bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8120 ISD::LoadExtType ExtTy,
8121 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008122 // TODO: This may be worth removing. Check regression tests for diffs.
8123 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8124 return false;
8125
John Brawne3b44f92018-03-23 14:47:07 +00008126 // If we're reducing the load width in order to avoid having to use an extra
8127 // instruction to do extension then it's probably a good idea.
8128 if (ExtTy != ISD::NON_EXTLOAD)
8129 return true;
8130 // Don't reduce load width if it would prevent us from combining a shift into
8131 // the offset.
8132 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8133 assert(Mem);
8134 const SDValue &Base = Mem->getBasePtr();
8135 if (Base.getOpcode() == ISD::ADD &&
8136 Base.getOperand(1).getOpcode() == ISD::SHL &&
8137 Base.getOperand(1).hasOneUse() &&
8138 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8139 // The shift can be combined if it matches the size of the value being
8140 // loaded (and so reducing the width would make it not match).
8141 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8142 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8143 if (ShiftAmount == Log2_32(LoadBytes))
8144 return false;
8145 }
8146 // We have no reason to disallow reducing the load width, so allow it.
8147 return true;
8148}
8149
Tim Northover3b0846e2014-05-24 12:50:23 +00008150// Truncations from 64-bit GPR to 32-bit GPR is free.
8151bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8152 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8153 return false;
8154 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8155 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008156 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008157}
8158bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008159 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008160 return false;
8161 unsigned NumBits1 = VT1.getSizeInBits();
8162 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008163 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008164}
8165
Chad Rosier54390052015-02-23 19:15:16 +00008166/// Check if it is profitable to hoist instruction in then/else to if.
8167/// Not profitable if I and it's user can form a FMA instruction
8168/// because we prefer FMSUB/FMADD.
8169bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8170 if (I->getOpcode() != Instruction::FMul)
8171 return true;
8172
Davide Italiano3e9986f2017-04-18 00:29:54 +00008173 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008174 return true;
8175
8176 Instruction *User = I->user_back();
8177
8178 if (User &&
8179 !(User->getOpcode() == Instruction::FSub ||
8180 User->getOpcode() == Instruction::FAdd))
8181 return true;
8182
8183 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008184 const DataLayout &DL = I->getModule()->getDataLayout();
8185 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008186
Eric Christopher114fa1c2016-02-29 22:50:49 +00008187 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8188 isOperationLegalOrCustom(ISD::FMA, VT) &&
8189 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8190 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008191}
8192
Tim Northover3b0846e2014-05-24 12:50:23 +00008193// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8194// 64-bit GPR.
8195bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8196 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8197 return false;
8198 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8199 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008200 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008201}
8202bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008203 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008204 return false;
8205 unsigned NumBits1 = VT1.getSizeInBits();
8206 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008207 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008208}
8209
8210bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8211 EVT VT1 = Val.getValueType();
8212 if (isZExtFree(VT1, VT2)) {
8213 return true;
8214 }
8215
8216 if (Val.getOpcode() != ISD::LOAD)
8217 return false;
8218
8219 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008220 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8221 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8222 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008223}
8224
Quentin Colombet6843ac42015-03-31 20:52:32 +00008225bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8226 if (isa<FPExtInst>(Ext))
8227 return false;
8228
Haicheng Wu50692a22017-08-01 21:26:45 +00008229 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008230 if (Ext->getType()->isVectorTy())
8231 return false;
8232
8233 for (const Use &U : Ext->uses()) {
8234 // The extension is free if we can fold it with a left shift in an
8235 // addressing mode or an arithmetic operation: add, sub, and cmp.
8236
8237 // Is there a shift?
8238 const Instruction *Instr = cast<Instruction>(U.getUser());
8239
8240 // Is this a constant shift?
8241 switch (Instr->getOpcode()) {
8242 case Instruction::Shl:
8243 if (!isa<ConstantInt>(Instr->getOperand(1)))
8244 return false;
8245 break;
8246 case Instruction::GetElementPtr: {
8247 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008248 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008249 std::advance(GTI, U.getOperandNo()-1);
8250 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008251 // This extension will end up with a shift because of the scaling factor.
8252 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8253 // Get the shift amount based on the scaling factor:
8254 // log2(sizeof(IdxTy)) - log2(8).
8255 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008256 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008257 // Is the constant foldable in the shift of the addressing mode?
8258 // I.e., shift amount is between 1 and 4 inclusive.
8259 if (ShiftAmt == 0 || ShiftAmt > 4)
8260 return false;
8261 break;
8262 }
8263 case Instruction::Trunc:
8264 // Check if this is a noop.
8265 // trunc(sext ty1 to ty2) to ty1.
8266 if (Instr->getType() == Ext->getOperand(0)->getType())
8267 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008268 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008269 default:
8270 return false;
8271 }
8272
8273 // At this point we can use the bfm family, so this extension is free
8274 // for that use.
8275 }
8276 return true;
8277}
8278
Tim Northover3b0846e2014-05-24 12:50:23 +00008279bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8280 unsigned &RequiredAligment) const {
8281 if (!LoadedType.isSimple() ||
8282 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8283 return false;
8284 // Cyclone supports unaligned accesses.
8285 RequiredAligment = 0;
8286 unsigned NumBits = LoadedType.getSizeInBits();
8287 return NumBits == 32 || NumBits == 64;
8288}
8289
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008290/// A helper function for determining the number of interleaved accesses we
8291/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008292unsigned
8293AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8294 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008295 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8296}
8297
Geoff Berryb1e87142017-07-14 21:44:12 +00008298MachineMemOperand::Flags
8299AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8300 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8301 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8302 return MOStridedAccess;
8303 return MachineMemOperand::MONone;
8304}
8305
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008306bool AArch64TargetLowering::isLegalInterleavedAccessType(
8307 VectorType *VecTy, const DataLayout &DL) const {
8308
8309 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8310 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8311
8312 // Ensure the number of vector elements is greater than 1.
8313 if (VecTy->getNumElements() < 2)
8314 return false;
8315
8316 // Ensure the element type is legal.
8317 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8318 return false;
8319
8320 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8321 // 128 will be split into multiple interleaved accesses.
8322 return VecSize == 64 || VecSize % 128 == 0;
8323}
8324
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008325/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008326///
8327/// E.g. Lower an interleaved load (Factor = 2):
8328/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8329/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8330/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8331///
8332/// Into:
8333/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8334/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8335/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8336bool AArch64TargetLowering::lowerInterleavedLoad(
8337 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8338 ArrayRef<unsigned> Indices, unsigned Factor) const {
8339 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8340 "Invalid interleave factor");
8341 assert(!Shuffles.empty() && "Empty shufflevector input");
8342 assert(Shuffles.size() == Indices.size() &&
8343 "Unmatched number of shufflevectors and indices");
8344
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008345 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008346
8347 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008348
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008349 // Skip if we do not have NEON and skip illegal vector types. We can
8350 // "legalize" wide vector types into multiple interleaved accesses as long as
8351 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008352 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008353 return false;
8354
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008355 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8356
Hao Liu7ec8ee32015-06-26 02:32:07 +00008357 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8358 // load integer vectors first and then convert to pointer vectors.
8359 Type *EltTy = VecTy->getVectorElementType();
8360 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008361 VecTy =
8362 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008363
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008364 IRBuilder<> Builder(LI);
8365
8366 // The base address of the load.
8367 Value *BaseAddr = LI->getPointerOperand();
8368
8369 if (NumLoads > 1) {
8370 // If we're going to generate more than one load, reset the sub-vector type
8371 // to something legal.
8372 VecTy = VectorType::get(VecTy->getVectorElementType(),
8373 VecTy->getVectorNumElements() / NumLoads);
8374
8375 // We will compute the pointer operand of each load from the original base
8376 // address using GEPs. Cast the base address to a pointer to the scalar
8377 // element type.
8378 BaseAddr = Builder.CreateBitCast(
8379 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8380 LI->getPointerAddressSpace()));
8381 }
8382
Hao Liu7ec8ee32015-06-26 02:32:07 +00008383 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8384 Type *Tys[2] = {VecTy, PtrTy};
8385 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8386 Intrinsic::aarch64_neon_ld3,
8387 Intrinsic::aarch64_neon_ld4};
8388 Function *LdNFunc =
8389 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8390
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008391 // Holds sub-vectors extracted from the load intrinsic return values. The
8392 // sub-vectors are associated with the shufflevector instructions they will
8393 // replace.
8394 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008395
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008396 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008397
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008398 // If we're generating more than one load, compute the base address of
8399 // subsequent loads as an offset from the previous.
8400 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008401 BaseAddr =
8402 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8403 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008404
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008405 CallInst *LdN = Builder.CreateCall(
8406 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008407
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008408 // Extract and store the sub-vectors returned by the load intrinsic.
8409 for (unsigned i = 0; i < Shuffles.size(); i++) {
8410 ShuffleVectorInst *SVI = Shuffles[i];
8411 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008412
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008413 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8414
8415 // Convert the integer vector to pointer vector if the element is pointer.
8416 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008417 SubVec = Builder.CreateIntToPtr(
8418 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8419 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008420 SubVecs[SVI].push_back(SubVec);
8421 }
8422 }
8423
8424 // Replace uses of the shufflevector instructions with the sub-vectors
8425 // returned by the load intrinsic. If a shufflevector instruction is
8426 // associated with more than one sub-vector, those sub-vectors will be
8427 // concatenated into a single wide vector.
8428 for (ShuffleVectorInst *SVI : Shuffles) {
8429 auto &SubVec = SubVecs[SVI];
8430 auto *WideVec =
8431 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8432 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008433 }
8434
8435 return true;
8436}
8437
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008438/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008439///
8440/// E.g. Lower an interleaved store (Factor = 3):
8441/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008442/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008443/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8444///
8445/// Into:
8446/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8447/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8448/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8449/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8450///
8451/// Note that the new shufflevectors will be removed and we'll only generate one
8452/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008453///
8454/// Example for a more general valid mask (Factor 3). Lower:
8455/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8456/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8457/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8458///
8459/// Into:
8460/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8461/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8462/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8463/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008464bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8465 ShuffleVectorInst *SVI,
8466 unsigned Factor) const {
8467 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8468 "Invalid interleave factor");
8469
8470 VectorType *VecTy = SVI->getType();
8471 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8472 "Invalid interleaved store");
8473
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008474 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008475 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008476 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008477
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008478 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008479
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008480 // Skip if we do not have NEON and skip illegal vector types. We can
8481 // "legalize" wide vector types into multiple interleaved accesses as long as
8482 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008483 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008484 return false;
8485
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008486 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8487
Hao Liu7ec8ee32015-06-26 02:32:07 +00008488 Value *Op0 = SVI->getOperand(0);
8489 Value *Op1 = SVI->getOperand(1);
8490 IRBuilder<> Builder(SI);
8491
8492 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8493 // vectors to integer vectors.
8494 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008495 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008496 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008497
8498 // Convert to the corresponding integer vector.
8499 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8500 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8501 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8502
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008503 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008504 }
8505
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008506 // The base address of the store.
8507 Value *BaseAddr = SI->getPointerOperand();
8508
8509 if (NumStores > 1) {
8510 // If we're going to generate more than one store, reset the lane length
8511 // and sub-vector type to something legal.
8512 LaneLen /= NumStores;
8513 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8514
8515 // We will compute the pointer operand of each store from the original base
8516 // address using GEPs. Cast the base address to a pointer to the scalar
8517 // element type.
8518 BaseAddr = Builder.CreateBitCast(
8519 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8520 SI->getPointerAddressSpace()));
8521 }
8522
8523 auto Mask = SVI->getShuffleMask();
8524
Hao Liu7ec8ee32015-06-26 02:32:07 +00008525 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8526 Type *Tys[2] = {SubVecTy, PtrTy};
8527 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8528 Intrinsic::aarch64_neon_st3,
8529 Intrinsic::aarch64_neon_st4};
8530 Function *StNFunc =
8531 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8532
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008533 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008534
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008535 SmallVector<Value *, 5> Ops;
8536
8537 // Split the shufflevector operands into sub vectors for the new stN call.
8538 for (unsigned i = 0; i < Factor; i++) {
8539 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8540 if (Mask[IdxI] >= 0) {
8541 Ops.push_back(Builder.CreateShuffleVector(
8542 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8543 } else {
8544 unsigned StartMask = 0;
8545 for (unsigned j = 1; j < LaneLen; j++) {
8546 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8547 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8548 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8549 break;
8550 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008551 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008552 // Note: Filling undef gaps with random elements is ok, since
8553 // those elements were being written anyway (with undefs).
8554 // In the case of all undefs we're defaulting to using elems from 0
8555 // Note: StartMask cannot be negative, it's checked in
8556 // isReInterleaveMask
8557 Ops.push_back(Builder.CreateShuffleVector(
8558 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008559 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008560 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008561
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008562 // If we generating more than one store, we compute the base address of
8563 // subsequent stores as an offset from the previous.
8564 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008565 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8566 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008567
8568 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8569 Builder.CreateCall(StNFunc, Ops);
8570 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008571 return true;
8572}
8573
Tim Northover3b0846e2014-05-24 12:50:23 +00008574static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8575 unsigned AlignCheck) {
8576 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8577 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8578}
8579
8580EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8581 unsigned SrcAlign, bool IsMemset,
8582 bool ZeroMemset,
8583 bool MemcpyStrSrc,
8584 MachineFunction &MF) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008585 const Function &F = MF.getFunction();
JF Bastien29200612018-09-06 16:03:32 +00008586 bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8587 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8588 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8589 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8590 // taken one instruction to materialize the v2i64 zero and one store (with
8591 // restrictive addressing mode). Just do i64 stores.
8592 bool IsSmallMemset = IsMemset && Size < 32;
8593 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8594 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8595 return true;
8596 bool Fast;
8597 return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8598 };
8599
8600 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8601 AlignmentIsAcceptable(MVT::v2i64, 16))
8602 return MVT::v2i64;
8603 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008604 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008605 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008606 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008607 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008608 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008609 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008610}
8611
8612// 12-bit optionally shifted immediates are legal for adds.
8613bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008614 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008615 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8616 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008617 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008618 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008619 // Same encoding for add/sub, just flip the sign.
8620 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008621 bool IsLegal = ((Immed >> 12) == 0 ||
8622 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008623 LLVM_DEBUG(dbgs() << "Is " << Immed
8624 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008625 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008626}
8627
8628// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8629// immediates is the same as for an add or a sub.
8630bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008631 return isLegalAddImmediate(Immed);
8632}
8633
8634/// isLegalAddressingMode - Return true if the addressing mode represented
8635/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008636bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8637 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008638 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008639 // AArch64 has five basic addressing modes:
8640 // reg
8641 // reg + 9-bit signed offset
8642 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8643 // reg1 + reg2
8644 // reg + SIZE_IN_BYTES * reg
8645
8646 // No global is ever allowed as a base.
8647 if (AM.BaseGV)
8648 return false;
8649
8650 // No reg+reg+imm addressing.
8651 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8652 return false;
8653
8654 // check reg + imm case:
8655 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8656 uint64_t NumBytes = 0;
8657 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008658 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008659 NumBytes = NumBits / 8;
8660 if (!isPowerOf2_64(NumBits))
8661 NumBytes = 0;
8662 }
8663
8664 if (!AM.Scale) {
8665 int64_t Offset = AM.BaseOffs;
8666
8667 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008668 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008669 return true;
8670
8671 // 12-bit unsigned offset
8672 unsigned shift = Log2_64(NumBytes);
8673 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8674 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8675 (Offset >> shift) << shift == Offset)
8676 return true;
8677 return false;
8678 }
8679
8680 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8681
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008682 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008683}
8684
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008685bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8686 // Consider splitting large offset of struct or array.
8687 return true;
8688}
8689
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008690int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8691 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008692 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008693 // Scaling factors are not free at all.
8694 // Operands | Rt Latency
8695 // -------------------------------------------
8696 // Rt, [Xn, Xm] | 4
8697 // -------------------------------------------
8698 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8699 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008700 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008701 // Scale represents reg2 * scale, thus account for 1 if
8702 // it is not equal to 0 or 1.
8703 return AM.Scale != 0 && AM.Scale != 1;
8704 return -1;
8705}
8706
8707bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8708 VT = VT.getScalarType();
8709
8710 if (!VT.isSimple())
8711 return false;
8712
8713 switch (VT.getSimpleVT().SimpleTy) {
8714 case MVT::f32:
8715 case MVT::f64:
8716 return true;
8717 default:
8718 break;
8719 }
8720
8721 return false;
8722}
8723
8724const MCPhysReg *
8725AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8726 // LR is a callee-save register, but we must treat it as clobbered by any call
8727 // site. Hence we include LR in the scratch registers, which are in turn added
8728 // as implicit-defs for stackmaps and patchpoints.
8729 static const MCPhysReg ScratchRegs[] = {
8730 AArch64::X16, AArch64::X17, AArch64::LR, 0
8731 };
8732 return ScratchRegs;
8733}
8734
8735bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008736AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8737 CombineLevel Level) const {
8738 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008739 EVT VT = N->getValueType(0);
8740 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8741 // it with shift to let it be lowered to UBFX.
8742 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8743 isa<ConstantSDNode>(N->getOperand(1))) {
8744 uint64_t TruncMask = N->getConstantOperandVal(1);
8745 if (isMask_64(TruncMask) &&
8746 N->getOperand(0).getOpcode() == ISD::SRL &&
8747 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8748 return false;
8749 }
8750 return true;
8751}
8752
8753bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8754 Type *Ty) const {
8755 assert(Ty->isIntegerTy());
8756
8757 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8758 if (BitSize == 0)
8759 return false;
8760
8761 int64_t Val = Imm.getSExtValue();
8762 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8763 return true;
8764
8765 if ((int64_t)Val < 0)
8766 Val = ~Val;
8767 if (BitSize == 32)
8768 Val &= (1LL << 32) - 1;
8769
8770 unsigned LZ = countLeadingZeros((uint64_t)Val);
8771 unsigned Shift = (63 - LZ) / 16;
8772 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008773 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008774}
8775
Sebastian Pop41073e82018-03-06 16:54:55 +00008776bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8777 unsigned Index) const {
8778 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8779 return false;
8780
8781 return (Index == 0 || Index == ResVT.getVectorNumElements());
8782}
8783
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008784/// Turn vector tests of the signbit in the form of:
8785/// xor (sra X, elt_size(X)-1), -1
8786/// into:
8787/// cmge X, X, #0
8788static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8789 const AArch64Subtarget *Subtarget) {
8790 EVT VT = N->getValueType(0);
8791 if (!Subtarget->hasNEON() || !VT.isVector())
8792 return SDValue();
8793
8794 // There must be a shift right algebraic before the xor, and the xor must be a
8795 // 'not' operation.
8796 SDValue Shift = N->getOperand(0);
8797 SDValue Ones = N->getOperand(1);
8798 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8799 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8800 return SDValue();
8801
8802 // The shift should be smearing the sign bit across each vector element.
8803 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8804 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8805 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8806 return SDValue();
8807
8808 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8809}
8810
Tim Northover3b0846e2014-05-24 12:50:23 +00008811// Generate SUBS and CSEL for integer abs.
8812static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8813 EVT VT = N->getValueType(0);
8814
8815 SDValue N0 = N->getOperand(0);
8816 SDValue N1 = N->getOperand(1);
8817 SDLoc DL(N);
8818
8819 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8820 // and change it to SUB and CSEL.
8821 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8822 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8823 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8824 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8825 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008826 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008827 N0.getOperand(0));
8828 // Generate SUBS & CSEL.
8829 SDValue Cmp =
8830 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008831 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008832 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008833 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008834 SDValue(Cmp.getNode(), 1));
8835 }
8836 return SDValue();
8837}
8838
Tim Northover3b0846e2014-05-24 12:50:23 +00008839static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8840 TargetLowering::DAGCombinerInfo &DCI,
8841 const AArch64Subtarget *Subtarget) {
8842 if (DCI.isBeforeLegalizeOps())
8843 return SDValue();
8844
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008845 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8846 return Cmp;
8847
Tim Northover3b0846e2014-05-24 12:50:23 +00008848 return performIntegerAbsCombine(N, DAG);
8849}
8850
Chad Rosier17020f92014-07-23 14:57:52 +00008851SDValue
8852AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8853 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008854 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008855 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008856 if (isIntDivCheap(N->getValueType(0), Attr))
8857 return SDValue(N,0); // Lower SDIV as SDIV
8858
Chad Rosier17020f92014-07-23 14:57:52 +00008859 // fold (sdiv X, pow2)
8860 EVT VT = N->getValueType(0);
8861 if ((VT != MVT::i32 && VT != MVT::i64) ||
8862 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8863 return SDValue();
8864
8865 SDLoc DL(N);
8866 SDValue N0 = N->getOperand(0);
8867 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008868 SDValue Zero = DAG.getConstant(0, DL, VT);
8869 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008870
8871 // Add (N0 < 0) ? Pow2 - 1 : 0;
8872 SDValue CCVal;
8873 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8874 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8875 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8876
Craig Toppera568a272018-07-30 21:04:34 +00008877 Created.push_back(Cmp.getNode());
8878 Created.push_back(Add.getNode());
8879 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00008880
8881 // Divide by pow2.
8882 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008883 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008884
8885 // If we're dividing by a positive value, we're done. Otherwise, we must
8886 // negate the result.
8887 if (Divisor.isNonNegative())
8888 return SRA;
8889
Craig Toppera568a272018-07-30 21:04:34 +00008890 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008891 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008892}
8893
Tim Northover3b0846e2014-05-24 12:50:23 +00008894static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8895 TargetLowering::DAGCombinerInfo &DCI,
8896 const AArch64Subtarget *Subtarget) {
8897 if (DCI.isBeforeLegalizeOps())
8898 return SDValue();
8899
Chad Rosier31ee8132016-11-11 17:07:37 +00008900 // The below optimizations require a constant RHS.
8901 if (!isa<ConstantSDNode>(N->getOperand(1)))
8902 return SDValue();
8903
8904 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8905 const APInt &ConstValue = C->getAPIntValue();
8906
Tim Northover3b0846e2014-05-24 12:50:23 +00008907 // Multiplication of a power of two plus/minus one can be done more
8908 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8909 // future CPUs have a cheaper MADD instruction, this may need to be
8910 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8911 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008912 // More aggressively, some multiplications N0 * C can be lowered to
8913 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8914 // e.g. 6=3*2=(2+1)*2.
8915 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8916 // which equals to (1+2)*16-(1+2).
8917 SDValue N0 = N->getOperand(0);
8918 // TrailingZeroes is used to test if the mul can be lowered to
8919 // shift+add+shift.
8920 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8921 if (TrailingZeroes) {
8922 // Conservatively do not lower to shift+add+shift if the mul might be
8923 // folded into smul or umul.
8924 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8925 isZeroExtended(N0.getNode(), DAG)))
8926 return SDValue();
8927 // Conservatively do not lower to shift+add+shift if the mul might be
8928 // folded into madd or msub.
8929 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8930 N->use_begin()->getOpcode() == ISD::SUB))
8931 return SDValue();
8932 }
8933 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8934 // and shift+add+shift.
8935 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8936
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008937 unsigned ShiftAmt, AddSubOpc;
8938 // Is the shifted value the LHS operand of the add/sub?
8939 bool ShiftValUseIsN0 = true;
8940 // Do we need to negate the result?
8941 bool NegateResult = false;
8942
Chad Rosier31ee8132016-11-11 17:07:37 +00008943 if (ConstValue.isNonNegative()) {
8944 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00008945 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00008946 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8947 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008948 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00008949 if (SCVMinus1.isPowerOf2()) {
8950 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008951 AddSubOpc = ISD::ADD;
8952 } else if (CVPlus1.isPowerOf2()) {
8953 ShiftAmt = CVPlus1.logBase2();
8954 AddSubOpc = ISD::SUB;
8955 } else
8956 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00008957 } else {
8958 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00008959 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008960 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008961 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008962 if (CVNegPlus1.isPowerOf2()) {
8963 ShiftAmt = CVNegPlus1.logBase2();
8964 AddSubOpc = ISD::SUB;
8965 ShiftValUseIsN0 = false;
8966 } else if (CVNegMinus1.isPowerOf2()) {
8967 ShiftAmt = CVNegMinus1.logBase2();
8968 AddSubOpc = ISD::ADD;
8969 NegateResult = true;
8970 } else
8971 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008972 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008973
8974 SDLoc DL(N);
8975 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008976 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008977 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8978
8979 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8980 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8981 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008982 assert(!(NegateResult && TrailingZeroes) &&
8983 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008984 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008985 if (NegateResult)
8986 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8987 // Shift the result.
8988 if (TrailingZeroes)
8989 return DAG.getNode(ISD::SHL, DL, VT, Res,
8990 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8991 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00008992}
8993
Jim Grosbachf7502c42014-07-18 00:40:52 +00008994static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8995 SelectionDAG &DAG) {
8996 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8997 // optimize away operation when it's from a constant.
8998 //
8999 // The general transformation is:
9000 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9001 // AND(VECTOR_CMP(x,y), constant2)
9002 // constant2 = UNARYOP(constant)
9003
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009004 // Early exit if this isn't a vector operation, the operand of the
9005 // unary operation isn't a bitwise AND, or if the sizes of the operations
9006 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009007 EVT VT = N->getValueType(0);
9008 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009009 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9010 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009011 return SDValue();
9012
Jim Grosbach724e4382014-07-23 20:41:43 +00009013 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009014 // make the transformation for non-constant splats as well, but it's unclear
9015 // that would be a benefit as it would not eliminate any operations, just
9016 // perform one more step in scalar code before moving to the vector unit.
9017 if (BuildVectorSDNode *BV =
9018 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009019 // Bail out if the vector isn't a constant.
9020 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009021 return SDValue();
9022
9023 // Everything checks out. Build up the new and improved node.
9024 SDLoc DL(N);
9025 EVT IntVT = BV->getValueType(0);
9026 // Create a new constant of the appropriate type for the transformed
9027 // DAG.
9028 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9029 // The AND node needs bitcasts to/from an integer vector type around it.
9030 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9031 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9032 N->getOperand(0)->getOperand(0), MaskConst);
9033 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9034 return Res;
9035 }
9036
9037 return SDValue();
9038}
9039
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009040static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9041 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009042 // First try to optimize away the conversion when it's conditionally from
9043 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009044 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009045 return Res;
9046
Tim Northover3b0846e2014-05-24 12:50:23 +00009047 EVT VT = N->getValueType(0);
9048 if (VT != MVT::f32 && VT != MVT::f64)
9049 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009050
Tim Northover3b0846e2014-05-24 12:50:23 +00009051 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009052 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009053 return SDValue();
9054
9055 // If the result of an integer load is only used by an integer-to-float
9056 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009057 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009058 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009059 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009060 // Do not change the width of a volatile load.
9061 !cast<LoadSDNode>(N0)->isVolatile()) {
9062 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9063 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009064 LN0->getPointerInfo(), LN0->getAlignment(),
9065 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009066
9067 // Make sure successors of the original load stay after it by updating them
9068 // to use the new Chain.
9069 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9070
9071 unsigned Opcode =
9072 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9073 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9074 }
9075
9076 return SDValue();
9077}
9078
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009079/// Fold a floating-point multiply by power of two into floating-point to
9080/// fixed-point conversion.
9081static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009082 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009083 const AArch64Subtarget *Subtarget) {
9084 if (!Subtarget->hasNEON())
9085 return SDValue();
9086
9087 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009088 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9089 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009090 return SDValue();
9091
9092 SDValue ConstVec = Op->getOperand(1);
9093 if (!isa<BuildVectorSDNode>(ConstVec))
9094 return SDValue();
9095
9096 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9097 uint32_t FloatBits = FloatTy.getSizeInBits();
9098 if (FloatBits != 32 && FloatBits != 64)
9099 return SDValue();
9100
9101 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9102 uint32_t IntBits = IntTy.getSizeInBits();
9103 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9104 return SDValue();
9105
9106 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9107 if (IntBits > FloatBits)
9108 return SDValue();
9109
9110 BitVector UndefElements;
9111 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9112 int32_t Bits = IntBits == 64 ? 64 : 32;
9113 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9114 if (C == -1 || C == 0 || C > Bits)
9115 return SDValue();
9116
9117 MVT ResTy;
9118 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9119 switch (NumLanes) {
9120 default:
9121 return SDValue();
9122 case 2:
9123 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9124 break;
9125 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009126 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009127 break;
9128 }
9129
Silviu Barangafa00ba32016-08-08 13:13:57 +00009130 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9131 return SDValue();
9132
9133 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9134 "Illegal vector type after legalization");
9135
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009136 SDLoc DL(N);
9137 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9138 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9139 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9140 SDValue FixConv =
9141 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9142 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9143 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9144 // We can handle smaller integers by generating an extra trunc.
9145 if (IntBits < FloatBits)
9146 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9147
9148 return FixConv;
9149}
9150
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009151/// Fold a floating-point divide by power of two into fixed-point to
9152/// floating-point conversion.
9153static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009154 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009155 const AArch64Subtarget *Subtarget) {
9156 if (!Subtarget->hasNEON())
9157 return SDValue();
9158
9159 SDValue Op = N->getOperand(0);
9160 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009161 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9162 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009163 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9164 return SDValue();
9165
9166 SDValue ConstVec = N->getOperand(1);
9167 if (!isa<BuildVectorSDNode>(ConstVec))
9168 return SDValue();
9169
9170 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9171 int32_t IntBits = IntTy.getSizeInBits();
9172 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9173 return SDValue();
9174
9175 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9176 int32_t FloatBits = FloatTy.getSizeInBits();
9177 if (FloatBits != 32 && FloatBits != 64)
9178 return SDValue();
9179
9180 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9181 if (IntBits > FloatBits)
9182 return SDValue();
9183
9184 BitVector UndefElements;
9185 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9186 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9187 if (C == -1 || C == 0 || C > FloatBits)
9188 return SDValue();
9189
9190 MVT ResTy;
9191 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9192 switch (NumLanes) {
9193 default:
9194 return SDValue();
9195 case 2:
9196 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9197 break;
9198 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009199 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009200 break;
9201 }
9202
Tim Northover85cf5642016-08-26 18:52:31 +00009203 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9204 return SDValue();
9205
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009206 SDLoc DL(N);
9207 SDValue ConvInput = Op.getOperand(0);
9208 bool IsSigned = Opc == ISD::SINT_TO_FP;
9209 if (IntBits < FloatBits)
9210 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9211 ResTy, ConvInput);
9212
9213 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9214 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9215 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9216 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9217 DAG.getConstant(C, DL, MVT::i32));
9218}
9219
Tim Northover3b0846e2014-05-24 12:50:23 +00009220/// An EXTR instruction is made up of two shifts, ORed together. This helper
9221/// searches for and classifies those shifts.
9222static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9223 bool &FromHi) {
9224 if (N.getOpcode() == ISD::SHL)
9225 FromHi = false;
9226 else if (N.getOpcode() == ISD::SRL)
9227 FromHi = true;
9228 else
9229 return false;
9230
9231 if (!isa<ConstantSDNode>(N.getOperand(1)))
9232 return false;
9233
9234 ShiftAmount = N->getConstantOperandVal(1);
9235 Src = N->getOperand(0);
9236 return true;
9237}
9238
9239/// EXTR instruction extracts a contiguous chunk of bits from two existing
9240/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009241/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9242/// with an EXTR. Can't quite be done in TableGen because the two immediates
9243/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009244static SDValue tryCombineToEXTR(SDNode *N,
9245 TargetLowering::DAGCombinerInfo &DCI) {
9246 SelectionDAG &DAG = DCI.DAG;
9247 SDLoc DL(N);
9248 EVT VT = N->getValueType(0);
9249
9250 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9251
9252 if (VT != MVT::i32 && VT != MVT::i64)
9253 return SDValue();
9254
9255 SDValue LHS;
9256 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009257 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009258 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9259 return SDValue();
9260
9261 SDValue RHS;
9262 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009263 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009264 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9265 return SDValue();
9266
9267 // If they're both trying to come from the high part of the register, they're
9268 // not really an EXTR.
9269 if (LHSFromHi == RHSFromHi)
9270 return SDValue();
9271
9272 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9273 return SDValue();
9274
9275 if (LHSFromHi) {
9276 std::swap(LHS, RHS);
9277 std::swap(ShiftLHS, ShiftRHS);
9278 }
9279
9280 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009281 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009282}
9283
9284static SDValue tryCombineToBSL(SDNode *N,
9285 TargetLowering::DAGCombinerInfo &DCI) {
9286 EVT VT = N->getValueType(0);
9287 SelectionDAG &DAG = DCI.DAG;
9288 SDLoc DL(N);
9289
9290 if (!VT.isVector())
9291 return SDValue();
9292
9293 SDValue N0 = N->getOperand(0);
9294 if (N0.getOpcode() != ISD::AND)
9295 return SDValue();
9296
9297 SDValue N1 = N->getOperand(1);
9298 if (N1.getOpcode() != ISD::AND)
9299 return SDValue();
9300
9301 // We only have to look for constant vectors here since the general, variable
9302 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009303 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009304 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9305 for (int i = 1; i >= 0; --i)
9306 for (int j = 1; j >= 0; --j) {
9307 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9308 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9309 if (!BVN0 || !BVN1)
9310 continue;
9311
9312 bool FoundMatch = true;
9313 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9314 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9315 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9316 if (!CN0 || !CN1 ||
9317 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9318 FoundMatch = false;
9319 break;
9320 }
9321 }
9322
9323 if (FoundMatch)
9324 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9325 N0->getOperand(1 - i), N1->getOperand(1 - j));
9326 }
9327
9328 return SDValue();
9329}
9330
9331static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9332 const AArch64Subtarget *Subtarget) {
9333 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009334 SelectionDAG &DAG = DCI.DAG;
9335 EVT VT = N->getValueType(0);
9336
9337 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9338 return SDValue();
9339
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009340 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009341 return Res;
9342
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009343 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009344 return Res;
9345
9346 return SDValue();
9347}
9348
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009349static SDValue performSRLCombine(SDNode *N,
9350 TargetLowering::DAGCombinerInfo &DCI) {
9351 SelectionDAG &DAG = DCI.DAG;
9352 EVT VT = N->getValueType(0);
9353 if (VT != MVT::i32 && VT != MVT::i64)
9354 return SDValue();
9355
9356 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9357 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9358 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9359 SDValue N0 = N->getOperand(0);
9360 if (N0.getOpcode() == ISD::BSWAP) {
9361 SDLoc DL(N);
9362 SDValue N1 = N->getOperand(1);
9363 SDValue N00 = N0.getOperand(0);
9364 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9365 uint64_t ShiftAmt = C->getZExtValue();
9366 if (VT == MVT::i32 && ShiftAmt == 16 &&
9367 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9368 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9369 if (VT == MVT::i64 && ShiftAmt == 32 &&
9370 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9371 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9372 }
9373 }
9374 return SDValue();
9375}
9376
Tim Northover3b0846e2014-05-24 12:50:23 +00009377static SDValue performBitcastCombine(SDNode *N,
9378 TargetLowering::DAGCombinerInfo &DCI,
9379 SelectionDAG &DAG) {
9380 // Wait 'til after everything is legalized to try this. That way we have
9381 // legal vector types and such.
9382 if (DCI.isBeforeLegalizeOps())
9383 return SDValue();
9384
9385 // Remove extraneous bitcasts around an extract_subvector.
9386 // For example,
9387 // (v4i16 (bitconvert
9388 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9389 // becomes
9390 // (extract_subvector ((v8i16 ...), (i64 4)))
9391
9392 // Only interested in 64-bit vectors as the ultimate result.
9393 EVT VT = N->getValueType(0);
9394 if (!VT.isVector())
9395 return SDValue();
9396 if (VT.getSimpleVT().getSizeInBits() != 64)
9397 return SDValue();
9398 // Is the operand an extract_subvector starting at the beginning or halfway
9399 // point of the vector? A low half may also come through as an
9400 // EXTRACT_SUBREG, so look for that, too.
9401 SDValue Op0 = N->getOperand(0);
9402 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9403 !(Op0->isMachineOpcode() &&
9404 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9405 return SDValue();
9406 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9407 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9408 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9409 return SDValue();
9410 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9411 if (idx != AArch64::dsub)
9412 return SDValue();
9413 // The dsub reference is equivalent to a lane zero subvector reference.
9414 idx = 0;
9415 }
9416 // Look through the bitcast of the input to the extract.
9417 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9418 return SDValue();
9419 SDValue Source = Op0->getOperand(0)->getOperand(0);
9420 // If the source type has twice the number of elements as our destination
9421 // type, we know this is an extract of the high or low half of the vector.
9422 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009423 if (!SVT.isVector() ||
9424 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009425 return SDValue();
9426
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009427 LLVM_DEBUG(
9428 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009429
9430 // Create the simplified form to just extract the low or high half of the
9431 // vector directly rather than bothering with the bitcasts.
9432 SDLoc dl(N);
9433 unsigned NumElements = VT.getVectorNumElements();
9434 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009435 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009436 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9437 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009438 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009439 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9440 Source, SubReg),
9441 0);
9442 }
9443}
9444
9445static SDValue performConcatVectorsCombine(SDNode *N,
9446 TargetLowering::DAGCombinerInfo &DCI,
9447 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009448 SDLoc dl(N);
9449 EVT VT = N->getValueType(0);
9450 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9451
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009452 // Optimize concat_vectors of truncated vectors, where the intermediate
9453 // type is illegal, to avoid said illegality, e.g.,
9454 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9455 // (v2i16 (truncate (v2i64)))))
9456 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009457 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9458 // (v4i32 (bitcast (v2i64))),
9459 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009460 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9461 // on both input and result type, so we might generate worse code.
9462 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9463 if (N->getNumOperands() == 2 &&
9464 N0->getOpcode() == ISD::TRUNCATE &&
9465 N1->getOpcode() == ISD::TRUNCATE) {
9466 SDValue N00 = N0->getOperand(0);
9467 SDValue N10 = N1->getOperand(0);
9468 EVT N00VT = N00.getValueType();
9469
9470 if (N00VT == N10.getValueType() &&
9471 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9472 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009473 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9474 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9475 for (size_t i = 0; i < Mask.size(); ++i)
9476 Mask[i] = i * 2;
9477 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9478 DAG.getVectorShuffle(
9479 MidVT, dl,
9480 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9481 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009482 }
9483 }
9484
Tim Northover3b0846e2014-05-24 12:50:23 +00009485 // Wait 'til after everything is legalized to try this. That way we have
9486 // legal vector types and such.
9487 if (DCI.isBeforeLegalizeOps())
9488 return SDValue();
9489
Tim Northover3b0846e2014-05-24 12:50:23 +00009490 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9491 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9492 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009493 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009494 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009495 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009496 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009497 }
9498
9499 // Canonicalise concat_vectors so that the right-hand vector has as few
9500 // bit-casts as possible before its real operation. The primary matching
9501 // destination for these operations will be the narrowing "2" instructions,
9502 // which depend on the operation being performed on this right-hand vector.
9503 // For example,
9504 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9505 // becomes
9506 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9507
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009508 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009509 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009510 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009511 MVT RHSTy = RHS.getValueType().getSimpleVT();
9512 // If the RHS is not a vector, this is not the pattern we're looking for.
9513 if (!RHSTy.isVector())
9514 return SDValue();
9515
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009516 LLVM_DEBUG(
9517 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009518
9519 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9520 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009521 return DAG.getNode(ISD::BITCAST, dl, VT,
9522 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9523 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9524 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009525}
9526
9527static SDValue tryCombineFixedPointConvert(SDNode *N,
9528 TargetLowering::DAGCombinerInfo &DCI,
9529 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009530 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009531 // legal vector types and such.
9532 if (DCI.isBeforeLegalizeOps())
9533 return SDValue();
9534 // Transform a scalar conversion of a value from a lane extract into a
9535 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9536 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9537 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9538 //
9539 // The second form interacts better with instruction selection and the
9540 // register allocator to avoid cross-class register copies that aren't
9541 // coalescable due to a lane reference.
9542
9543 // Check the operand and see if it originates from a lane extract.
9544 SDValue Op1 = N->getOperand(1);
9545 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9546 // Yep, no additional predication needed. Perform the transform.
9547 SDValue IID = N->getOperand(0);
9548 SDValue Shift = N->getOperand(2);
9549 SDValue Vec = Op1.getOperand(0);
9550 SDValue Lane = Op1.getOperand(1);
9551 EVT ResTy = N->getValueType(0);
9552 EVT VecResTy;
9553 SDLoc DL(N);
9554
9555 // The vector width should be 128 bits by the time we get here, even
9556 // if it started as 64 bits (the extract_vector handling will have
9557 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009558 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009559 "unexpected vector size on extract_vector_elt!");
9560 if (Vec.getValueType() == MVT::v4i32)
9561 VecResTy = MVT::v4f32;
9562 else if (Vec.getValueType() == MVT::v2i64)
9563 VecResTy = MVT::v2f64;
9564 else
Craig Topper2a30d782014-06-18 05:05:13 +00009565 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009566
9567 SDValue Convert =
9568 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9569 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9570 }
9571 return SDValue();
9572}
9573
9574// AArch64 high-vector "long" operations are formed by performing the non-high
9575// version on an extract_subvector of each operand which gets the high half:
9576//
9577// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9578//
9579// However, there are cases which don't have an extract_high explicitly, but
9580// have another operation that can be made compatible with one for free. For
9581// example:
9582//
9583// (dupv64 scalar) --> (extract_high (dup128 scalar))
9584//
9585// This routine does the actual conversion of such DUPs, once outer routines
9586// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009587// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9588// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009589static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009590 switch (N.getOpcode()) {
9591 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009592 case AArch64ISD::DUPLANE8:
9593 case AArch64ISD::DUPLANE16:
9594 case AArch64ISD::DUPLANE32:
9595 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009596 case AArch64ISD::MOVI:
9597 case AArch64ISD::MOVIshift:
9598 case AArch64ISD::MOVIedit:
9599 case AArch64ISD::MOVImsl:
9600 case AArch64ISD::MVNIshift:
9601 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009602 break;
9603 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009604 // FMOV could be supported, but isn't very useful, as it would only occur
9605 // if you passed a bitcast' floating point immediate to an eligible long
9606 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009607 return SDValue();
9608 }
9609
9610 MVT NarrowTy = N.getSimpleValueType();
9611 if (!NarrowTy.is64BitVector())
9612 return SDValue();
9613
9614 MVT ElementTy = NarrowTy.getVectorElementType();
9615 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009616 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009617
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009618 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009619 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9620 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009621 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009622}
9623
9624static bool isEssentiallyExtractSubvector(SDValue N) {
9625 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9626 return true;
9627
9628 return N.getOpcode() == ISD::BITCAST &&
9629 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9630}
9631
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009632/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009633struct GenericSetCCInfo {
9634 const SDValue *Opnd0;
9635 const SDValue *Opnd1;
9636 ISD::CondCode CC;
9637};
9638
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009639/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009640struct AArch64SetCCInfo {
9641 const SDValue *Cmp;
9642 AArch64CC::CondCode CC;
9643};
9644
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009645/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009646union SetCCInfo {
9647 GenericSetCCInfo Generic;
9648 AArch64SetCCInfo AArch64;
9649};
9650
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009651/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009652/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9653/// GenericSetCCInfo.
9654struct SetCCInfoAndKind {
9655 SetCCInfo Info;
9656 bool IsAArch64;
9657};
9658
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009659/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009660/// an
9661/// AArch64 lowered one.
9662/// \p SetCCInfo is filled accordingly.
9663/// \post SetCCInfo is meanginfull only when this function returns true.
9664/// \return True when Op is a kind of SET_CC operation.
9665static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9666 // If this is a setcc, this is straight forward.
9667 if (Op.getOpcode() == ISD::SETCC) {
9668 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9669 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9670 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9671 SetCCInfo.IsAArch64 = false;
9672 return true;
9673 }
9674 // Otherwise, check if this is a matching csel instruction.
9675 // In other words:
9676 // - csel 1, 0, cc
9677 // - csel 0, 1, !cc
9678 if (Op.getOpcode() != AArch64ISD::CSEL)
9679 return false;
9680 // Set the information about the operands.
9681 // TODO: we want the operands of the Cmp not the csel
9682 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9683 SetCCInfo.IsAArch64 = true;
9684 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9685 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9686
9687 // Check that the operands matches the constraints:
9688 // (1) Both operands must be constants.
9689 // (2) One must be 1 and the other must be 0.
9690 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9691 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9692
9693 // Check (1).
9694 if (!TValue || !FValue)
9695 return false;
9696
9697 // Check (2).
9698 if (!TValue->isOne()) {
9699 // Update the comparison when we are interested in !cc.
9700 std::swap(TValue, FValue);
9701 SetCCInfo.Info.AArch64.CC =
9702 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9703 }
9704 return TValue->isOne() && FValue->isNullValue();
9705}
9706
9707// Returns true if Op is setcc or zext of setcc.
9708static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9709 if (isSetCC(Op, Info))
9710 return true;
9711 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9712 isSetCC(Op->getOperand(0), Info));
9713}
9714
9715// The folding we want to perform is:
9716// (add x, [zext] (setcc cc ...) )
9717// -->
9718// (csel x, (add x, 1), !cc ...)
9719//
9720// The latter will get matched to a CSINC instruction.
9721static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9722 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9723 SDValue LHS = Op->getOperand(0);
9724 SDValue RHS = Op->getOperand(1);
9725 SetCCInfoAndKind InfoAndKind;
9726
9727 // If neither operand is a SET_CC, give up.
9728 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9729 std::swap(LHS, RHS);
9730 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9731 return SDValue();
9732 }
9733
9734 // FIXME: This could be generatized to work for FP comparisons.
9735 EVT CmpVT = InfoAndKind.IsAArch64
9736 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9737 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9738 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9739 return SDValue();
9740
9741 SDValue CCVal;
9742 SDValue Cmp;
9743 SDLoc dl(Op);
9744 if (InfoAndKind.IsAArch64) {
9745 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009746 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9747 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009748 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9749 } else
9750 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9751 *InfoAndKind.Info.Generic.Opnd1,
9752 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9753 CCVal, DAG, dl);
9754
9755 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009756 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009757 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9758}
9759
9760// The basic add/sub long vector instructions have variants with "2" on the end
9761// which act on the high-half of their inputs. They are normally matched by
9762// patterns like:
9763//
9764// (add (zeroext (extract_high LHS)),
9765// (zeroext (extract_high RHS)))
9766// -> uaddl2 vD, vN, vM
9767//
9768// However, if one of the extracts is something like a duplicate, this
9769// instruction can still be used profitably. This function puts the DAG into a
9770// more appropriate form for those patterns to trigger.
9771static SDValue performAddSubLongCombine(SDNode *N,
9772 TargetLowering::DAGCombinerInfo &DCI,
9773 SelectionDAG &DAG) {
9774 if (DCI.isBeforeLegalizeOps())
9775 return SDValue();
9776
9777 MVT VT = N->getSimpleValueType(0);
9778 if (!VT.is128BitVector()) {
9779 if (N->getOpcode() == ISD::ADD)
9780 return performSetccAddFolding(N, DAG);
9781 return SDValue();
9782 }
9783
9784 // Make sure both branches are extended in the same way.
9785 SDValue LHS = N->getOperand(0);
9786 SDValue RHS = N->getOperand(1);
9787 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9788 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9789 LHS.getOpcode() != RHS.getOpcode())
9790 return SDValue();
9791
9792 unsigned ExtType = LHS.getOpcode();
9793
9794 // It's not worth doing if at least one of the inputs isn't already an
9795 // extract, but we don't know which it'll be so we have to try both.
9796 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9797 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9798 if (!RHS.getNode())
9799 return SDValue();
9800
9801 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9802 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9803 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9804 if (!LHS.getNode())
9805 return SDValue();
9806
9807 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9808 }
9809
9810 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9811}
9812
9813// Massage DAGs which we can use the high-half "long" operations on into
9814// something isel will recognize better. E.g.
9815//
9816// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9817// (aarch64_neon_umull (extract_high (v2i64 vec)))
9818// (extract_high (v2i64 (dup128 scalar)))))
9819//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009820static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009821 TargetLowering::DAGCombinerInfo &DCI,
9822 SelectionDAG &DAG) {
9823 if (DCI.isBeforeLegalizeOps())
9824 return SDValue();
9825
Hal Finkelcd8664c2015-12-11 23:11:52 +00009826 SDValue LHS = N->getOperand(1);
9827 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009828 assert(LHS.getValueType().is64BitVector() &&
9829 RHS.getValueType().is64BitVector() &&
9830 "unexpected shape for long operation");
9831
9832 // Either node could be a DUP, but it's not worth doing both of them (you'd
9833 // just as well use the non-high version) so look for a corresponding extract
9834 // operation on the other "wing".
9835 if (isEssentiallyExtractSubvector(LHS)) {
9836 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9837 if (!RHS.getNode())
9838 return SDValue();
9839 } else if (isEssentiallyExtractSubvector(RHS)) {
9840 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9841 if (!LHS.getNode())
9842 return SDValue();
9843 }
9844
Hal Finkelcd8664c2015-12-11 23:11:52 +00009845 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9846 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009847}
9848
9849static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9850 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9851 unsigned ElemBits = ElemTy.getSizeInBits();
9852
9853 int64_t ShiftAmount;
9854 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9855 APInt SplatValue, SplatUndef;
9856 unsigned SplatBitSize;
9857 bool HasAnyUndefs;
9858 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9859 HasAnyUndefs, ElemBits) ||
9860 SplatBitSize != ElemBits)
9861 return SDValue();
9862
9863 ShiftAmount = SplatValue.getSExtValue();
9864 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9865 ShiftAmount = CVN->getSExtValue();
9866 } else
9867 return SDValue();
9868
9869 unsigned Opcode;
9870 bool IsRightShift;
9871 switch (IID) {
9872 default:
9873 llvm_unreachable("Unknown shift intrinsic");
9874 case Intrinsic::aarch64_neon_sqshl:
9875 Opcode = AArch64ISD::SQSHL_I;
9876 IsRightShift = false;
9877 break;
9878 case Intrinsic::aarch64_neon_uqshl:
9879 Opcode = AArch64ISD::UQSHL_I;
9880 IsRightShift = false;
9881 break;
9882 case Intrinsic::aarch64_neon_srshl:
9883 Opcode = AArch64ISD::SRSHR_I;
9884 IsRightShift = true;
9885 break;
9886 case Intrinsic::aarch64_neon_urshl:
9887 Opcode = AArch64ISD::URSHR_I;
9888 IsRightShift = true;
9889 break;
9890 case Intrinsic::aarch64_neon_sqshlu:
9891 Opcode = AArch64ISD::SQSHLU_I;
9892 IsRightShift = false;
9893 break;
9894 }
9895
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009896 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9897 SDLoc dl(N);
9898 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9899 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9900 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9901 SDLoc dl(N);
9902 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9903 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9904 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009905
9906 return SDValue();
9907}
9908
9909// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9910// the intrinsics must be legal and take an i32, this means there's almost
9911// certainly going to be a zext in the DAG which we can eliminate.
9912static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9913 SDValue AndN = N->getOperand(2);
9914 if (AndN.getOpcode() != ISD::AND)
9915 return SDValue();
9916
9917 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9918 if (!CMask || CMask->getZExtValue() != Mask)
9919 return SDValue();
9920
9921 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9922 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9923}
9924
Ahmed Bougachafab58922015-03-10 20:45:38 +00009925static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9926 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009927 SDLoc dl(N);
9928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9929 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009930 N->getOperand(1).getSimpleValueType(),
9931 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009932 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009933}
9934
Tim Northover3b0846e2014-05-24 12:50:23 +00009935static SDValue performIntrinsicCombine(SDNode *N,
9936 TargetLowering::DAGCombinerInfo &DCI,
9937 const AArch64Subtarget *Subtarget) {
9938 SelectionDAG &DAG = DCI.DAG;
9939 unsigned IID = getIntrinsicID(N);
9940 switch (IID) {
9941 default:
9942 break;
9943 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9944 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9945 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00009946 case Intrinsic::aarch64_neon_saddv:
9947 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9948 case Intrinsic::aarch64_neon_uaddv:
9949 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9950 case Intrinsic::aarch64_neon_sminv:
9951 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9952 case Intrinsic::aarch64_neon_uminv:
9953 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9954 case Intrinsic::aarch64_neon_smaxv:
9955 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9956 case Intrinsic::aarch64_neon_umaxv:
9957 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009958 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +00009959 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009960 N->getOperand(1), N->getOperand(2));
9961 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +00009962 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009963 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00009964 case Intrinsic::aarch64_neon_fmaxnm:
9965 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9966 N->getOperand(1), N->getOperand(2));
9967 case Intrinsic::aarch64_neon_fminnm:
9968 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9969 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009970 case Intrinsic::aarch64_neon_smull:
9971 case Intrinsic::aarch64_neon_umull:
9972 case Intrinsic::aarch64_neon_pmull:
9973 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00009974 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009975 case Intrinsic::aarch64_neon_sqshl:
9976 case Intrinsic::aarch64_neon_uqshl:
9977 case Intrinsic::aarch64_neon_sqshlu:
9978 case Intrinsic::aarch64_neon_srshl:
9979 case Intrinsic::aarch64_neon_urshl:
9980 return tryCombineShiftImm(IID, N, DAG);
9981 case Intrinsic::aarch64_crc32b:
9982 case Intrinsic::aarch64_crc32cb:
9983 return tryCombineCRC32(0xff, N, DAG);
9984 case Intrinsic::aarch64_crc32h:
9985 case Intrinsic::aarch64_crc32ch:
9986 return tryCombineCRC32(0xffff, N, DAG);
9987 }
9988 return SDValue();
9989}
9990
9991static SDValue performExtendCombine(SDNode *N,
9992 TargetLowering::DAGCombinerInfo &DCI,
9993 SelectionDAG &DAG) {
9994 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9995 // we can convert that DUP into another extract_high (of a bigger DUP), which
9996 // helps the backend to decide that an sabdl2 would be useful, saving a real
9997 // extract_high operation.
9998 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00009999 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010000 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010001 unsigned IID = getIntrinsicID(ABDNode);
10002 if (IID == Intrinsic::aarch64_neon_sabd ||
10003 IID == Intrinsic::aarch64_neon_uabd) {
10004 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10005 if (!NewABD.getNode())
10006 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010007
Hal Finkelcd8664c2015-12-11 23:11:52 +000010008 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10009 NewABD);
10010 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010011 }
10012
10013 // This is effectively a custom type legalization for AArch64.
10014 //
10015 // Type legalization will split an extend of a small, legal, type to a larger
10016 // illegal type by first splitting the destination type, often creating
10017 // illegal source types, which then get legalized in isel-confusing ways,
10018 // leading to really terrible codegen. E.g.,
10019 // %result = v8i32 sext v8i8 %value
10020 // becomes
10021 // %losrc = extract_subreg %value, ...
10022 // %hisrc = extract_subreg %value, ...
10023 // %lo = v4i32 sext v4i8 %losrc
10024 // %hi = v4i32 sext v4i8 %hisrc
10025 // Things go rapidly downhill from there.
10026 //
10027 // For AArch64, the [sz]ext vector instructions can only go up one element
10028 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10029 // take two instructions.
10030 //
10031 // This implies that the most efficient way to do the extend from v8i8
10032 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10033 // the normal splitting to happen for the v8i16->v8i32.
10034
10035 // This is pre-legalization to catch some cases where the default
10036 // type legalization will create ill-tempered code.
10037 if (!DCI.isBeforeLegalizeOps())
10038 return SDValue();
10039
10040 // We're only interested in cleaning things up for non-legal vector types
10041 // here. If both the source and destination are legal, things will just
10042 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010043 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010044 EVT ResVT = N->getValueType(0);
10045 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10046 return SDValue();
10047 // If the vector type isn't a simple VT, it's beyond the scope of what
10048 // we're worried about here. Let legalization do its thing and hope for
10049 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010050 SDValue Src = N->getOperand(0);
10051 EVT SrcVT = Src->getValueType(0);
10052 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010053 return SDValue();
10054
Tim Northover3b0846e2014-05-24 12:50:23 +000010055 // If the source VT is a 64-bit vector, we can play games and get the
10056 // better results we want.
10057 if (SrcVT.getSizeInBits() != 64)
10058 return SDValue();
10059
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010060 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010061 unsigned ElementCount = SrcVT.getVectorNumElements();
10062 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10063 SDLoc DL(N);
10064 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10065
10066 // Now split the rest of the operation into two halves, each with a 64
10067 // bit source.
10068 EVT LoVT, HiVT;
10069 SDValue Lo, Hi;
10070 unsigned NumElements = ResVT.getVectorNumElements();
10071 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10072 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10073 ResVT.getVectorElementType(), NumElements / 2);
10074
10075 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10076 LoVT.getVectorNumElements());
10077 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010078 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010079 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010080 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010081 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10082 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10083
10084 // Now combine the parts back together so we still have a single result
10085 // like the combiner expects.
10086 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10087}
10088
Geoff Berry8301c642016-11-16 19:35:19 +000010089static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10090 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010091 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010092 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010093 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010094
10095 // Create scalar stores. This is at least as good as the code sequence for a
10096 // split unaligned store which is a dup.s, ext.b, and two stores.
10097 // Most of the time the three stores should be replaced by store pair
10098 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010099 SDLoc DL(&St);
10100 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010101 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010102
John Brawn3a9c8422017-02-06 18:07:20 +000010103 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010104 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010105 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010106 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010107
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010108 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010109 if (BasePtr->getOpcode() == ISD::ADD &&
10110 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10111 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10112 BasePtr = BasePtr->getOperand(0);
10113 }
10114
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010115 unsigned Offset = EltOffset;
10116 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010117 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010118 SDValue OffsetPtr =
10119 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10120 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010121 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010122 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010123 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010124 Offset += EltOffset;
10125 }
10126 return NewST1;
10127}
10128
Geoff Berry526c5052016-11-14 19:39:04 +000010129/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10130/// load store optimizer pass will merge them to store pair stores. This should
10131/// be better than a movi to create the vector zero followed by a vector store
10132/// if the zero constant is not re-used, since one instructions and one register
10133/// live range will be removed.
10134///
10135/// For example, the final generated code should be:
10136///
10137/// stp xzr, xzr, [x0]
10138///
10139/// instead of:
10140///
10141/// movi v0.2d, #0
10142/// str q0, [x0]
10143///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010144static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10145 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010146 EVT VT = StVal.getValueType();
10147
Geoff Berry8301c642016-11-16 19:35:19 +000010148 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10149 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010150 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010151 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10152 VT.getVectorElementType().getSizeInBits() == 64) ||
10153 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10154 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010155 return SDValue();
10156
10157 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10158 return SDValue();
10159
10160 // If the zero constant has more than one use then the vector store could be
10161 // better since the constant mov will be amortized and stp q instructions
10162 // should be able to be formed.
10163 if (!StVal.hasOneUse())
10164 return SDValue();
10165
Tim Northover964eea72019-01-08 13:30:27 +000010166 // If the store is truncating then it's going down to i16 or smaller, which
10167 // means it can be implemented in a single store anyway.
10168 if (St.isTruncatingStore())
10169 return SDValue();
10170
Geoff Berry526c5052016-11-14 19:39:04 +000010171 // If the immediate offset of the address operand is too large for the stp
10172 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010173 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10174 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010175 if (Offset < -512 || Offset > 504)
10176 return SDValue();
10177 }
10178
10179 for (int I = 0; I < NumVecElts; ++I) {
10180 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010181 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010182 return SDValue();
10183 }
Geoff Berry8301c642016-11-16 19:35:19 +000010184
Geoff Berrybb23df92017-09-21 21:10:06 +000010185 // Use a CopyFromReg WZR/XZR here to prevent
10186 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10187 SDLoc DL(&St);
10188 unsigned ZeroReg;
10189 EVT ZeroVT;
10190 if (VT.getVectorElementType().getSizeInBits() == 32) {
10191 ZeroReg = AArch64::WZR;
10192 ZeroVT = MVT::i32;
10193 } else {
10194 ZeroReg = AArch64::XZR;
10195 ZeroVT = MVT::i64;
10196 }
10197 SDValue SplatVal =
10198 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010199 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010200}
10201
Tim Northover3b0846e2014-05-24 12:50:23 +000010202/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10203/// value. The load store optimizer pass will merge them to store pair stores.
10204/// This has better performance than a splat of the scalar followed by a split
10205/// vector store. Even if the stores are not merged it is four stores vs a dup,
10206/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010207static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10208 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010209 EVT VT = StVal.getValueType();
10210
10211 // Don't replace floating point stores, they possibly won't be transformed to
10212 // stp because of the store pair suppress pass.
10213 if (VT.isFloatingPoint())
10214 return SDValue();
10215
Tim Northover3b0846e2014-05-24 12:50:23 +000010216 // We can express a splat as store pair(s) for 2 or 4 elements.
10217 unsigned NumVecElts = VT.getVectorNumElements();
10218 if (NumVecElts != 4 && NumVecElts != 2)
10219 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010220
Tim Northover964eea72019-01-08 13:30:27 +000010221 // If the store is truncating then it's going down to i16 or smaller, which
10222 // means it can be implemented in a single store anyway.
10223 if (St.isTruncatingStore())
10224 return SDValue();
10225
Tim Northover3b0846e2014-05-24 12:50:23 +000010226 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010227 // Make sure that each of the relevant vector element locations are inserted
10228 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10229 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10230 SDValue SplatVal;
10231 for (unsigned I = 0; I < NumVecElts; ++I) {
10232 // Check for insert vector elements.
10233 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010234 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010235
10236 // Check that same value is inserted at each vector element.
10237 if (I == 0)
10238 SplatVal = StVal.getOperand(1);
10239 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010240 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010241
10242 // Check insert element index.
10243 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10244 if (!CIndex)
10245 return SDValue();
10246 uint64_t IndexVal = CIndex->getZExtValue();
10247 if (IndexVal >= NumVecElts)
10248 return SDValue();
10249 IndexNotInserted.reset(IndexVal);
10250
10251 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010252 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010253 // Check that all vector element locations were inserted to.
10254 if (IndexNotInserted.any())
10255 return SDValue();
10256
Geoff Berry8301c642016-11-16 19:35:19 +000010257 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010258}
10259
Geoff Berry8301c642016-11-16 19:35:19 +000010260static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10261 SelectionDAG &DAG,
10262 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010263
10264 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010265 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010266 return SDValue();
10267
Geoff Berry526c5052016-11-14 19:39:04 +000010268 SDValue StVal = S->getValue();
10269 EVT VT = StVal.getValueType();
10270 if (!VT.isVector())
10271 return SDValue();
10272
10273 // If we get a splat of zeros, convert this vector store to a store of
10274 // scalars. They will be merged into store pairs of xzr thereby removing one
10275 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010276 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010277 return ReplacedZeroSplat;
10278
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010279 // FIXME: The logic for deciding if an unaligned store should be split should
10280 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10281 // a call to that function here.
10282
Matthias Braun651cff42016-06-02 18:03:53 +000010283 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010284 return SDValue();
10285
Sanjay Patel924879a2015-08-04 15:49:57 +000010286 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +000010287 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010288 return SDValue();
10289
Tim Northover3b0846e2014-05-24 12:50:23 +000010290 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10291 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010292 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010293 return SDValue();
10294
10295 // Split unaligned 16B stores. They are terrible for performance.
10296 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10297 // extensions can use this to mark that it does not want splitting to happen
10298 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10299 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10300 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10301 S->getAlignment() <= 2)
10302 return SDValue();
10303
10304 // If we get a splat of a scalar convert this vector store to a store of
10305 // scalars. They will be merged into store pairs thereby removing two
10306 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010307 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010308 return ReplacedSplat;
10309
10310 SDLoc DL(S);
10311 unsigned NumElts = VT.getVectorNumElements() / 2;
10312 // Split VT into two.
10313 EVT HalfVT =
10314 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10315 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010316 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010317 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010318 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010319 SDValue BasePtr = S->getBasePtr();
10320 SDValue NewST1 =
10321 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010322 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010323 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010324 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010325 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010326 S->getPointerInfo(), S->getAlignment(),
10327 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010328}
10329
10330/// Target-specific DAG combine function for post-increment LD1 (lane) and
10331/// post-increment LD1R.
10332static SDValue performPostLD1Combine(SDNode *N,
10333 TargetLowering::DAGCombinerInfo &DCI,
10334 bool IsLaneOp) {
10335 if (DCI.isBeforeLegalizeOps())
10336 return SDValue();
10337
10338 SelectionDAG &DAG = DCI.DAG;
10339 EVT VT = N->getValueType(0);
10340
10341 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10342 SDNode *LD = N->getOperand(LoadIdx).getNode();
10343 // If it is not LOAD, can not do such combine.
10344 if (LD->getOpcode() != ISD::LOAD)
10345 return SDValue();
10346
Geoff Berry60460262018-05-11 16:25:06 +000010347 // The vector lane must be a constant in the LD1LANE opcode.
10348 SDValue Lane;
10349 if (IsLaneOp) {
10350 Lane = N->getOperand(2);
10351 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10352 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10353 return SDValue();
10354 }
10355
Tim Northover3b0846e2014-05-24 12:50:23 +000010356 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10357 EVT MemVT = LoadSDN->getMemoryVT();
10358 // Check if memory operand is the same type as the vector element.
10359 if (MemVT != VT.getVectorElementType())
10360 return SDValue();
10361
10362 // Check if there are other uses. If so, do not combine as it will introduce
10363 // an extra load.
10364 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10365 ++UI) {
10366 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10367 continue;
10368 if (*UI != N)
10369 return SDValue();
10370 }
10371
10372 SDValue Addr = LD->getOperand(1);
10373 SDValue Vector = N->getOperand(0);
10374 // Search for a use of the address operand that is an increment.
10375 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10376 Addr.getNode()->use_end(); UI != UE; ++UI) {
10377 SDNode *User = *UI;
10378 if (User->getOpcode() != ISD::ADD
10379 || UI.getUse().getResNo() != Addr.getResNo())
10380 continue;
10381
Tim Northover3b0846e2014-05-24 12:50:23 +000010382 // If the increment is a constant, it must match the memory ref size.
10383 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10384 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10385 uint32_t IncVal = CInc->getZExtValue();
10386 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10387 if (IncVal != NumBytes)
10388 continue;
10389 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10390 }
10391
Nirav Davee40e2bb2018-09-25 15:30:22 +000010392 // To avoid cycle construction make sure that neither the load nor the add
10393 // are predecessors to each other or the Vector.
10394 SmallPtrSet<const SDNode *, 32> Visited;
10395 SmallVector<const SDNode *, 16> Worklist;
10396 Visited.insert(N);
10397 Worklist.push_back(User);
10398 Worklist.push_back(LD);
10399 Worklist.push_back(Vector.getNode());
10400 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10401 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010402 continue;
10403
Tim Northover3b0846e2014-05-24 12:50:23 +000010404 SmallVector<SDValue, 8> Ops;
10405 Ops.push_back(LD->getOperand(0)); // Chain
10406 if (IsLaneOp) {
10407 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010408 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010409 }
10410 Ops.push_back(Addr);
10411 Ops.push_back(Inc);
10412
10413 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010414 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010415 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10416 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10417 MemVT,
10418 LoadSDN->getMemOperand());
10419
10420 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010421 SDValue NewResults[] = {
10422 SDValue(LD, 0), // The result of load
10423 SDValue(UpdN.getNode(), 2) // Chain
10424 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010425 DCI.CombineTo(LD, NewResults);
10426 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10427 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10428
10429 break;
10430 }
10431 return SDValue();
10432}
10433
Joel Jones7466ccf2017-07-10 22:11:50 +000010434/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010435/// address translation.
10436static bool performTBISimplification(SDValue Addr,
10437 TargetLowering::DAGCombinerInfo &DCI,
10438 SelectionDAG &DAG) {
10439 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010440 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010441 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10442 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010443 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010444 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010445 DCI.CommitTargetLoweringOpt(TLO);
10446 return true;
10447 }
10448 return false;
10449}
10450
10451static SDValue performSTORECombine(SDNode *N,
10452 TargetLowering::DAGCombinerInfo &DCI,
10453 SelectionDAG &DAG,
10454 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010455 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010456 return Split;
10457
10458 if (Subtarget->supportsAddressTopByteIgnored() &&
10459 performTBISimplification(N->getOperand(2), DCI, DAG))
10460 return SDValue(N, 0);
10461
10462 return SDValue();
10463}
10464
Chad Rosier6c36eff2015-09-03 18:13:57 +000010465
Tim Northover3b0846e2014-05-24 12:50:23 +000010466/// Target-specific DAG combine function for NEON load/store intrinsics
10467/// to merge base address updates.
10468static SDValue performNEONPostLDSTCombine(SDNode *N,
10469 TargetLowering::DAGCombinerInfo &DCI,
10470 SelectionDAG &DAG) {
10471 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10472 return SDValue();
10473
10474 unsigned AddrOpIdx = N->getNumOperands() - 1;
10475 SDValue Addr = N->getOperand(AddrOpIdx);
10476
10477 // Search for a use of the address operand that is an increment.
10478 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10479 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10480 SDNode *User = *UI;
10481 if (User->getOpcode() != ISD::ADD ||
10482 UI.getUse().getResNo() != Addr.getResNo())
10483 continue;
10484
10485 // Check that the add is independent of the load/store. Otherwise, folding
10486 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010487 SmallPtrSet<const SDNode *, 32> Visited;
10488 SmallVector<const SDNode *, 16> Worklist;
10489 Visited.insert(Addr.getNode());
10490 Worklist.push_back(N);
10491 Worklist.push_back(User);
10492 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10493 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010494 continue;
10495
10496 // Find the new opcode for the updating load/store.
10497 bool IsStore = false;
10498 bool IsLaneOp = false;
10499 bool IsDupOp = false;
10500 unsigned NewOpc = 0;
10501 unsigned NumVecs = 0;
10502 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10503 switch (IntNo) {
10504 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10505 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10506 NumVecs = 2; break;
10507 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10508 NumVecs = 3; break;
10509 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10510 NumVecs = 4; break;
10511 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10512 NumVecs = 2; IsStore = true; break;
10513 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10514 NumVecs = 3; IsStore = true; break;
10515 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10516 NumVecs = 4; IsStore = true; break;
10517 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10518 NumVecs = 2; break;
10519 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10520 NumVecs = 3; break;
10521 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10522 NumVecs = 4; break;
10523 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10524 NumVecs = 2; IsStore = true; break;
10525 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10526 NumVecs = 3; IsStore = true; break;
10527 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10528 NumVecs = 4; IsStore = true; break;
10529 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10530 NumVecs = 2; IsDupOp = true; break;
10531 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10532 NumVecs = 3; IsDupOp = true; break;
10533 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10534 NumVecs = 4; IsDupOp = true; break;
10535 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10536 NumVecs = 2; IsLaneOp = true; break;
10537 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10538 NumVecs = 3; IsLaneOp = true; break;
10539 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10540 NumVecs = 4; IsLaneOp = true; break;
10541 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10542 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10543 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10544 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10545 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10546 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10547 }
10548
10549 EVT VecTy;
10550 if (IsStore)
10551 VecTy = N->getOperand(2).getValueType();
10552 else
10553 VecTy = N->getValueType(0);
10554
10555 // If the increment is a constant, it must match the memory ref size.
10556 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10557 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10558 uint32_t IncVal = CInc->getZExtValue();
10559 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10560 if (IsLaneOp || IsDupOp)
10561 NumBytes /= VecTy.getVectorNumElements();
10562 if (IncVal != NumBytes)
10563 continue;
10564 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10565 }
10566 SmallVector<SDValue, 8> Ops;
10567 Ops.push_back(N->getOperand(0)); // Incoming chain
10568 // Load lane and store have vector list as input.
10569 if (IsLaneOp || IsStore)
10570 for (unsigned i = 2; i < AddrOpIdx; ++i)
10571 Ops.push_back(N->getOperand(i));
10572 Ops.push_back(Addr); // Base register
10573 Ops.push_back(Inc);
10574
10575 // Return Types.
10576 EVT Tys[6];
10577 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10578 unsigned n;
10579 for (n = 0; n < NumResultVecs; ++n)
10580 Tys[n] = VecTy;
10581 Tys[n++] = MVT::i64; // Type of write back register
10582 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010583 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010584
10585 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10586 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10587 MemInt->getMemoryVT(),
10588 MemInt->getMemOperand());
10589
10590 // Update the uses.
10591 std::vector<SDValue> NewResults;
10592 for (unsigned i = 0; i < NumResultVecs; ++i) {
10593 NewResults.push_back(SDValue(UpdN.getNode(), i));
10594 }
10595 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10596 DCI.CombineTo(N, NewResults);
10597 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10598
10599 break;
10600 }
10601 return SDValue();
10602}
10603
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010604// Checks to see if the value is the prescribed width and returns information
10605// about its extension mode.
10606static
10607bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10608 ExtType = ISD::NON_EXTLOAD;
10609 switch(V.getNode()->getOpcode()) {
10610 default:
10611 return false;
10612 case ISD::LOAD: {
10613 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10614 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10615 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10616 ExtType = LoadNode->getExtensionType();
10617 return true;
10618 }
10619 return false;
10620 }
10621 case ISD::AssertSext: {
10622 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10623 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10624 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10625 ExtType = ISD::SEXTLOAD;
10626 return true;
10627 }
10628 return false;
10629 }
10630 case ISD::AssertZext: {
10631 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10632 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10633 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10634 ExtType = ISD::ZEXTLOAD;
10635 return true;
10636 }
10637 return false;
10638 }
10639 case ISD::Constant:
10640 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010641 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10642 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010643 }
10644 }
10645
10646 return true;
10647}
10648
10649// This function does a whole lot of voodoo to determine if the tests are
10650// equivalent without and with a mask. Essentially what happens is that given a
10651// DAG resembling:
10652//
10653// +-------------+ +-------------+ +-------------+ +-------------+
10654// | Input | | AddConstant | | CompConstant| | CC |
10655// +-------------+ +-------------+ +-------------+ +-------------+
10656// | | | |
10657// V V | +----------+
10658// +-------------+ +----+ | |
10659// | ADD | |0xff| | |
10660// +-------------+ +----+ | |
10661// | | | |
10662// V V | |
10663// +-------------+ | |
10664// | AND | | |
10665// +-------------+ | |
10666// | | |
10667// +-----+ | |
10668// | | |
10669// V V V
10670// +-------------+
10671// | CMP |
10672// +-------------+
10673//
10674// The AND node may be safely removed for some combinations of inputs. In
10675// particular we need to take into account the extension type of the Input,
10676// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10677// width of the input (this can work for any width inputs, the above graph is
10678// specific to 8 bits.
10679//
10680// The specific equations were worked out by generating output tables for each
10681// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10682// problem was simplified by working with 4 bit inputs, which means we only
10683// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10684// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10685// patterns present in both extensions (0,7). For every distinct set of
10686// AddConstant and CompConstants bit patterns we can consider the masked and
10687// unmasked versions to be equivalent if the result of this function is true for
10688// all 16 distinct bit patterns of for the current extension type of Input (w0).
10689//
10690// sub w8, w0, w1
10691// and w10, w8, #0x0f
10692// cmp w8, w2
10693// cset w9, AArch64CC
10694// cmp w10, w2
10695// cset w11, AArch64CC
10696// cmp w9, w11
10697// cset w0, eq
10698// ret
10699//
10700// Since the above function shows when the outputs are equivalent it defines
10701// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10702// would be expensive to run during compiles. The equations below were written
10703// in a test harness that confirmed they gave equivalent outputs to the above
10704// for all inputs function, so they can be used determine if the removal is
10705// legal instead.
10706//
10707// isEquivalentMaskless() is the code for testing if the AND can be removed
10708// factored out of the DAG recognition as the DAG can take several forms.
10709
David Majnemere61e4bf2016-06-21 05:10:24 +000010710static bool isEquivalentMaskless(unsigned CC, unsigned width,
10711 ISD::LoadExtType ExtType, int AddConstant,
10712 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010713 // By being careful about our equations and only writing the in term
10714 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10715 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010716 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010717
10718 // For the purposes of these comparisons sign extending the type is
10719 // equivalent to zero extending the add and displacing it by half the integer
10720 // width. Provided we are careful and make sure our equations are valid over
10721 // the whole range we can just adjust the input and avoid writing equations
10722 // for sign extended inputs.
10723 if (ExtType == ISD::SEXTLOAD)
10724 AddConstant -= (1 << (width-1));
10725
10726 switch(CC) {
10727 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010728 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010729 if ((AddConstant == 0) ||
10730 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10731 (AddConstant >= 0 && CompConstant < 0) ||
10732 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10733 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010734 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010735 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010736 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010737 if ((AddConstant == 0) ||
10738 (AddConstant >= 0 && CompConstant <= 0) ||
10739 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10740 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010741 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010742 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010743 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010744 if ((AddConstant >= 0 && CompConstant < 0) ||
10745 (AddConstant <= 0 && CompConstant >= -1 &&
10746 CompConstant < AddConstant + MaxUInt))
10747 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010748 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010749 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010750 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010751 if ((AddConstant == 0) ||
10752 (AddConstant > 0 && CompConstant <= 0) ||
10753 (AddConstant < 0 && CompConstant <= AddConstant))
10754 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010755 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010756 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010757 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010758 if ((AddConstant >= 0 && CompConstant <= 0) ||
10759 (AddConstant <= 0 && CompConstant >= 0 &&
10760 CompConstant <= AddConstant + MaxUInt))
10761 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010762 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010763 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010764 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010765 if ((AddConstant > 0 && CompConstant < 0) ||
10766 (AddConstant < 0 && CompConstant >= 0 &&
10767 CompConstant < AddConstant + MaxUInt) ||
10768 (AddConstant >= 0 && CompConstant >= 0 &&
10769 CompConstant >= AddConstant) ||
10770 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010771 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010772 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010773 case AArch64CC::VS:
10774 case AArch64CC::VC:
10775 case AArch64CC::AL:
10776 case AArch64CC::NV:
10777 return true;
10778 case AArch64CC::Invalid:
10779 break;
10780 }
10781
10782 return false;
10783}
10784
10785static
10786SDValue performCONDCombine(SDNode *N,
10787 TargetLowering::DAGCombinerInfo &DCI,
10788 SelectionDAG &DAG, unsigned CCIndex,
10789 unsigned CmpIndex) {
10790 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10791 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10792 unsigned CondOpcode = SubsNode->getOpcode();
10793
10794 if (CondOpcode != AArch64ISD::SUBS)
10795 return SDValue();
10796
10797 // There is a SUBS feeding this condition. Is it fed by a mask we can
10798 // use?
10799
10800 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10801 unsigned MaskBits = 0;
10802
10803 if (AndNode->getOpcode() != ISD::AND)
10804 return SDValue();
10805
10806 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10807 uint32_t CNV = CN->getZExtValue();
10808 if (CNV == 255)
10809 MaskBits = 8;
10810 else if (CNV == 65535)
10811 MaskBits = 16;
10812 }
10813
10814 if (!MaskBits)
10815 return SDValue();
10816
10817 SDValue AddValue = AndNode->getOperand(0);
10818
10819 if (AddValue.getOpcode() != ISD::ADD)
10820 return SDValue();
10821
10822 // The basic dag structure is correct, grab the inputs and validate them.
10823
10824 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10825 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10826 SDValue SubsInputValue = SubsNode->getOperand(1);
10827
10828 // The mask is present and the provenance of all the values is a smaller type,
10829 // lets see if the mask is superfluous.
10830
10831 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10832 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10833 return SDValue();
10834
10835 ISD::LoadExtType ExtType;
10836
10837 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10838 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10839 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10840 return SDValue();
10841
10842 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10843 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10844 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10845 return SDValue();
10846
10847 // The AND is not necessary, remove it.
10848
10849 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10850 SubsNode->getValueType(1));
10851 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10852
10853 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10854 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10855
10856 return SDValue(N, 0);
10857}
10858
Tim Northover3b0846e2014-05-24 12:50:23 +000010859// Optimize compare with zero and branch.
10860static SDValue performBRCONDCombine(SDNode *N,
10861 TargetLowering::DAGCombinerInfo &DCI,
10862 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000010863 MachineFunction &MF = DAG.getMachineFunction();
10864 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
10865 // will not be produced, as they are conditional branch instructions that do
10866 // not set flags.
10867 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
10868 return SDValue();
10869
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010870 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010871 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010872 SDValue Chain = N->getOperand(0);
10873 SDValue Dest = N->getOperand(1);
10874 SDValue CCVal = N->getOperand(2);
10875 SDValue Cmp = N->getOperand(3);
10876
10877 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10878 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10879 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10880 return SDValue();
10881
10882 unsigned CmpOpc = Cmp.getOpcode();
10883 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10884 return SDValue();
10885
10886 // Only attempt folding if there is only one use of the flag and no use of the
10887 // value.
10888 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10889 return SDValue();
10890
10891 SDValue LHS = Cmp.getOperand(0);
10892 SDValue RHS = Cmp.getOperand(1);
10893
10894 assert(LHS.getValueType() == RHS.getValueType() &&
10895 "Expected the value type to be the same for both operands!");
10896 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10897 return SDValue();
10898
Artyom Skrobov314ee042015-11-25 19:41:11 +000010899 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010900 std::swap(LHS, RHS);
10901
Artyom Skrobov314ee042015-11-25 19:41:11 +000010902 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010903 return SDValue();
10904
10905 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10906 LHS.getOpcode() == ISD::SRL)
10907 return SDValue();
10908
10909 // Fold the compare into the branch instruction.
10910 SDValue BR;
10911 if (CC == AArch64CC::EQ)
10912 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10913 else
10914 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10915
10916 // Do not add new nodes to DAG combiner worklist.
10917 DCI.CombineTo(N, BR, false);
10918
10919 return SDValue();
10920}
10921
Geoff Berry9e934b02016-01-04 18:55:47 +000010922// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10923// as well as whether the test should be inverted. This code is required to
10924// catch these cases (as opposed to standard dag combines) because
10925// AArch64ISD::TBZ is matched during legalization.
10926static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10927 SelectionDAG &DAG) {
10928
10929 if (!Op->hasOneUse())
10930 return Op;
10931
10932 // We don't handle undef/constant-fold cases below, as they should have
10933 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10934 // etc.)
10935
10936 // (tbz (trunc x), b) -> (tbz x, b)
10937 // This case is just here to enable more of the below cases to be caught.
10938 if (Op->getOpcode() == ISD::TRUNCATE &&
10939 Bit < Op->getValueType(0).getSizeInBits()) {
10940 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10941 }
10942
10943 if (Op->getNumOperands() != 2)
10944 return Op;
10945
10946 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10947 if (!C)
10948 return Op;
10949
10950 switch (Op->getOpcode()) {
10951 default:
10952 return Op;
10953
10954 // (tbz (and x, m), b) -> (tbz x, b)
10955 case ISD::AND:
10956 if ((C->getZExtValue() >> Bit) & 1)
10957 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10958 return Op;
10959
10960 // (tbz (shl x, c), b) -> (tbz x, b-c)
10961 case ISD::SHL:
10962 if (C->getZExtValue() <= Bit &&
10963 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10964 Bit = Bit - C->getZExtValue();
10965 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10966 }
10967 return Op;
10968
10969 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10970 case ISD::SRA:
10971 Bit = Bit + C->getZExtValue();
10972 if (Bit >= Op->getValueType(0).getSizeInBits())
10973 Bit = Op->getValueType(0).getSizeInBits() - 1;
10974 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10975
10976 // (tbz (srl x, c), b) -> (tbz x, b+c)
10977 case ISD::SRL:
10978 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10979 Bit = Bit + C->getZExtValue();
10980 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10981 }
10982 return Op;
10983
10984 // (tbz (xor x, -1), b) -> (tbnz x, b)
10985 case ISD::XOR:
10986 if ((C->getZExtValue() >> Bit) & 1)
10987 Invert = !Invert;
10988 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10989 }
10990}
10991
10992// Optimize test single bit zero/non-zero and branch.
10993static SDValue performTBZCombine(SDNode *N,
10994 TargetLowering::DAGCombinerInfo &DCI,
10995 SelectionDAG &DAG) {
10996 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10997 bool Invert = false;
10998 SDValue TestSrc = N->getOperand(1);
10999 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11000
11001 if (TestSrc == NewTestSrc)
11002 return SDValue();
11003
11004 unsigned NewOpc = N->getOpcode();
11005 if (Invert) {
11006 if (NewOpc == AArch64ISD::TBZ)
11007 NewOpc = AArch64ISD::TBNZ;
11008 else {
11009 assert(NewOpc == AArch64ISD::TBNZ);
11010 NewOpc = AArch64ISD::TBZ;
11011 }
11012 }
11013
11014 SDLoc DL(N);
11015 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11016 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11017}
11018
Tim Northover3b0846e2014-05-24 12:50:23 +000011019// vselect (v1i1 setcc) ->
11020// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11021// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11022// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11023// such VSELECT.
11024static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11025 SDValue N0 = N->getOperand(0);
11026 EVT CCVT = N0.getValueType();
11027
11028 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11029 CCVT.getVectorElementType() != MVT::i1)
11030 return SDValue();
11031
11032 EVT ResVT = N->getValueType(0);
11033 EVT CmpVT = N0.getOperand(0).getValueType();
11034 // Only combine when the result type is of the same size as the compared
11035 // operands.
11036 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11037 return SDValue();
11038
11039 SDValue IfTrue = N->getOperand(1);
11040 SDValue IfFalse = N->getOperand(2);
11041 SDValue SetCC =
11042 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11043 N0.getOperand(0), N0.getOperand(1),
11044 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11045 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11046 IfTrue, IfFalse);
11047}
11048
11049/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11050/// the compare-mask instructions rather than going via NZCV, even if LHS and
11051/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11052/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011053static SDValue performSelectCombine(SDNode *N,
11054 TargetLowering::DAGCombinerInfo &DCI) {
11055 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011056 SDValue N0 = N->getOperand(0);
11057 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011058
Ahmed Bougachac004c602015-04-27 21:43:12 +000011059 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011060 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011061
Ahmed Bougachac004c602015-04-27 21:43:12 +000011062 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11063 // scalar SetCCResultType. We also don't expect vectors, because we assume
11064 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11065 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11066 "Scalar-SETCC feeding SELECT has unexpected result type!");
11067
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011068 // If NumMaskElts == 0, the comparison is larger than select result. The
11069 // largest real NEON comparison is 64-bits per lane, which means the result is
11070 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011071 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011072
11073 // Don't try to do this optimization when the setcc itself has i1 operands.
11074 // There are no legal vectors of i1, so this would be pointless.
11075 if (SrcVT == MVT::i1)
11076 return SDValue();
11077
Tim Northover3c0915e2014-08-29 15:34:58 +000011078 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011079 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011080 return SDValue();
11081
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011082 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011083 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11084
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011085 // Also bail out if the vector CCVT isn't the same size as ResVT.
11086 // This can happen if the SETCC operand size doesn't divide the ResVT size
11087 // (e.g., f64 vs v3f32).
11088 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11089 return SDValue();
11090
Ahmed Bougachac004c602015-04-27 21:43:12 +000011091 // Make sure we didn't create illegal types, if we're not supposed to.
11092 assert(DCI.isBeforeLegalize() ||
11093 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11094
Tim Northover3b0846e2014-05-24 12:50:23 +000011095 // First perform a vector comparison, where lane 0 is the one we're interested
11096 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011097 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011098 SDValue LHS =
11099 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11100 SDValue RHS =
11101 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11102 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11103
11104 // Now duplicate the comparison mask we want across all other lanes.
11105 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011106 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011107 Mask = DAG.getNode(ISD::BITCAST, DL,
11108 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011109
11110 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11111}
11112
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011113/// Get rid of unnecessary NVCASTs (that don't change the type).
11114static SDValue performNVCASTCombine(SDNode *N) {
11115 if (N->getValueType(0) == N->getOperand(0).getValueType())
11116 return N->getOperand(0);
11117
11118 return SDValue();
11119}
11120
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011121// If all users of the globaladdr are of the form (globaladdr + constant), find
11122// the smallest constant, fold it into the globaladdr's offset and rewrite the
11123// globaladdr as (globaladdr + constant) - constant.
11124static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11125 const AArch64Subtarget *Subtarget,
11126 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011127 auto *GN = cast<GlobalAddressSDNode>(N);
11128 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11129 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011130 return SDValue();
11131
11132 uint64_t MinOffset = -1ull;
11133 for (SDNode *N : GN->uses()) {
11134 if (N->getOpcode() != ISD::ADD)
11135 return SDValue();
11136 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11137 if (!C)
11138 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11139 if (!C)
11140 return SDValue();
11141 MinOffset = std::min(MinOffset, C->getZExtValue());
11142 }
11143 uint64_t Offset = MinOffset + GN->getOffset();
11144
11145 // Require that the new offset is larger than the existing one. Otherwise, we
11146 // can end up oscillating between two possible DAGs, for example,
11147 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11148 if (Offset <= uint64_t(GN->getOffset()))
11149 return SDValue();
11150
11151 // Check whether folding this offset is legal. It must not go out of bounds of
11152 // the referenced object to avoid violating the code model, and must be
11153 // smaller than 2^21 because this is the largest offset expressible in all
11154 // object formats.
11155 //
11156 // This check also prevents us from folding negative offsets, which will end
11157 // up being treated in the same way as large positive ones. They could also
11158 // cause code model violations, and aren't really common enough to matter.
11159 if (Offset >= (1 << 21))
11160 return SDValue();
11161
11162 const GlobalValue *GV = GN->getGlobal();
11163 Type *T = GV->getValueType();
11164 if (!T->isSized() ||
11165 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11166 return SDValue();
11167
11168 SDLoc DL(GN);
11169 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11170 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11171 DAG.getConstant(MinOffset, DL, MVT::i64));
11172}
11173
Tim Northover3b0846e2014-05-24 12:50:23 +000011174SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11175 DAGCombinerInfo &DCI) const {
11176 SelectionDAG &DAG = DCI.DAG;
11177 switch (N->getOpcode()) {
11178 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011179 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011180 break;
11181 case ISD::ADD:
11182 case ISD::SUB:
11183 return performAddSubLongCombine(N, DCI, DAG);
11184 case ISD::XOR:
11185 return performXorCombine(N, DAG, DCI, Subtarget);
11186 case ISD::MUL:
11187 return performMulCombine(N, DAG, DCI, Subtarget);
11188 case ISD::SINT_TO_FP:
11189 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011190 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011191 case ISD::FP_TO_SINT:
11192 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011193 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011194 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011195 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011196 case ISD::OR:
11197 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011198 case ISD::SRL:
11199 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011200 case ISD::INTRINSIC_WO_CHAIN:
11201 return performIntrinsicCombine(N, DCI, Subtarget);
11202 case ISD::ANY_EXTEND:
11203 case ISD::ZERO_EXTEND:
11204 case ISD::SIGN_EXTEND:
11205 return performExtendCombine(N, DCI, DAG);
11206 case ISD::BITCAST:
11207 return performBitcastCombine(N, DCI, DAG);
11208 case ISD::CONCAT_VECTORS:
11209 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011210 case ISD::SELECT:
11211 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011212 case ISD::VSELECT:
11213 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011214 case ISD::LOAD:
11215 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11216 return SDValue(N, 0);
11217 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011218 case ISD::STORE:
11219 return performSTORECombine(N, DCI, DAG, Subtarget);
11220 case AArch64ISD::BRCOND:
11221 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011222 case AArch64ISD::TBNZ:
11223 case AArch64ISD::TBZ:
11224 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011225 case AArch64ISD::CSEL:
11226 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011227 case AArch64ISD::DUP:
11228 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011229 case AArch64ISD::NVCAST:
11230 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011231 case ISD::INSERT_VECTOR_ELT:
11232 return performPostLD1Combine(N, DCI, true);
11233 case ISD::INTRINSIC_VOID:
11234 case ISD::INTRINSIC_W_CHAIN:
11235 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11236 case Intrinsic::aarch64_neon_ld2:
11237 case Intrinsic::aarch64_neon_ld3:
11238 case Intrinsic::aarch64_neon_ld4:
11239 case Intrinsic::aarch64_neon_ld1x2:
11240 case Intrinsic::aarch64_neon_ld1x3:
11241 case Intrinsic::aarch64_neon_ld1x4:
11242 case Intrinsic::aarch64_neon_ld2lane:
11243 case Intrinsic::aarch64_neon_ld3lane:
11244 case Intrinsic::aarch64_neon_ld4lane:
11245 case Intrinsic::aarch64_neon_ld2r:
11246 case Intrinsic::aarch64_neon_ld3r:
11247 case Intrinsic::aarch64_neon_ld4r:
11248 case Intrinsic::aarch64_neon_st2:
11249 case Intrinsic::aarch64_neon_st3:
11250 case Intrinsic::aarch64_neon_st4:
11251 case Intrinsic::aarch64_neon_st1x2:
11252 case Intrinsic::aarch64_neon_st1x3:
11253 case Intrinsic::aarch64_neon_st1x4:
11254 case Intrinsic::aarch64_neon_st2lane:
11255 case Intrinsic::aarch64_neon_st3lane:
11256 case Intrinsic::aarch64_neon_st4lane:
11257 return performNEONPostLDSTCombine(N, DCI, DAG);
11258 default:
11259 break;
11260 }
Reid Klecknereb568942018-11-01 18:02:27 +000011261 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011262 case ISD::GlobalAddress:
11263 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011264 }
11265 return SDValue();
11266}
11267
11268// Check if the return value is used as only a return value, as otherwise
11269// we can't perform a tail-call. In particular, we need to check for
11270// target ISD nodes that are returns and any other "odd" constructs
11271// that the generic analysis code won't necessarily catch.
11272bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11273 SDValue &Chain) const {
11274 if (N->getNumValues() != 1)
11275 return false;
11276 if (!N->hasNUsesOfValue(1, 0))
11277 return false;
11278
11279 SDValue TCChain = Chain;
11280 SDNode *Copy = *N->use_begin();
11281 if (Copy->getOpcode() == ISD::CopyToReg) {
11282 // If the copy has a glue operand, we conservatively assume it isn't safe to
11283 // perform a tail call.
11284 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11285 MVT::Glue)
11286 return false;
11287 TCChain = Copy->getOperand(0);
11288 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11289 return false;
11290
11291 bool HasRet = false;
11292 for (SDNode *Node : Copy->uses()) {
11293 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11294 return false;
11295 HasRet = true;
11296 }
11297
11298 if (!HasRet)
11299 return false;
11300
11301 Chain = TCChain;
11302 return true;
11303}
11304
11305// Return whether the an instruction can potentially be optimized to a tail
11306// call. This will cause the optimizers to attempt to move, or duplicate,
11307// return instructions to help enable tail call optimizations for this
11308// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011309bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011310 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011311}
11312
11313bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11314 SDValue &Offset,
11315 ISD::MemIndexedMode &AM,
11316 bool &IsInc,
11317 SelectionDAG &DAG) const {
11318 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11319 return false;
11320
11321 Base = Op->getOperand(0);
11322 // All of the indexed addressing mode instructions take a signed
11323 // 9 bit immediate offset.
11324 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011325 int64_t RHSC = RHS->getSExtValue();
11326 if (Op->getOpcode() == ISD::SUB)
11327 RHSC = -(uint64_t)RHSC;
11328 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011329 return false;
11330 IsInc = (Op->getOpcode() == ISD::ADD);
11331 Offset = Op->getOperand(1);
11332 return true;
11333 }
11334 return false;
11335}
11336
11337bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11338 SDValue &Offset,
11339 ISD::MemIndexedMode &AM,
11340 SelectionDAG &DAG) const {
11341 EVT VT;
11342 SDValue Ptr;
11343 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11344 VT = LD->getMemoryVT();
11345 Ptr = LD->getBasePtr();
11346 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11347 VT = ST->getMemoryVT();
11348 Ptr = ST->getBasePtr();
11349 } else
11350 return false;
11351
11352 bool IsInc;
11353 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11354 return false;
11355 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11356 return true;
11357}
11358
11359bool AArch64TargetLowering::getPostIndexedAddressParts(
11360 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11361 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11362 EVT VT;
11363 SDValue Ptr;
11364 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11365 VT = LD->getMemoryVT();
11366 Ptr = LD->getBasePtr();
11367 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11368 VT = ST->getMemoryVT();
11369 Ptr = ST->getBasePtr();
11370 } else
11371 return false;
11372
11373 bool IsInc;
11374 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11375 return false;
11376 // Post-indexing updates the base, so it's not a valid transform
11377 // if that's not the same as the load's pointer.
11378 if (Ptr != Base)
11379 return false;
11380 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11381 return true;
11382}
11383
Tim Northoverf8bfe212014-07-18 13:07:05 +000011384static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11385 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011386 SDLoc DL(N);
11387 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011388
11389 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11390 return;
11391
Tim Northoverf8bfe212014-07-18 13:07:05 +000011392 Op = SDValue(
11393 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11394 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011395 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011396 0);
11397 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11398 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11399}
11400
Charlie Turner434d4592015-10-16 15:38:25 +000011401static void ReplaceReductionResults(SDNode *N,
11402 SmallVectorImpl<SDValue> &Results,
11403 SelectionDAG &DAG, unsigned InterOp,
11404 unsigned AcrossOp) {
11405 EVT LoVT, HiVT;
11406 SDValue Lo, Hi;
11407 SDLoc dl(N);
11408 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11409 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11410 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11411 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11412 Results.push_back(SplitVal);
11413}
11414
Tim Northover2f32e7f2016-08-04 19:32:28 +000011415static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11416 SDLoc DL(N);
11417 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11418 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11419 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11420 DAG.getConstant(64, DL, MVT::i64)));
11421 return std::make_pair(Lo, Hi);
11422}
11423
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011424// Create an even/odd pair of X registers holding integer value V.
11425static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11426 SDLoc dl(V.getNode());
11427 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11428 SDValue VHi = DAG.getAnyExtOrTrunc(
11429 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11430 dl, MVT::i64);
11431 if (DAG.getDataLayout().isBigEndian())
11432 std::swap (VLo, VHi);
11433 SDValue RegClass =
11434 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11435 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11436 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11437 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11438 return SDValue(
11439 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11440}
11441
Tim Northovercdf15292016-04-14 17:03:29 +000011442static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011443 SmallVectorImpl<SDValue> &Results,
11444 SelectionDAG &DAG,
11445 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011446 assert(N->getValueType(0) == MVT::i128 &&
11447 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011448
11449 if (Subtarget->hasLSE()) {
11450 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11451 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11452 SDValue Ops[] = {
11453 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11454 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11455 N->getOperand(1), // Ptr
11456 N->getOperand(0), // Chain in
11457 };
11458
Chandler Carruth66654b72018-08-14 23:30:32 +000011459 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011460
11461 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011462 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011463 case AtomicOrdering::Monotonic:
11464 Opcode = AArch64::CASPX;
11465 break;
11466 case AtomicOrdering::Acquire:
11467 Opcode = AArch64::CASPAX;
11468 break;
11469 case AtomicOrdering::Release:
11470 Opcode = AArch64::CASPLX;
11471 break;
11472 case AtomicOrdering::AcquireRelease:
11473 case AtomicOrdering::SequentiallyConsistent:
11474 Opcode = AArch64::CASPALX;
11475 break;
11476 default:
11477 llvm_unreachable("Unexpected ordering!");
11478 }
11479
11480 MachineSDNode *CmpSwap = DAG.getMachineNode(
11481 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011482 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011483
11484 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11485 if (DAG.getDataLayout().isBigEndian())
11486 std::swap(SubReg1, SubReg2);
11487 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11488 SDValue(CmpSwap, 0)));
11489 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11490 SDValue(CmpSwap, 0)));
11491 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11492 return;
11493 }
11494
Tim Northover2f32e7f2016-08-04 19:32:28 +000011495 auto Desired = splitInt128(N->getOperand(2), DAG);
11496 auto New = splitInt128(N->getOperand(3), DAG);
11497 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11498 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011499 SDNode *CmpSwap = DAG.getMachineNode(
11500 AArch64::CMP_SWAP_128, SDLoc(N),
11501 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11502
Chandler Carruth66654b72018-08-14 23:30:32 +000011503 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11504 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011505
11506 Results.push_back(SDValue(CmpSwap, 0));
11507 Results.push_back(SDValue(CmpSwap, 1));
11508 Results.push_back(SDValue(CmpSwap, 3));
11509}
11510
Tim Northover3b0846e2014-05-24 12:50:23 +000011511void AArch64TargetLowering::ReplaceNodeResults(
11512 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11513 switch (N->getOpcode()) {
11514 default:
11515 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011516 case ISD::BITCAST:
11517 ReplaceBITCASTResults(N, Results, DAG);
11518 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011519 case ISD::VECREDUCE_ADD:
11520 case ISD::VECREDUCE_SMAX:
11521 case ISD::VECREDUCE_SMIN:
11522 case ISD::VECREDUCE_UMAX:
11523 case ISD::VECREDUCE_UMIN:
11524 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11525 return;
11526
Charlie Turner434d4592015-10-16 15:38:25 +000011527 case AArch64ISD::SADDV:
11528 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11529 return;
11530 case AArch64ISD::UADDV:
11531 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11532 return;
11533 case AArch64ISD::SMINV:
11534 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11535 return;
11536 case AArch64ISD::UMINV:
11537 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11538 return;
11539 case AArch64ISD::SMAXV:
11540 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11541 return;
11542 case AArch64ISD::UMAXV:
11543 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11544 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011545 case ISD::FP_TO_UINT:
11546 case ISD::FP_TO_SINT:
11547 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11548 // Let normal code take care of it by not adding anything to Results.
11549 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011550 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011551 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011552 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011553 }
11554}
11555
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011556bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011557 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11558 return TargetLowering::useLoadStackGuardNode();
11559 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011560}
11561
Sanjay Patel1dd15592015-07-28 23:05:48 +000011562unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011563 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11564 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011565 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011566}
11567
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011568TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011569AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011570 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11571 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011572 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11573 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011574 return TypeWidenVector;
11575
11576 return TargetLoweringBase::getPreferredVectorAction(VT);
11577}
11578
Robin Morisseted3d48f2014-09-03 21:29:59 +000011579// Loads and stores less than 128-bits are already atomic; ones above that
11580// are doomed anyway, so defer to the default libcall and blame the OS when
11581// things go wrong.
11582bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11583 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11584 return Size == 128;
11585}
11586
11587// Loads and stores less than 128-bits are already atomic; ones above that
11588// are doomed anyway, so defer to the default libcall and blame the OS when
11589// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011590TargetLowering::AtomicExpansionKind
11591AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011592 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011593 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011594}
11595
11596// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011597TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011598AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011599 if (AI->isFloatingPointOperation())
11600 return AtomicExpansionKind::CmpXChg;
11601
Robin Morisseted3d48f2014-09-03 21:29:59 +000011602 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011603 if (Size > 128) return AtomicExpansionKind::None;
11604 // Nand not supported in LSE.
11605 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011606 // Leave 128 bits to LLSC.
11607 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011608}
11609
Alex Bradbury79518b02018-09-19 14:51:42 +000011610TargetLowering::AtomicExpansionKind
11611AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011612 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011613 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011614 if (Subtarget->hasLSE())
11615 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011616 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11617 // implement cmpxchg without spilling. If the address being exchanged is also
11618 // on the stack and close enough to the spill slot, this can lead to a
11619 // situation where the monitor always gets cleared and the atomic operation
11620 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011621 if (getTargetMachine().getOptLevel() == 0)
11622 return AtomicExpansionKind::None;
11623 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011624}
11625
Tim Northover3b0846e2014-05-24 12:50:23 +000011626Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11627 AtomicOrdering Ord) const {
11628 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11629 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011630 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011631
11632 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11633 // intrinsic must return {i64, i64} and we have to recombine them into a
11634 // single i128 here.
11635 if (ValTy->getPrimitiveSizeInBits() == 128) {
11636 Intrinsic::ID Int =
11637 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011638 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011639
11640 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11641 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11642
11643 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11644 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11645 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11646 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11647 return Builder.CreateOr(
11648 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11649 }
11650
11651 Type *Tys[] = { Addr->getType() };
11652 Intrinsic::ID Int =
11653 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011654 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011655
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011656 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11657
11658 const DataLayout &DL = M->getDataLayout();
11659 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11660 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11661
11662 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011663}
11664
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011665void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11666 IRBuilder<> &Builder) const {
11667 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011668 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011669}
11670
Tim Northover3b0846e2014-05-24 12:50:23 +000011671Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11672 Value *Val, Value *Addr,
11673 AtomicOrdering Ord) const {
11674 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011675 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011676
11677 // Since the intrinsics must have legal type, the i128 intrinsics take two
11678 // parameters: "i64, i64". We must marshal Val into the appropriate form
11679 // before the call.
11680 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11681 Intrinsic::ID Int =
11682 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11683 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11684 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11685
11686 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11687 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11688 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011689 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011690 }
11691
11692 Intrinsic::ID Int =
11693 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11694 Type *Tys[] = { Addr->getType() };
11695 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11696
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011697 const DataLayout &DL = M->getDataLayout();
11698 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11699 Val = Builder.CreateBitCast(Val, IntValTy);
11700
David Blaikieff6409d2015-05-18 22:13:54 +000011701 return Builder.CreateCall(Stxr,
11702 {Builder.CreateZExtOrBitCast(
11703 Val, Stxr->getFunctionType()->getParamType(0)),
11704 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011705}
Tim Northover3c55cca2014-11-27 21:02:42 +000011706
11707bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11708 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11709 return Ty->isArrayTy();
11710}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011711
11712bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11713 EVT) const {
11714 return false;
11715}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011716
Petr Hoseka7d59162017-02-24 03:10:10 +000011717static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011718 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11719 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011720 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011721 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000011722 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11723 Offset),
11724 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011725}
11726
Petr Hoseka7d59162017-02-24 03:10:10 +000011727Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11728 // Android provides a fixed TLS slot for the stack cookie. See the definition
11729 // of TLS_SLOT_STACK_GUARD in
11730 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11731 if (Subtarget->isTargetAndroid())
11732 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011733
Petr Hoseka7d59162017-02-24 03:10:10 +000011734 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011735 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011736 if (Subtarget->isTargetFuchsia())
11737 return UseTlsOffset(IRB, -0x10);
11738
11739 return TargetLowering::getIRStackGuard(IRB);
11740}
11741
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011742void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11743 // MSVC CRT provides functionalities for stack protection.
11744 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11745 // MSVC CRT has a global variable holding security cookie.
11746 M.getOrInsertGlobal("__security_cookie",
11747 Type::getInt8PtrTy(M.getContext()));
11748
11749 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000011750 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11751 "__security_check_cookie", Type::getVoidTy(M.getContext()),
11752 Type::getInt8PtrTy(M.getContext()));
11753 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
11754 F->setCallingConv(CallingConv::Win64);
11755 F->addAttribute(1, Attribute::AttrKind::InReg);
11756 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011757 return;
11758 }
11759 TargetLowering::insertSSPDeclarations(M);
11760}
11761
11762Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11763 // MSVC CRT has a global variable holding security cookie.
11764 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11765 return M.getGlobalVariable("__security_cookie");
11766 return TargetLowering::getSDagStackGuard(M);
11767}
11768
James Y Knight7976eb52019-02-01 20:43:25 +000011769Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011770 // MSVC CRT has a function to validate security cookie.
11771 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11772 return M.getFunction("__security_check_cookie");
11773 return TargetLowering::getSSPStackGuardCheck(M);
11774}
11775
Petr Hoseka7d59162017-02-24 03:10:10 +000011776Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011777 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11778 // definition of TLS_SLOT_SAFESTACK in
11779 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011780 if (Subtarget->isTargetAndroid())
11781 return UseTlsOffset(IRB, 0x48);
11782
11783 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011784 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011785 if (Subtarget->isTargetFuchsia())
11786 return UseTlsOffset(IRB, -0x8);
11787
11788 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011789}
Manman Rencbe4f942015-12-16 21:04:19 +000011790
Geoff Berry5d534b62017-02-21 18:53:14 +000011791bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11792 const Instruction &AndI) const {
11793 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11794 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11795 // may be beneficial to sink in other cases, but we would have to check that
11796 // the cmp would not get folded into the br to form a cbz for these to be
11797 // beneficial.
11798 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11799 if (!Mask)
11800 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011801 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011802}
11803
Manman Rencbe4f942015-12-16 21:04:19 +000011804void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11805 // Update IsSplitCSR in AArch64unctionInfo.
11806 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11807 AFI->setIsSplitCSR(true);
11808}
11809
11810void AArch64TargetLowering::insertCopiesSplitCSR(
11811 MachineBasicBlock *Entry,
11812 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11813 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11814 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11815 if (!IStart)
11816 return;
11817
11818 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11819 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011820 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011821 for (const MCPhysReg *I = IStart; *I; ++I) {
11822 const TargetRegisterClass *RC = nullptr;
11823 if (AArch64::GPR64RegClass.contains(*I))
11824 RC = &AArch64::GPR64RegClass;
11825 else if (AArch64::FPR64RegClass.contains(*I))
11826 RC = &AArch64::FPR64RegClass;
11827 else
11828 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11829
11830 unsigned NewVR = MRI->createVirtualRegister(RC);
11831 // Create copy from CSR to a virtual register.
11832 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11833 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11834 // nounwind. If we want to generalize this later, we may need to emit
11835 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011836 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011837 Attribute::NoUnwind) &&
11838 "Function should be nounwind in insertCopiesSplitCSR!");
11839 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011840 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011841 .addReg(*I);
11842
Manman Ren4632e8e2016-01-15 20:13:28 +000011843 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011844 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011845 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11846 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011847 .addReg(NewVR);
11848 }
11849}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011850
Reid Klecknerb5180542017-03-21 16:57:19 +000011851bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011852 // Integer division on AArch64 is expensive. However, when aggressively
11853 // optimizing for code size, we prefer to use a div instruction, as it is
11854 // usually smaller than the alternative sequence.
11855 // The exception to this is vector division. Since AArch64 doesn't have vector
11856 // integer division, leaving the division as-is is a loss even in terms of
11857 // size, because it will have to be scalarized, while the alternative code
11858 // sequence can be performed in vector form.
11859 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011860 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011861 return OptSize && !VT.isVector();
11862}
Tim Northoverf19d4672017-02-08 17:57:20 +000011863
Joel Jones07150922018-01-25 21:55:39 +000011864bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11865 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11866}
11867
Tim Northoverf19d4672017-02-08 17:57:20 +000011868unsigned
11869AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011870 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011871 return getPointerTy(DL).getSizeInBits();
11872
11873 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11874}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011875
11876void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11877 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11878 TargetLoweringBase::finalizeLowering(MF);
11879}
Eli Friedmanad1151c2018-11-09 23:33:30 +000011880
11881// Unlike X86, we let frame lowering assign offsets to all catch objects.
11882bool AArch64TargetLowering::needsFixedCatchObjects() const {
11883 return false;
11884}