blob: c65af806d512c7bf5cedf6e23bac28e37c1eda04 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000018#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000020#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000021#include "Utils/AArch64BaseInfo.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/STLExtras.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000026#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000027#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000028#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000032#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000033#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000035#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000036#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000039#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000041#include "llvm/CodeGen/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000044#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000046#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000047#include "llvm/IR/Attributes.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000052#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000054#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000055#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000056#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000058#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000059#include "llvm/IR/Module.h"
60#include "llvm/IR/OperandTraits.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000061#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000062#include "llvm/IR/Use.h"
63#include "llvm/IR/Value.h"
64#include "llvm/MC/MCRegisterInfo.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000067#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000068#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000069#include "llvm/Support/Debug.h"
70#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000071#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000072#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000073#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000074#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000075#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000076#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000077#include <algorithm>
78#include <bitset>
79#include <cassert>
80#include <cctype>
81#include <cstdint>
82#include <cstdlib>
83#include <iterator>
84#include <limits>
85#include <tuple>
86#include <utility>
87#include <vector>
88
Tim Northover3b0846e2014-05-24 12:50:23 +000089using namespace llvm;
90
91#define DEBUG_TYPE "aarch64-lower"
92
93STATISTIC(NumTailCalls, "Number of tail calls");
94STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000095STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000096
Tim Northover3b0846e2014-05-24 12:50:23 +000097static cl::opt<bool>
98EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000099 cl::desc("Allow AArch64 SLI/SRI formation"),
100 cl::init(false));
101
102// FIXME: The necessary dtprel relocations don't seem to be supported
103// well in the GNU bfd and gold linkers at the moment. Therefore, by
104// default, for now, fall back to GeneralDynamic code generation.
105cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106 "aarch64-elf-ldtls-generation", cl::Hidden,
107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000109
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000110static cl::opt<bool>
111EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112 cl::desc("Enable AArch64 logical imm instruction "
113 "optimization"),
114 cl::init(true));
115
Matthias Braunaf7d7702015-07-16 20:02:37 +0000116/// Value type used for condition codes.
117static const MVT MVT_CC = MVT::i32;
118
Eric Christopher905f12d2015-01-29 00:19:42 +0000119AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120 const AArch64Subtarget &STI)
121 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123 // we have to make something up. Arbitrarily, choose ZeroOrOne.
124 setBooleanContents(ZeroOrOneBooleanContent);
125 // When comparing vectors the result sets the different elements in the
126 // vector to all-one or all-zero.
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129 // Set up the register classes.
130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132
133 if (Subtarget->hasFPARMv8()) {
134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138 }
139
140 if (Subtarget->hasNEON()) {
141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143 // Someone set us up the NEON.
144 addDRTypeForNEON(MVT::v2f32);
145 addDRTypeForNEON(MVT::v8i8);
146 addDRTypeForNEON(MVT::v4i16);
147 addDRTypeForNEON(MVT::v2i32);
148 addDRTypeForNEON(MVT::v1i64);
149 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000150 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000151
152 addQRTypeForNEON(MVT::v4f32);
153 addQRTypeForNEON(MVT::v2f64);
154 addQRTypeForNEON(MVT::v16i8);
155 addQRTypeForNEON(MVT::v8i16);
156 addQRTypeForNEON(MVT::v4i32);
157 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000158 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000159 }
160
161 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000162 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000163
164 // Provide all sorts of operation actions
165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167 setOperationAction(ISD::SETCC, MVT::i32, Custom);
168 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000169 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000170 setOperationAction(ISD::SETCC, MVT::f32, Custom);
171 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000172 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
173 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000174 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
175 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
176 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000177 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000178 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
179 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
180 setOperationAction(ISD::SELECT, MVT::i32, Custom);
181 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000182 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000183 setOperationAction(ISD::SELECT, MVT::f32, Custom);
184 setOperationAction(ISD::SELECT, MVT::f64, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
186 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000187 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000188 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
189 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000190 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
192
193 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
194 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
195 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
196
197 setOperationAction(ISD::FREM, MVT::f32, Expand);
198 setOperationAction(ISD::FREM, MVT::f64, Expand);
199 setOperationAction(ISD::FREM, MVT::f80, Expand);
200
Amara Emersone27d5012018-04-10 19:01:58 +0000201 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
202
Tim Northover3b0846e2014-05-24 12:50:23 +0000203 // Custom lowering hooks are needed for XOR
204 // to fold it into CSINC/CSINV.
205 setOperationAction(ISD::XOR, MVT::i32, Custom);
206 setOperationAction(ISD::XOR, MVT::i64, Custom);
207
208 // Virtually no operation on f128 is legal, but LLVM can't expand them when
209 // there's a valid register class, so we need custom operations in most cases.
210 setOperationAction(ISD::FABS, MVT::f128, Expand);
211 setOperationAction(ISD::FADD, MVT::f128, Custom);
212 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
213 setOperationAction(ISD::FCOS, MVT::f128, Expand);
214 setOperationAction(ISD::FDIV, MVT::f128, Custom);
215 setOperationAction(ISD::FMA, MVT::f128, Expand);
216 setOperationAction(ISD::FMUL, MVT::f128, Custom);
217 setOperationAction(ISD::FNEG, MVT::f128, Expand);
218 setOperationAction(ISD::FPOW, MVT::f128, Expand);
219 setOperationAction(ISD::FREM, MVT::f128, Expand);
220 setOperationAction(ISD::FRINT, MVT::f128, Expand);
221 setOperationAction(ISD::FSIN, MVT::f128, Expand);
222 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
223 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
224 setOperationAction(ISD::FSUB, MVT::f128, Custom);
225 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
226 setOperationAction(ISD::SETCC, MVT::f128, Custom);
227 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
228 setOperationAction(ISD::SELECT, MVT::f128, Custom);
229 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
230 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
231
232 // Lowering for many of the conversions is actually specified by the non-f128
233 // type. The LowerXXX function will be trivial when f128 isn't involved.
234 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
235 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
236 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
237 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
238 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
239 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
240 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
241 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
242 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
243 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
244 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
245 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
246 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
247 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
248
249 // Variable arguments.
250 setOperationAction(ISD::VASTART, MVT::Other, Custom);
251 setOperationAction(ISD::VAARG, MVT::Other, Custom);
252 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
253 setOperationAction(ISD::VAEND, MVT::Other, Expand);
254
255 // Variable-sized objects.
256 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
257 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000258
259 if (Subtarget->isTargetWindows())
260 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
261 else
262 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000263
Tim Northover3b0846e2014-05-24 12:50:23 +0000264 // Constant pool entries
265 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
266
267 // BlockAddress
268 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
269
270 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
271 setOperationAction(ISD::ADDC, MVT::i32, Custom);
272 setOperationAction(ISD::ADDE, MVT::i32, Custom);
273 setOperationAction(ISD::SUBC, MVT::i32, Custom);
274 setOperationAction(ISD::SUBE, MVT::i32, Custom);
275 setOperationAction(ISD::ADDC, MVT::i64, Custom);
276 setOperationAction(ISD::ADDE, MVT::i64, Custom);
277 setOperationAction(ISD::SUBC, MVT::i64, Custom);
278 setOperationAction(ISD::SUBE, MVT::i64, Custom);
279
280 // AArch64 lacks both left-rotate and popcount instructions.
281 setOperationAction(ISD::ROTL, MVT::i32, Expand);
282 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000283 for (MVT VT : MVT::vector_valuetypes()) {
284 setOperationAction(ISD::ROTL, VT, Expand);
285 setOperationAction(ISD::ROTR, VT, Expand);
286 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000287
288 // AArch64 doesn't have {U|S}MUL_LOHI.
289 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
290 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
291
Tim Northover3b0846e2014-05-24 12:50:23 +0000292 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
293 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
294
295 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
296 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000297 for (MVT VT : MVT::vector_valuetypes()) {
298 setOperationAction(ISD::SDIVREM, VT, Expand);
299 setOperationAction(ISD::UDIVREM, VT, Expand);
300 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000301 setOperationAction(ISD::SREM, MVT::i32, Expand);
302 setOperationAction(ISD::SREM, MVT::i64, Expand);
303 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
304 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
305 setOperationAction(ISD::UREM, MVT::i32, Expand);
306 setOperationAction(ISD::UREM, MVT::i64, Expand);
307
308 // Custom lower Add/Sub/Mul with overflow.
309 setOperationAction(ISD::SADDO, MVT::i32, Custom);
310 setOperationAction(ISD::SADDO, MVT::i64, Custom);
311 setOperationAction(ISD::UADDO, MVT::i32, Custom);
312 setOperationAction(ISD::UADDO, MVT::i64, Custom);
313 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
314 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
315 setOperationAction(ISD::USUBO, MVT::i32, Custom);
316 setOperationAction(ISD::USUBO, MVT::i64, Custom);
317 setOperationAction(ISD::SMULO, MVT::i32, Custom);
318 setOperationAction(ISD::SMULO, MVT::i64, Custom);
319 setOperationAction(ISD::UMULO, MVT::i32, Custom);
320 setOperationAction(ISD::UMULO, MVT::i64, Custom);
321
322 setOperationAction(ISD::FSIN, MVT::f32, Expand);
323 setOperationAction(ISD::FSIN, MVT::f64, Expand);
324 setOperationAction(ISD::FCOS, MVT::f32, Expand);
325 setOperationAction(ISD::FCOS, MVT::f64, Expand);
326 setOperationAction(ISD::FPOW, MVT::f32, Expand);
327 setOperationAction(ISD::FPOW, MVT::f64, Expand);
328 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000330 if (Subtarget->hasFullFP16())
331 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
332 else
333 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000334
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000335 setOperationAction(ISD::FREM, MVT::f16, Promote);
336 setOperationAction(ISD::FREM, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000337 setOperationAction(ISD::FREM, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000338 setOperationAction(ISD::FPOW, MVT::f16, Promote);
339 setOperationAction(ISD::FPOW, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000340 setOperationAction(ISD::FPOW, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000341 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
342 setOperationAction(ISD::FCOS, MVT::f16, Promote);
343 setOperationAction(ISD::FCOS, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000344 setOperationAction(ISD::FCOS, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000345 setOperationAction(ISD::FSIN, MVT::f16, Promote);
346 setOperationAction(ISD::FSIN, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000347 setOperationAction(ISD::FSIN, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000348 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
349 setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000350 setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000351 setOperationAction(ISD::FEXP, MVT::f16, Promote);
352 setOperationAction(ISD::FEXP, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000353 setOperationAction(ISD::FEXP, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000354 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
355 setOperationAction(ISD::FEXP2, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000356 setOperationAction(ISD::FEXP2, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000357 setOperationAction(ISD::FLOG, MVT::f16, Promote);
358 setOperationAction(ISD::FLOG, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000359 setOperationAction(ISD::FLOG, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000360 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
361 setOperationAction(ISD::FLOG2, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000362 setOperationAction(ISD::FLOG2, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000363 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
364 setOperationAction(ISD::FLOG10, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000365 setOperationAction(ISD::FLOG10, MVT::v8f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000366
367 if (!Subtarget->hasFullFP16()) {
368 setOperationAction(ISD::SELECT, MVT::f16, Promote);
369 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
370 setOperationAction(ISD::SETCC, MVT::f16, Promote);
371 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
372 setOperationAction(ISD::FADD, MVT::f16, Promote);
373 setOperationAction(ISD::FSUB, MVT::f16, Promote);
374 setOperationAction(ISD::FMUL, MVT::f16, Promote);
375 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000376 setOperationAction(ISD::FMA, MVT::f16, Promote);
377 setOperationAction(ISD::FNEG, MVT::f16, Promote);
378 setOperationAction(ISD::FABS, MVT::f16, Promote);
379 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
380 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000381 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
382 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
383 setOperationAction(ISD::FRINT, MVT::f16, Promote);
384 setOperationAction(ISD::FROUND, MVT::f16, Promote);
385 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
386 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
387 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000388 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
389 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000390
391 // promote v4f16 to v4f32 when that is known to be safe.
392 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
393 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
394 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
395 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
396 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
397 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
398 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
399 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
400 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
401 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
402 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
403 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
404
405 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
406 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
407 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
408 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
409 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
410 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
411 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
412 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
413 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
414 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
415 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
416 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
417 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
418 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
419 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000420
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000421 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
422 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
423 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
424 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
425 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
426 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
427 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
428 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
429 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
430 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
431 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
432 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
433 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
434 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
435 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
436 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
437 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
438 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
439 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
440 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
441 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000442
Tim Northover3b0846e2014-05-24 12:50:23 +0000443 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000444 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000445 setOperationAction(ISD::FFLOOR, Ty, Legal);
446 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
447 setOperationAction(ISD::FCEIL, Ty, Legal);
448 setOperationAction(ISD::FRINT, Ty, Legal);
449 setOperationAction(ISD::FTRUNC, Ty, Legal);
450 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000451 setOperationAction(ISD::FMINNUM, Ty, Legal);
452 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000453 setOperationAction(ISD::FMINIMUM, Ty, Legal);
454 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000455 }
456
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000457 if (Subtarget->hasFullFP16()) {
458 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
459 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
460 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
461 setOperationAction(ISD::FRINT, MVT::f16, Legal);
462 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
463 setOperationAction(ISD::FROUND, MVT::f16, Legal);
464 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
465 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000466 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
467 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000468 }
469
Tim Northover3b0846e2014-05-24 12:50:23 +0000470 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
471
Tim Northover70666e72018-06-20 12:09:01 +0000472 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
473
Tim Northovercdf15292016-04-14 17:03:29 +0000474 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000475 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000477 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000479
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000480 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
481 // This requires the Performance Monitors extension.
482 if (Subtarget->hasPerfMon())
483 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
484
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000485 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
486 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
487 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
489 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
490 } else {
491 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
492 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
493 }
494
Juergen Ributzka23266502014-12-10 19:43:32 +0000495 // Make floating-point constants legal for the large code model, so they don't
496 // become loads from the constant pool.
497 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
498 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
499 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
500 }
501
Tim Northover3b0846e2014-05-24 12:50:23 +0000502 // AArch64 does not have floating-point extending loads, i1 sign-extending
503 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000504 for (MVT VT : MVT::fp_valuetypes()) {
505 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
506 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
507 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
508 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
509 }
510 for (MVT VT : MVT::integer_valuetypes())
511 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
512
Tim Northover3b0846e2014-05-24 12:50:23 +0000513 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
514 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
515 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
516 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
517 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
518 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
519 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000520
521 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
522 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
523
Tim Northover3b0846e2014-05-24 12:50:23 +0000524 // Indexed loads and stores are supported.
525 for (unsigned im = (unsigned)ISD::PRE_INC;
526 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
527 setIndexedLoadAction(im, MVT::i8, Legal);
528 setIndexedLoadAction(im, MVT::i16, Legal);
529 setIndexedLoadAction(im, MVT::i32, Legal);
530 setIndexedLoadAction(im, MVT::i64, Legal);
531 setIndexedLoadAction(im, MVT::f64, Legal);
532 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000533 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000534 setIndexedStoreAction(im, MVT::i8, Legal);
535 setIndexedStoreAction(im, MVT::i16, Legal);
536 setIndexedStoreAction(im, MVT::i32, Legal);
537 setIndexedStoreAction(im, MVT::i64, Legal);
538 setIndexedStoreAction(im, MVT::f64, Legal);
539 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000540 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000541 }
542
543 // Trap.
544 setOperationAction(ISD::TRAP, MVT::Other, Legal);
545
546 // We combine OR nodes for bitfield operations.
547 setTargetDAGCombine(ISD::OR);
548
549 // Vector add and sub nodes may conceal a high-half opportunity.
550 // Also, try to fold ADD into CSINC/CSINV..
551 setTargetDAGCombine(ISD::ADD);
552 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000553 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000554 setTargetDAGCombine(ISD::XOR);
555 setTargetDAGCombine(ISD::SINT_TO_FP);
556 setTargetDAGCombine(ISD::UINT_TO_FP);
557
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000558 setTargetDAGCombine(ISD::FP_TO_SINT);
559 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000560 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000561
Tim Northover3b0846e2014-05-24 12:50:23 +0000562 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
563
564 setTargetDAGCombine(ISD::ANY_EXTEND);
565 setTargetDAGCombine(ISD::ZERO_EXTEND);
566 setTargetDAGCombine(ISD::SIGN_EXTEND);
567 setTargetDAGCombine(ISD::BITCAST);
568 setTargetDAGCombine(ISD::CONCAT_VECTORS);
569 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000570 if (Subtarget->supportsAddressTopByteIgnored())
571 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000572
573 setTargetDAGCombine(ISD::MUL);
574
575 setTargetDAGCombine(ISD::SELECT);
576 setTargetDAGCombine(ISD::VSELECT);
577
578 setTargetDAGCombine(ISD::INTRINSIC_VOID);
579 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
581
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000582 setTargetDAGCombine(ISD::GlobalAddress);
583
Evandro Menezesf8425342018-05-29 15:58:50 +0000584 // In case of strict alignment, avoid an excessive number of byte wide stores.
585 MaxStoresPerMemsetOptSize = 8;
586 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
587 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000588
Evandro Menezesf8425342018-05-29 15:58:50 +0000589 MaxGluedStoresPerMemcpy = 4;
590 MaxStoresPerMemcpyOptSize = 4;
591 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
592 ? MaxStoresPerMemcpyOptSize : 16;
593
594 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000595
596 setStackPointerRegisterToSaveRestore(AArch64::SP);
597
598 setSchedulingPreference(Sched::Hybrid);
599
Quentin Colombet6843ac42015-03-31 20:52:32 +0000600 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000601
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000602 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000603 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000604 // Set preferred alignments.
605 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
606 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000607
Evandro Menezese45de8a2016-09-26 15:32:33 +0000608 // Only change the limit for entries in a jump table if specified by
609 // the subtarget, but not at the command line.
610 unsigned MaxJT = STI.getMaximumJumpTableSize();
611 if (MaxJT && getMaximumJumpTableSize() == 0)
612 setMaximumJumpTableSize(MaxJT);
613
Tim Northover3b0846e2014-05-24 12:50:23 +0000614 setHasExtractBitsInsn(true);
615
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000616 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
617
Tim Northover3b0846e2014-05-24 12:50:23 +0000618 if (Subtarget->hasNEON()) {
619 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
620 // silliness like this:
621 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
622 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
623 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
624 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
625 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
626 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
627 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
628 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
629 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
630 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
631 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
632 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
633 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
634 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
635 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
636 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
637 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
638 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
639 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
640 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
641 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
642 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
643 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
644 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
645 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
646
647 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
648 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
649 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
650 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
651 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
652
653 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
654
655 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
656 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000657 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
658 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
659 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
660 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000661 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
662 // -> v8f16 conversions.
Craig Toppera4f99972018-01-01 19:21:35 +0000663 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
664 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
665 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
666 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000667 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
668 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
669 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
670 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
671 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000672 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
673 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
674 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
675 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000676
Craig Topperc5551bf2016-04-26 05:26:51 +0000677 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
678 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
679
Craig Topper3b4842b2016-04-28 01:58:21 +0000680 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
681 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
682 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
683 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
684 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
685 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
686 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
687 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
688
Tim Northover3b0846e2014-05-24 12:50:23 +0000689 // AArch64 doesn't have MUL.2d:
690 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000691 // Custom handling for some quad-vector types to detect MULL.
692 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
693 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
694 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
695
Amara Emersonc9916d72017-05-16 21:29:22 +0000696 // Vector reductions
697 for (MVT VT : MVT::integer_valuetypes()) {
698 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
699 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
700 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
701 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
702 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
703 }
704 for (MVT VT : MVT::fp_valuetypes()) {
705 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
706 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
707 }
708
Tim Northover3b0846e2014-05-24 12:50:23 +0000709 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
710 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
711 // Likewise, narrowing and extending vector loads/stores aren't handled
712 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000713 for (MVT VT : MVT::vector_valuetypes()) {
714 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000715
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000716 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
717 setOperationAction(ISD::MULHS, VT, Custom);
718 setOperationAction(ISD::MULHU, VT, Custom);
719 } else {
720 setOperationAction(ISD::MULHS, VT, Expand);
721 setOperationAction(ISD::MULHU, VT, Expand);
722 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000723 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000724 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000725
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000726 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000727
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000728 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000729 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000730 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
731 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
732 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
733 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000734 }
735
736 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000737 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000738 setOperationAction(ISD::FFLOOR, Ty, Legal);
739 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
740 setOperationAction(ISD::FCEIL, Ty, Legal);
741 setOperationAction(ISD::FRINT, Ty, Legal);
742 setOperationAction(ISD::FTRUNC, Ty, Legal);
743 setOperationAction(ISD::FROUND, Ty, Legal);
744 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000745
746 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000747 }
James Molloyf089ab72014-08-06 10:42:18 +0000748
Matthias Braun651cff42016-06-02 18:03:53 +0000749 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000750}
751
Craig Topper18e69f42016-04-15 06:20:21 +0000752void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000753 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000754
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000755 if (VT.isFloatingPoint()) {
756 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
757 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
758 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 }
760
761 // Mark vector float intrinsics as expand.
762 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000763 setOperationAction(ISD::FSIN, VT, Expand);
764 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000765 setOperationAction(ISD::FPOW, VT, Expand);
766 setOperationAction(ISD::FLOG, VT, Expand);
767 setOperationAction(ISD::FLOG2, VT, Expand);
768 setOperationAction(ISD::FLOG10, VT, Expand);
769 setOperationAction(ISD::FEXP, VT, Expand);
770 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000771
772 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000773 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000774 }
775
Craig Topper18e69f42016-04-15 06:20:21 +0000776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
778 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
779 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
780 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
781 setOperationAction(ISD::SRA, VT, Custom);
782 setOperationAction(ISD::SRL, VT, Custom);
783 setOperationAction(ISD::SHL, VT, Custom);
784 setOperationAction(ISD::AND, VT, Custom);
785 setOperationAction(ISD::OR, VT, Custom);
786 setOperationAction(ISD::SETCC, VT, Custom);
787 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000788
Craig Topper18e69f42016-04-15 06:20:21 +0000789 setOperationAction(ISD::SELECT, VT, Expand);
790 setOperationAction(ISD::SELECT_CC, VT, Expand);
791 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000792 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000793 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000794
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000795 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000796 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000797 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000798
Craig Topper18e69f42016-04-15 06:20:21 +0000799 setOperationAction(ISD::UDIV, VT, Expand);
800 setOperationAction(ISD::SDIV, VT, Expand);
801 setOperationAction(ISD::UREM, VT, Expand);
802 setOperationAction(ISD::SREM, VT, Expand);
803 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000804
Craig Topper18e69f42016-04-15 06:20:21 +0000805 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
806 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000807
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000808 if (!VT.isFloatingPoint())
809 setOperationAction(ISD::ABS, VT, Legal);
810
Hal Finkelcd8664c2015-12-11 23:11:52 +0000811 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000812 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000813 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000814 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000815
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000816 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
817 if (VT.isFloatingPoint() &&
818 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000819 for (unsigned Opcode :
820 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000821 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000822
Tim Northover3b0846e2014-05-24 12:50:23 +0000823 if (Subtarget->isLittleEndian()) {
824 for (unsigned im = (unsigned)ISD::PRE_INC;
825 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000826 setIndexedLoadAction(im, VT, Legal);
827 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000828 }
829 }
830}
831
832void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
833 addRegisterClass(VT, &AArch64::FPR64RegClass);
834 addTypeForNEON(VT, MVT::v2i32);
835}
836
837void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
838 addRegisterClass(VT, &AArch64::FPR128RegClass);
839 addTypeForNEON(VT, MVT::v4i32);
840}
841
Mehdi Amini44ede332015-07-09 02:09:04 +0000842EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
843 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000844 if (!VT.isVector())
845 return MVT::i32;
846 return VT.changeVectorElementTypeToInteger();
847}
848
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000849static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
850 const APInt &Demanded,
851 TargetLowering::TargetLoweringOpt &TLO,
852 unsigned NewOpc) {
853 uint64_t OldImm = Imm, NewImm, Enc;
854 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
855
856 // Return if the immediate is already all zeros, all ones, a bimm32 or a
857 // bimm64.
858 if (Imm == 0 || Imm == Mask ||
859 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
860 return false;
861
862 unsigned EltSize = Size;
863 uint64_t DemandedBits = Demanded.getZExtValue();
864
865 // Clear bits that are not demanded.
866 Imm &= DemandedBits;
867
868 while (true) {
869 // The goal here is to set the non-demanded bits in a way that minimizes
870 // the number of switching between 0 and 1. In order to achieve this goal,
871 // we set the non-demanded bits to the value of the preceding demanded bits.
872 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
873 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
874 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
875 // The final result is 0b11000011.
876 uint64_t NonDemandedBits = ~DemandedBits;
877 uint64_t InvertedImm = ~Imm & DemandedBits;
878 uint64_t RotatedImm =
879 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
880 NonDemandedBits;
881 uint64_t Sum = RotatedImm + NonDemandedBits;
882 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
883 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
884 NewImm = (Imm | Ones) & Mask;
885
886 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
887 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
888 // we halve the element size and continue the search.
889 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
890 break;
891
892 // We cannot shrink the element size any further if it is 2-bits.
893 if (EltSize == 2)
894 return false;
895
896 EltSize /= 2;
897 Mask >>= EltSize;
898 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
899
900 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
901 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
902 return false;
903
904 // Merge the upper and lower halves of Imm and DemandedBits.
905 Imm |= Hi;
906 DemandedBits |= DemandedBitsHi;
907 }
908
909 ++NumOptimizedImms;
910
911 // Replicate the element across the register width.
912 while (EltSize < Size) {
913 NewImm |= NewImm << EltSize;
914 EltSize *= 2;
915 }
916
917 (void)OldImm;
918 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
919 "demanded bits should never be altered");
920 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
921
922 // Create the new constant immediate node.
923 EVT VT = Op.getValueType();
924 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000925 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000926
927 // If the new constant immediate is all-zeros or all-ones, let the target
928 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000929 if (NewImm == 0 || NewImm == OrigMask) {
930 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
931 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000932 // Otherwise, create a machine node so that target independent DAG combine
933 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000934 } else {
935 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
936 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
937 New = SDValue(
938 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
939 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000940
941 return TLO.CombineTo(Op, New);
942}
943
944bool AArch64TargetLowering::targetShrinkDemandedConstant(
945 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
946 // Delay this optimization to as late as possible.
947 if (!TLO.LegalOps)
948 return false;
949
950 if (!EnableOptimizeLogicalImm)
951 return false;
952
953 EVT VT = Op.getValueType();
954 if (VT.isVector())
955 return false;
956
957 unsigned Size = VT.getSizeInBits();
958 assert((Size == 32 || Size == 64) &&
959 "i32 or i64 is expected after legalization.");
960
961 // Exit early if we demand all bits.
962 if (Demanded.countPopulation() == Size)
963 return false;
964
965 unsigned NewOpc;
966 switch (Op.getOpcode()) {
967 default:
968 return false;
969 case ISD::AND:
970 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
971 break;
972 case ISD::OR:
973 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
974 break;
975 case ISD::XOR:
976 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
977 break;
978 }
979 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
980 if (!C)
981 return false;
982 uint64_t Imm = C->getZExtValue();
983 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
984}
985
Tim Northover3b0846e2014-05-24 12:50:23 +0000986/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000987/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000988void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000989 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000990 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000991 switch (Op.getOpcode()) {
992 default:
993 break;
994 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000995 KnownBits Known2;
996 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
997 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
998 Known.Zero &= Known2.Zero;
999 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001000 break;
1001 }
1002 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001003 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001004 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1005 switch (IntID) {
1006 default: return;
1007 case Intrinsic::aarch64_ldaxr:
1008 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001009 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001010 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001011 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001012 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001013 return;
1014 }
1015 }
1016 break;
1017 }
1018 case ISD::INTRINSIC_WO_CHAIN:
1019 case ISD::INTRINSIC_VOID: {
1020 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1021 switch (IntNo) {
1022 default:
1023 break;
1024 case Intrinsic::aarch64_neon_umaxv:
1025 case Intrinsic::aarch64_neon_uminv: {
1026 // Figure out the datatype of the vector operand. The UMINV instruction
1027 // will zero extend the result, so we can mark as known zero all the
1028 // bits larger than the element datatype. 32-bit or larget doesn't need
1029 // this as those are legal types and will be handled by isel directly.
1030 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001031 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001032 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1033 assert(BitWidth >= 8 && "Unexpected width!");
1034 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001035 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1037 assert(BitWidth >= 16 && "Unexpected width!");
1038 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001039 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001040 }
1041 break;
1042 } break;
1043 }
1044 }
1045 }
1046}
1047
Mehdi Aminieaabc512015-07-09 15:12:23 +00001048MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1049 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001050 return MVT::i64;
1051}
1052
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001053bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1054 unsigned AddrSpace,
1055 unsigned Align,
1056 bool *Fast) const {
1057 if (Subtarget->requiresStrictAlign())
1058 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001059
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001060 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001061 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1062 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001063 // See comments in performSTORECombine() for more details about
1064 // these conditions.
1065
1066 // Code that uses clang vector extensions can mark that it
1067 // wants unaligned accesses to be treated as fast by
1068 // underspecifying alignment to be 1 or 2.
1069 Align <= 2 ||
1070
1071 // Disregard v2i64. Memcpy lowering produces those and splitting
1072 // them regresses performance on micro-benchmarks and olden/bh.
1073 VT == MVT::v2i64;
1074 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001075 return true;
1076}
1077
Tim Northover3b0846e2014-05-24 12:50:23 +00001078FastISel *
1079AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1080 const TargetLibraryInfo *libInfo) const {
1081 return AArch64::createFastISel(funcInfo, libInfo);
1082}
1083
1084const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001085 switch ((AArch64ISD::NodeType)Opcode) {
1086 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001087 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1088 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001089 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001090 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1091 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1092 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1093 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1094 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1095 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1096 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1097 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1098 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1099 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001100 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001101 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1102 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1103 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1104 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1105 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1106 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1107 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001108 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1109 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1110 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001111 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001112 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1113 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1114 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1115 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1116 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1117 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1118 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1119 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1120 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1121 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1122 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1123 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1124 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1125 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1126 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1127 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1128 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1129 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1130 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1131 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1132 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1133 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1134 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1135 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1136 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1137 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1138 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1139 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1140 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1141 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1142 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1143 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1144 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1145 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1146 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1147 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1148 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1149 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1150 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1151 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1152 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1153 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1154 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1155 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1156 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1157 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1158 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1159 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001160 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1161 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1162 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1163 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1164 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1165 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001166 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1167 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1168 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1169 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1170 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1171 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1172 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001173 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001174 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1175 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001176 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001177 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1178 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1179 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1180 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1181 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1182 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1183 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1184 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1185 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1186 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1187 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1188 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1189 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1190 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1191 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1192 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1193 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1194 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1195 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1196 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1197 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1198 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1199 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1200 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1201 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1202 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1203 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1204 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1205 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001206 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1207 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001208 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001209 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1210 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1211 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001212 }
Matthias Braund04893f2015-05-07 21:33:59 +00001213 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001214}
1215
1216MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001217AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001218 MachineBasicBlock *MBB) const {
1219 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1220 // phi node:
1221
1222 // OrigBB:
1223 // [... previous instrs leading to comparison ...]
1224 // b.ne TrueBB
1225 // b EndBB
1226 // TrueBB:
1227 // ; Fallthrough
1228 // EndBB:
1229 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1230
Tim Northover3b0846e2014-05-24 12:50:23 +00001231 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001232 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001233 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001234 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001235 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001236
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001237 unsigned DestReg = MI.getOperand(0).getReg();
1238 unsigned IfTrueReg = MI.getOperand(1).getReg();
1239 unsigned IfFalseReg = MI.getOperand(2).getReg();
1240 unsigned CondCode = MI.getOperand(3).getImm();
1241 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001242
1243 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245 MF->insert(It, TrueBB);
1246 MF->insert(It, EndBB);
1247
1248 // Transfer rest of current basic-block to EndBB
1249 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1250 MBB->end());
1251 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1252
1253 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1254 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1255 MBB->addSuccessor(TrueBB);
1256 MBB->addSuccessor(EndBB);
1257
1258 // TrueBB falls through to the end.
1259 TrueBB->addSuccessor(EndBB);
1260
1261 if (!NZCVKilled) {
1262 TrueBB->addLiveIn(AArch64::NZCV);
1263 EndBB->addLiveIn(AArch64::NZCV);
1264 }
1265
1266 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1267 .addReg(IfTrueReg)
1268 .addMBB(TrueBB)
1269 .addReg(IfFalseReg)
1270 .addMBB(MBB);
1271
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001272 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001273 return EndBB;
1274}
1275
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001276MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1277 MachineInstr &MI, MachineBasicBlock *BB) const {
1278 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001279 default:
1280#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001281 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001282#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001283 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001284
1285 case AArch64::F128CSEL:
1286 return EmitF128CSEL(MI, BB);
1287
1288 case TargetOpcode::STACKMAP:
1289 case TargetOpcode::PATCHPOINT:
1290 return emitPatchPoint(MI, BB);
1291 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001292}
1293
1294//===----------------------------------------------------------------------===//
1295// AArch64 Lowering private implementation.
1296//===----------------------------------------------------------------------===//
1297
1298//===----------------------------------------------------------------------===//
1299// Lowering Code
1300//===----------------------------------------------------------------------===//
1301
1302/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1303/// CC
1304static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1305 switch (CC) {
1306 default:
1307 llvm_unreachable("Unknown condition code!");
1308 case ISD::SETNE:
1309 return AArch64CC::NE;
1310 case ISD::SETEQ:
1311 return AArch64CC::EQ;
1312 case ISD::SETGT:
1313 return AArch64CC::GT;
1314 case ISD::SETGE:
1315 return AArch64CC::GE;
1316 case ISD::SETLT:
1317 return AArch64CC::LT;
1318 case ISD::SETLE:
1319 return AArch64CC::LE;
1320 case ISD::SETUGT:
1321 return AArch64CC::HI;
1322 case ISD::SETUGE:
1323 return AArch64CC::HS;
1324 case ISD::SETULT:
1325 return AArch64CC::LO;
1326 case ISD::SETULE:
1327 return AArch64CC::LS;
1328 }
1329}
1330
1331/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1332static void changeFPCCToAArch64CC(ISD::CondCode CC,
1333 AArch64CC::CondCode &CondCode,
1334 AArch64CC::CondCode &CondCode2) {
1335 CondCode2 = AArch64CC::AL;
1336 switch (CC) {
1337 default:
1338 llvm_unreachable("Unknown FP condition!");
1339 case ISD::SETEQ:
1340 case ISD::SETOEQ:
1341 CondCode = AArch64CC::EQ;
1342 break;
1343 case ISD::SETGT:
1344 case ISD::SETOGT:
1345 CondCode = AArch64CC::GT;
1346 break;
1347 case ISD::SETGE:
1348 case ISD::SETOGE:
1349 CondCode = AArch64CC::GE;
1350 break;
1351 case ISD::SETOLT:
1352 CondCode = AArch64CC::MI;
1353 break;
1354 case ISD::SETOLE:
1355 CondCode = AArch64CC::LS;
1356 break;
1357 case ISD::SETONE:
1358 CondCode = AArch64CC::MI;
1359 CondCode2 = AArch64CC::GT;
1360 break;
1361 case ISD::SETO:
1362 CondCode = AArch64CC::VC;
1363 break;
1364 case ISD::SETUO:
1365 CondCode = AArch64CC::VS;
1366 break;
1367 case ISD::SETUEQ:
1368 CondCode = AArch64CC::EQ;
1369 CondCode2 = AArch64CC::VS;
1370 break;
1371 case ISD::SETUGT:
1372 CondCode = AArch64CC::HI;
1373 break;
1374 case ISD::SETUGE:
1375 CondCode = AArch64CC::PL;
1376 break;
1377 case ISD::SETLT:
1378 case ISD::SETULT:
1379 CondCode = AArch64CC::LT;
1380 break;
1381 case ISD::SETLE:
1382 case ISD::SETULE:
1383 CondCode = AArch64CC::LE;
1384 break;
1385 case ISD::SETNE:
1386 case ISD::SETUNE:
1387 CondCode = AArch64CC::NE;
1388 break;
1389 }
1390}
1391
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001392/// Convert a DAG fp condition code to an AArch64 CC.
1393/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1394/// should be AND'ed instead of OR'ed.
1395static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1396 AArch64CC::CondCode &CondCode,
1397 AArch64CC::CondCode &CondCode2) {
1398 CondCode2 = AArch64CC::AL;
1399 switch (CC) {
1400 default:
1401 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1402 assert(CondCode2 == AArch64CC::AL);
1403 break;
1404 case ISD::SETONE:
1405 // (a one b)
1406 // == ((a olt b) || (a ogt b))
1407 // == ((a ord b) && (a une b))
1408 CondCode = AArch64CC::VC;
1409 CondCode2 = AArch64CC::NE;
1410 break;
1411 case ISD::SETUEQ:
1412 // (a ueq b)
1413 // == ((a uno b) || (a oeq b))
1414 // == ((a ule b) && (a uge b))
1415 CondCode = AArch64CC::PL;
1416 CondCode2 = AArch64CC::LE;
1417 break;
1418 }
1419}
1420
Tim Northover3b0846e2014-05-24 12:50:23 +00001421/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1422/// CC usable with the vector instructions. Fewer operations are available
1423/// without a real NZCV register, so we have to use less efficient combinations
1424/// to get the same effect.
1425static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1426 AArch64CC::CondCode &CondCode,
1427 AArch64CC::CondCode &CondCode2,
1428 bool &Invert) {
1429 Invert = false;
1430 switch (CC) {
1431 default:
1432 // Mostly the scalar mappings work fine.
1433 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1434 break;
1435 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001436 Invert = true;
1437 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001438 case ISD::SETO:
1439 CondCode = AArch64CC::MI;
1440 CondCode2 = AArch64CC::GE;
1441 break;
1442 case ISD::SETUEQ:
1443 case ISD::SETULT:
1444 case ISD::SETULE:
1445 case ISD::SETUGT:
1446 case ISD::SETUGE:
1447 // All of the compare-mask comparisons are ordered, but we can switch
1448 // between the two by a double inversion. E.g. ULE == !OGT.
1449 Invert = true;
1450 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1451 break;
1452 }
1453}
1454
1455static bool isLegalArithImmed(uint64_t C) {
1456 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001457 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001458 LLVM_DEBUG(dbgs() << "Is imm " << C
1459 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001460 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001461}
1462
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001463// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1464// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1465// can be set differently by this operation. It comes down to whether
1466// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1467// everything is fine. If not then the optimization is wrong. Thus general
1468// comparisons are only valid if op2 != 0.
1469//
1470// So, finally, the only LLVM-native comparisons that don't mention C and V
1471// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1472// the absence of information about op2.
1473static bool isCMN(SDValue Op, ISD::CondCode CC) {
1474 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1475 (CC == ISD::SETEQ || CC == ISD::SETNE);
1476}
1477
Tim Northover3b0846e2014-05-24 12:50:23 +00001478static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001479 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001480 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001481 const bool FullFP16 =
1482 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001483
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001484 if (VT.isFloatingPoint()) {
1485 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001486 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001487 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1488 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001489 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001490 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001491 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001492 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001493
1494 // The CMP instruction is just an alias for SUBS, and representing it as
1495 // SUBS means that it's possible to get CSE with subtract operations.
1496 // A later phase can perform the optimization of setting the destination
1497 // register to WZR/XZR if it ends up being unused.
1498 unsigned Opcode = AArch64ISD::SUBS;
1499
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001500 if (isCMN(RHS, CC)) {
1501 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001502 Opcode = AArch64ISD::ADDS;
1503 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001504 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001505 !isUnsignedIntSetCC(CC)) {
1506 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1507 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1508 // of the signed comparisons.
1509 Opcode = AArch64ISD::ANDS;
1510 RHS = LHS.getOperand(1);
1511 LHS = LHS.getOperand(0);
1512 }
1513
Matthias Braunaf7d7702015-07-16 20:02:37 +00001514 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001515 .getValue(1);
1516}
1517
Matthias Braunaf7d7702015-07-16 20:02:37 +00001518/// \defgroup AArch64CCMP CMP;CCMP matching
1519///
1520/// These functions deal with the formation of CMP;CCMP;... sequences.
1521/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1522/// a comparison. They set the NZCV flags to a predefined value if their
1523/// predicate is false. This allows to express arbitrary conjunctions, for
1524/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1525/// expressed as:
1526/// cmp A
1527/// ccmp B, inv(CB), CA
1528/// check for CB flags
1529///
1530/// In general we can create code for arbitrary "... (and (and A B) C)"
1531/// sequences. We can also implement some "or" expressions, because "(or A B)"
1532/// is equivalent to "not (and (not A) (not B))" and we can implement some
1533/// negation operations:
1534/// We can negate the results of a single comparison by inverting the flags
1535/// used when the predicate fails and inverting the flags tested in the next
1536/// instruction; We can also negate the results of the whole previous
1537/// conditional compare sequence by inverting the flags tested in the next
1538/// instruction. However there is no way to negate the result of a partial
1539/// sequence.
1540///
1541/// Therefore on encountering an "or" expression we can negate the subtree on
1542/// one side and have to be able to push the negate to the leafs of the subtree
1543/// on the other side (see also the comments in code). As complete example:
1544/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1545/// (and (setCC (cmp C)) (setCD (cmp D)))"
1546/// is transformed to
1547/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1548/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1549/// and implemented as:
1550/// cmp C
1551/// ccmp D, inv(CD), CC
1552/// ccmp A, CA, inv(CD)
1553/// ccmp B, CB, inv(CA)
1554/// check for CB flags
1555/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1556/// by conditional compare sequences.
1557/// @{
1558
Geoff Berrye41c2df2015-07-20 22:03:52 +00001559/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001560static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1561 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001562 AArch64CC::CondCode Predicate,
1563 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001564 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001565 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001566 const bool FullFP16 =
1567 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1568
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001569 if (LHS.getValueType().isFloatingPoint()) {
1570 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001571 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001572 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1573 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1574 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001575 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001576 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001577 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001578 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001579 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1580 Opcode = AArch64ISD::CCMN;
1581 RHS = RHS.getOperand(1);
1582 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001583 }
1584 if (Opcode == 0)
1585 Opcode = AArch64ISD::CCMP;
1586
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001587 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1588 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1589 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001590 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1591 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1592}
1593
1594/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1595/// CanPushNegate is set to true if we can push a negate operation through
1596/// the tree in a was that we are left with AND operations and negate operations
1597/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1598/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1599/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001600static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001601 unsigned Depth = 0) {
1602 if (!Val.hasOneUse())
1603 return false;
1604 unsigned Opcode = Val->getOpcode();
1605 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001606 if (Val->getOperand(0).getValueType() == MVT::f128)
1607 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001608 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001609 return true;
1610 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001611 // Protect against exponential runtime and stack overflow.
1612 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001613 return false;
1614 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1615 SDValue O0 = Val->getOperand(0);
1616 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001617 bool CanNegateL;
1618 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001619 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001620 bool CanNegateR;
1621 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001622 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001623
1624 if (Opcode == ISD::OR) {
1625 // For an OR expression we need to be able to negate at least one side or
1626 // we cannot do the transformation at all.
1627 if (!CanNegateL && !CanNegateR)
1628 return false;
1629 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1630 // can negate the x and y subtrees.
1631 CanNegate = CanNegateL && CanNegateR;
1632 } else {
1633 // If the operands are OR expressions then we finally need to negate their
1634 // outputs, we can only do that for the operand with emitted last by
1635 // negating OutCC, not for both operands.
1636 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1637 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1638 if (NeedsNegOutL && NeedsNegOutR)
1639 return false;
1640 // We cannot negate an AND operation (it would become an OR),
1641 CanNegate = false;
1642 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001643 return true;
1644 }
1645 return false;
1646}
1647
1648/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1649/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1650/// Tries to transform the given i1 producing node @p Val to a series compare
1651/// and conditional compare operations. @returns an NZCV flags producing node
1652/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1653/// transformation was not possible.
1654/// On recursive invocations @p PushNegate may be set to true to have negation
1655/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1656/// for the comparisons in the current subtree; @p Depth limits the search
1657/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001658static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1659 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001660 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001661 // We're at a tree leaf, produce a conditional comparison operation.
1662 unsigned Opcode = Val->getOpcode();
1663 if (Opcode == ISD::SETCC) {
1664 SDValue LHS = Val->getOperand(0);
1665 SDValue RHS = Val->getOperand(1);
1666 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1667 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001668 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001669 CC = getSetCCInverse(CC, isInteger);
1670 SDLoc DL(Val);
1671 // Determine OutCC and handle FP special case.
1672 if (isInteger) {
1673 OutCC = changeIntCCToAArch64CC(CC);
1674 } else {
1675 assert(LHS.getValueType().isFloatingPoint());
1676 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001677 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1678 // Some floating point conditions can't be tested with a single condition
1679 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001680 if (ExtraCC != AArch64CC::AL) {
1681 SDValue ExtraCmp;
1682 if (!CCOp.getNode())
1683 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001684 else
1685 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001686 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001687 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001688 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001689 }
1690 }
1691
1692 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001693 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001694 return emitComparison(LHS, RHS, CC, DL, DAG);
1695 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001696 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001697 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001698 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001699 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1700 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001701
1702 // Check if both sides can be transformed.
1703 SDValue LHS = Val->getOperand(0);
1704 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001705
Matthias Braunfdef49b2016-01-23 04:05:22 +00001706 // In case of an OR we need to negate our operands and the result.
1707 // (A v B) <=> not(not(A) ^ not(B))
1708 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001709 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001710 // predicate flags giving us a free negation for one side. The other side
1711 // must be negatable by itself.
1712 if (NegateOpsAndResult) {
1713 // See which side we can negate.
1714 bool CanNegateL;
1715 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1716 assert(isValidL && "Valid conjunction/disjunction tree");
1717 (void)isValidL;
1718
1719#ifndef NDEBUG
1720 bool CanNegateR;
1721 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1722 assert(isValidR && "Valid conjunction/disjunction tree");
1723 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1724#endif
1725
1726 // Order the side which we cannot negate to RHS so we can emit it first.
1727 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001728 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001729 } else {
1730 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001731 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001732 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001733 // Order the side where we need to negate the output flags to RHS so it
1734 // gets emitted first.
1735 if (NeedsNegOutL)
1736 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001737 }
1738
1739 // Emit RHS. If we want to negate the tree we only need to push a negate
1740 // through if we are already in a PushNegate case, otherwise we can negate
1741 // the "flags to test" afterwards.
1742 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001743 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001744 CCOp, Predicate);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001745 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001746 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001747 // Emit LHS. We may need to negate it.
1748 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1749 NegateOpsAndResult, CmpR,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001750 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001751 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001752 // (or absorb the Negate parameter).
1753 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001754 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1755 return CmpL;
1756}
1757
Matthias Braunfdef49b2016-01-23 04:05:22 +00001758/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1759/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1760/// \see emitConjunctionDisjunctionTreeRec().
1761static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001762 AArch64CC::CondCode &OutCC) {
Matthias Braunfdef49b2016-01-23 04:05:22 +00001763 bool CanNegate;
1764 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1765 return SDValue();
1766
1767 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001768 AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001769}
1770
Matthias Braunaf7d7702015-07-16 20:02:37 +00001771/// @}
1772
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001773/// Returns how profitable it is to fold a comparison's operand's shift and/or
1774/// extension operations.
1775static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1776 auto isSupportedExtend = [&](SDValue V) {
1777 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1778 return true;
1779
1780 if (V.getOpcode() == ISD::AND)
1781 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1782 uint64_t Mask = MaskCst->getZExtValue();
1783 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1784 }
1785
1786 return false;
1787 };
1788
1789 if (!Op.hasOneUse())
1790 return 0;
1791
1792 if (isSupportedExtend(Op))
1793 return 1;
1794
1795 unsigned Opc = Op.getOpcode();
1796 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1797 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1798 uint64_t Shift = ShiftCst->getZExtValue();
1799 if (isSupportedExtend(Op.getOperand(0)))
1800 return (Shift <= 4) ? 2 : 1;
1801 EVT VT = Op.getValueType();
1802 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1803 return 1;
1804 }
1805
1806 return 0;
1807}
1808
Tim Northover3b0846e2014-05-24 12:50:23 +00001809static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001810 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001811 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001812 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1813 EVT VT = RHS.getValueType();
1814 uint64_t C = RHSC->getZExtValue();
1815 if (!isLegalArithImmed(C)) {
1816 // Constant does not fit, try adjusting it by one?
1817 switch (CC) {
1818 default:
1819 break;
1820 case ISD::SETLT:
1821 case ISD::SETGE:
1822 if ((VT == MVT::i32 && C != 0x80000000 &&
1823 isLegalArithImmed((uint32_t)(C - 1))) ||
1824 (VT == MVT::i64 && C != 0x80000000ULL &&
1825 isLegalArithImmed(C - 1ULL))) {
1826 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1827 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001828 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001829 }
1830 break;
1831 case ISD::SETULT:
1832 case ISD::SETUGE:
1833 if ((VT == MVT::i32 && C != 0 &&
1834 isLegalArithImmed((uint32_t)(C - 1))) ||
1835 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1836 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1837 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001838 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001839 }
1840 break;
1841 case ISD::SETLE:
1842 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001843 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001844 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001845 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001846 isLegalArithImmed(C + 1ULL))) {
1847 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1848 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001849 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001850 }
1851 break;
1852 case ISD::SETULE:
1853 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001854 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001855 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001856 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001857 isLegalArithImmed(C + 1ULL))) {
1858 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1859 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001860 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001861 }
1862 break;
1863 }
1864 }
1865 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001866
1867 // Comparisons are canonicalized so that the RHS operand is simpler than the
1868 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1869 // can fold some shift+extend operations on the RHS operand, so swap the
1870 // operands if that can be done.
1871 //
1872 // For example:
1873 // lsl w13, w11, #1
1874 // cmp w13, w12
1875 // can be turned into:
1876 // cmp w12, w11, lsl #1
1877 if (!isa<ConstantSDNode>(RHS) ||
1878 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1879 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1880
1881 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1882 std::swap(LHS, RHS);
1883 CC = ISD::getSetCCSwappedOperands(CC);
1884 }
1885 }
1886
Matthias Braunaf7d7702015-07-16 20:02:37 +00001887 SDValue Cmp;
1888 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001889 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001890 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1891
1892 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1893 // For the i8 operand, the largest immediate is 255, so this can be easily
1894 // encoded in the compare instruction. For the i16 operand, however, the
1895 // largest immediate cannot be encoded in the compare.
1896 // Therefore, use a sign extending load and cmn to avoid materializing the
1897 // -1 constant. For example,
1898 // movz w1, #65535
1899 // ldrh w0, [x0, #0]
1900 // cmp w0, w1
1901 // >
1902 // ldrsh w0, [x0, #0]
1903 // cmn w0, #1
1904 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1905 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001906 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001907 // transformation is profitable.
1908 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1909 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1910 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1911 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1912 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1913 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1914 SDValue SExt =
1915 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1916 DAG.getValueType(MVT::i16));
1917 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1918 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001919 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001920 AArch64CC = changeIntCCToAArch64CC(CC);
1921 }
1922 }
1923
1924 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001925 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001926 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1927 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001928 }
1929 }
1930 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001931
1932 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001933 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001934 AArch64CC = changeIntCCToAArch64CC(CC);
1935 }
1936 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001937 return Cmp;
1938}
1939
1940static std::pair<SDValue, SDValue>
1941getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1942 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1943 "Unsupported value type");
1944 SDValue Value, Overflow;
1945 SDLoc DL(Op);
1946 SDValue LHS = Op.getOperand(0);
1947 SDValue RHS = Op.getOperand(1);
1948 unsigned Opc = 0;
1949 switch (Op.getOpcode()) {
1950 default:
1951 llvm_unreachable("Unknown overflow instruction!");
1952 case ISD::SADDO:
1953 Opc = AArch64ISD::ADDS;
1954 CC = AArch64CC::VS;
1955 break;
1956 case ISD::UADDO:
1957 Opc = AArch64ISD::ADDS;
1958 CC = AArch64CC::HS;
1959 break;
1960 case ISD::SSUBO:
1961 Opc = AArch64ISD::SUBS;
1962 CC = AArch64CC::VS;
1963 break;
1964 case ISD::USUBO:
1965 Opc = AArch64ISD::SUBS;
1966 CC = AArch64CC::LO;
1967 break;
1968 // Multiply needs a little bit extra work.
1969 case ISD::SMULO:
1970 case ISD::UMULO: {
1971 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001972 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001973 if (Op.getValueType() == MVT::i32) {
1974 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1975 // For a 32 bit multiply with overflow check we want the instruction
1976 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1977 // need to generate the following pattern:
1978 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1979 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1980 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1981 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1982 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001983 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001984 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1985 // operation. We need to clear out the upper 32 bits, because we used a
1986 // widening multiply that wrote all 64 bits. In the end this should be a
1987 // noop.
1988 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1989 if (IsSigned) {
1990 // The signed overflow check requires more than just a simple check for
1991 // any bit set in the upper 32 bits of the result. These bits could be
1992 // just the sign bits of a negative number. To perform the overflow
1993 // check we have to arithmetic shift right the 32nd bit of the result by
1994 // 31 bits. Then we compare the result to the upper 32 bits.
1995 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001996 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001997 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1998 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001999 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002000 // It is important that LowerBits is last, otherwise the arithmetic
2001 // shift will not be folded into the compare (SUBS).
2002 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2003 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2004 .getValue(1);
2005 } else {
2006 // The overflow check for unsigned multiply is easy. We only need to
2007 // check if any of the upper 32 bits are set. This can be done with a
2008 // CMP (shifted register). For that we need to generate the following
2009 // pattern:
2010 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2011 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002012 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002013 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2014 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002015 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2016 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002017 UpperBits).getValue(1);
2018 }
2019 break;
2020 }
2021 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2022 // For the 64 bit multiply
2023 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2024 if (IsSigned) {
2025 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2026 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002027 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002028 // It is important that LowerBits is last, otherwise the arithmetic
2029 // shift will not be folded into the compare (SUBS).
2030 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2031 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2032 .getValue(1);
2033 } else {
2034 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2035 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2036 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002037 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2038 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002039 UpperBits).getValue(1);
2040 }
2041 break;
2042 }
2043 } // switch (...)
2044
2045 if (Opc) {
2046 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2047
2048 // Emit the AArch64 operation with overflow check.
2049 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2050 Overflow = Value.getValue(1);
2051 }
2052 return std::make_pair(Value, Overflow);
2053}
2054
2055SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2056 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002057 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002058 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002059}
2060
Amara Emerson24ca39c2017-10-09 15:15:09 +00002061// Returns true if the given Op is the overflow flag result of an overflow
2062// intrinsic operation.
2063static bool isOverflowIntrOpRes(SDValue Op) {
2064 unsigned Opc = Op.getOpcode();
2065 return (Op.getResNo() == 1 &&
2066 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2067 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2068}
2069
Tim Northover3b0846e2014-05-24 12:50:23 +00002070static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2071 SDValue Sel = Op.getOperand(0);
2072 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002073 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002074
Amara Emerson24ca39c2017-10-09 15:15:09 +00002075 // If the operand is an overflow checking operation, invert the condition
2076 // code and kill the Not operation. I.e., transform:
2077 // (xor (overflow_op_bool, 1))
2078 // -->
2079 // (csel 1, 0, invert(cc), overflow_op_bool)
2080 // ... which later gets transformed to just a cset instruction with an
2081 // inverted condition code, rather than a cset + eor sequence.
2082 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2083 // Only lower legal XALUO ops.
2084 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2085 return SDValue();
2086
2087 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2088 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2089 AArch64CC::CondCode CC;
2090 SDValue Value, Overflow;
2091 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2092 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2093 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2094 CCVal, Overflow);
2095 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002096 // If neither operand is a SELECT_CC, give up.
2097 if (Sel.getOpcode() != ISD::SELECT_CC)
2098 std::swap(Sel, Other);
2099 if (Sel.getOpcode() != ISD::SELECT_CC)
2100 return Op;
2101
2102 // The folding we want to perform is:
2103 // (xor x, (select_cc a, b, cc, 0, -1) )
2104 // -->
2105 // (csel x, (xor x, -1), cc ...)
2106 //
2107 // The latter will get matched to a CSINV instruction.
2108
2109 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2110 SDValue LHS = Sel.getOperand(0);
2111 SDValue RHS = Sel.getOperand(1);
2112 SDValue TVal = Sel.getOperand(2);
2113 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002114
2115 // FIXME: This could be generalized to non-integer comparisons.
2116 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2117 return Op;
2118
2119 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2120 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2121
Eric Christopher572e03a2015-06-19 01:53:21 +00002122 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002123 if (!CFVal || !CTVal)
2124 return Op;
2125
2126 // We can commute the SELECT_CC by inverting the condition. This
2127 // might be needed to make this fit into a CSINV pattern.
2128 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2129 std::swap(TVal, FVal);
2130 std::swap(CTVal, CFVal);
2131 CC = ISD::getSetCCInverse(CC, true);
2132 }
2133
2134 // If the constants line up, perform the transform!
2135 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2136 SDValue CCVal;
2137 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2138
2139 FVal = Other;
2140 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002141 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002142
2143 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2144 CCVal, Cmp);
2145 }
2146
2147 return Op;
2148}
2149
2150static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2151 EVT VT = Op.getValueType();
2152
2153 // Let legalize expand this if it isn't a legal type yet.
2154 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2155 return SDValue();
2156
2157 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2158
2159 unsigned Opc;
2160 bool ExtraOp = false;
2161 switch (Op.getOpcode()) {
2162 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002163 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002164 case ISD::ADDC:
2165 Opc = AArch64ISD::ADDS;
2166 break;
2167 case ISD::SUBC:
2168 Opc = AArch64ISD::SUBS;
2169 break;
2170 case ISD::ADDE:
2171 Opc = AArch64ISD::ADCS;
2172 ExtraOp = true;
2173 break;
2174 case ISD::SUBE:
2175 Opc = AArch64ISD::SBCS;
2176 ExtraOp = true;
2177 break;
2178 }
2179
2180 if (!ExtraOp)
2181 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2182 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2183 Op.getOperand(2));
2184}
2185
2186static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2187 // Let legalize expand this if it isn't a legal type yet.
2188 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2189 return SDValue();
2190
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002191 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002192 AArch64CC::CondCode CC;
2193 // The actual operation that sets the overflow or carry flag.
2194 SDValue Value, Overflow;
2195 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2196
2197 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002198 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2199 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002200
2201 // We use an inverted condition, because the conditional select is inverted
2202 // too. This will allow it to be selected to a single instruction:
2203 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002204 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2205 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002206 CCVal, Overflow);
2207
2208 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002209 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002210}
2211
2212// Prefetch operands are:
2213// 1: Address to prefetch
2214// 2: bool isWrite
2215// 3: int locality (0 = no locality ... 3 = extreme locality)
2216// 4: bool isDataCache
2217static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2218 SDLoc DL(Op);
2219 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2220 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002221 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002222
2223 bool IsStream = !Locality;
2224 // When the locality number is set
2225 if (Locality) {
2226 // The front-end should have filtered out the out-of-range values
2227 assert(Locality <= 3 && "Prefetch locality out-of-range");
2228 // The locality degree is the opposite of the cache speed.
2229 // Put the number the other way around.
2230 // The encoding starts at 0 for level 1
2231 Locality = 3 - Locality;
2232 }
2233
2234 // built the mask value encoding the expected behavior.
2235 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002236 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002237 (Locality << 1) | // Cache level bits
2238 (unsigned)IsStream; // Stream bit
2239 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002240 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002241}
2242
2243SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2244 SelectionDAG &DAG) const {
2245 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2246
2247 RTLIB::Libcall LC;
2248 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2249
2250 return LowerF128Call(Op, DAG, LC);
2251}
2252
2253SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2254 SelectionDAG &DAG) const {
2255 if (Op.getOperand(0).getValueType() != MVT::f128) {
2256 // It's legal except when f128 is involved
2257 return Op;
2258 }
2259
2260 RTLIB::Libcall LC;
2261 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2262
2263 // FP_ROUND node has a second operand indicating whether it is known to be
2264 // precise. That doesn't take part in the LibCall so we can't directly use
2265 // LowerF128Call.
2266 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002267 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2268 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002269}
2270
2271static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2272 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2273 // Any additional optimization in this function should be recorded
2274 // in the cost tables.
2275 EVT InVT = Op.getOperand(0).getValueType();
2276 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002277 unsigned NumElts = InVT.getVectorNumElements();
2278
2279 // f16 vectors are promoted to f32 before a conversion.
2280 if (InVT.getVectorElementType() == MVT::f16) {
2281 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2282 SDLoc dl(Op);
2283 return DAG.getNode(
2284 Op.getOpcode(), dl, Op.getValueType(),
2285 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2286 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002287
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002288 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002289 SDLoc dl(Op);
2290 SDValue Cv =
2291 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2292 Op.getOperand(0));
2293 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002294 }
2295
2296 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002297 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002298 MVT ExtVT =
2299 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2300 VT.getVectorNumElements());
2301 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002302 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2303 }
2304
2305 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002306 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002307}
2308
2309SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2310 SelectionDAG &DAG) const {
2311 if (Op.getOperand(0).getValueType().isVector())
2312 return LowerVectorFP_TO_INT(Op, DAG);
2313
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002314 // f16 conversions are promoted to f32 when full fp16 is not supported.
2315 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2316 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002317 SDLoc dl(Op);
2318 return DAG.getNode(
2319 Op.getOpcode(), dl, Op.getValueType(),
2320 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2321 }
2322
Tim Northover3b0846e2014-05-24 12:50:23 +00002323 if (Op.getOperand(0).getValueType() != MVT::f128) {
2324 // It's legal except when f128 is involved
2325 return Op;
2326 }
2327
2328 RTLIB::Libcall LC;
2329 if (Op.getOpcode() == ISD::FP_TO_SINT)
2330 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2331 else
2332 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2333
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002334 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002335 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002336}
2337
2338static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2339 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2340 // Any additional optimization in this function should be recorded
2341 // in the cost tables.
2342 EVT VT = Op.getValueType();
2343 SDLoc dl(Op);
2344 SDValue In = Op.getOperand(0);
2345 EVT InVT = In.getValueType();
2346
Tim Northoveref0d7602014-06-15 09:27:06 +00002347 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2348 MVT CastVT =
2349 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2350 InVT.getVectorNumElements());
2351 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002352 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002353 }
2354
Tim Northoveref0d7602014-06-15 09:27:06 +00002355 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2356 unsigned CastOpc =
2357 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2358 EVT CastVT = VT.changeVectorElementTypeToInteger();
2359 In = DAG.getNode(CastOpc, dl, CastVT, In);
2360 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002361 }
2362
Tim Northoveref0d7602014-06-15 09:27:06 +00002363 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002364}
2365
2366SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2367 SelectionDAG &DAG) const {
2368 if (Op.getValueType().isVector())
2369 return LowerVectorINT_TO_FP(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.getValueType() == MVT::f16 &&
2373 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002374 SDLoc dl(Op);
2375 return DAG.getNode(
2376 ISD::FP_ROUND, dl, MVT::f16,
2377 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002378 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002379 }
2380
Tim Northover3b0846e2014-05-24 12:50:23 +00002381 // i128 conversions are libcalls.
2382 if (Op.getOperand(0).getValueType() == MVT::i128)
2383 return SDValue();
2384
2385 // Other conversions are legal, unless it's to the completely software-based
2386 // fp128.
2387 if (Op.getValueType() != MVT::f128)
2388 return Op;
2389
2390 RTLIB::Libcall LC;
2391 if (Op.getOpcode() == ISD::SINT_TO_FP)
2392 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2393 else
2394 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2395
2396 return LowerF128Call(Op, DAG, LC);
2397}
2398
2399SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2400 SelectionDAG &DAG) const {
2401 // For iOS, we want to call an alternative entry point: __sincos_stret,
2402 // which returns the values in two S / D registers.
2403 SDLoc dl(Op);
2404 SDValue Arg = Op.getOperand(0);
2405 EVT ArgVT = Arg.getValueType();
2406 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2407
2408 ArgListTy Args;
2409 ArgListEntry Entry;
2410
2411 Entry.Node = Arg;
2412 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002413 Entry.IsSExt = false;
2414 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002415 Args.push_back(Entry);
2416
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002417 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2418 : RTLIB::SINCOS_STRET_F32;
2419 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002420 SDValue Callee =
2421 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002422
Serge Gueltone38003f2017-05-09 19:31:13 +00002423 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002424 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002425 CLI.setDebugLoc(dl)
2426 .setChain(DAG.getEntryNode())
2427 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002428
2429 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2430 return CallResult.first;
2431}
2432
Tim Northoverf8bfe212014-07-18 13:07:05 +00002433static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2434 if (Op.getValueType() != MVT::f16)
2435 return SDValue();
2436
2437 assert(Op.getOperand(0).getValueType() == MVT::i16);
2438 SDLoc DL(Op);
2439
2440 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2441 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2442 return SDValue(
2443 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002444 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002445 0);
2446}
2447
Chad Rosierd9d0f862014-10-08 02:31:24 +00002448static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2449 if (OrigVT.getSizeInBits() >= 64)
2450 return OrigVT;
2451
2452 assert(OrigVT.isSimple() && "Expecting a simple value type");
2453
2454 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2455 switch (OrigSimpleTy) {
2456 default: llvm_unreachable("Unexpected Vector Type");
2457 case MVT::v2i8:
2458 case MVT::v2i16:
2459 return MVT::v2i32;
2460 case MVT::v4i8:
2461 return MVT::v4i16;
2462 }
2463}
2464
2465static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2466 const EVT &OrigTy,
2467 const EVT &ExtTy,
2468 unsigned ExtOpcode) {
2469 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2470 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2471 // 64-bits we need to insert a new extension so that it will be 64-bits.
2472 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2473 if (OrigTy.getSizeInBits() >= 64)
2474 return N;
2475
2476 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2477 EVT NewVT = getExtensionTo64Bits(OrigTy);
2478
2479 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2480}
2481
2482static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2483 bool isSigned) {
2484 EVT VT = N->getValueType(0);
2485
2486 if (N->getOpcode() != ISD::BUILD_VECTOR)
2487 return false;
2488
Pete Cooper3af9a252015-06-26 18:17:36 +00002489 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002491 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002492 unsigned HalfSize = EltSize / 2;
2493 if (isSigned) {
2494 if (!isIntN(HalfSize, C->getSExtValue()))
2495 return false;
2496 } else {
2497 if (!isUIntN(HalfSize, C->getZExtValue()))
2498 return false;
2499 }
2500 continue;
2501 }
2502 return false;
2503 }
2504
2505 return true;
2506}
2507
2508static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2509 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2510 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2511 N->getOperand(0)->getValueType(0),
2512 N->getValueType(0),
2513 N->getOpcode());
2514
2515 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2516 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002517 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002518 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002519 unsigned NumElts = VT.getVectorNumElements();
2520 MVT TruncVT = MVT::getIntegerVT(EltSize);
2521 SmallVector<SDValue, 8> Ops;
2522 for (unsigned i = 0; i != NumElts; ++i) {
2523 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2524 const APInt &CInt = C->getAPIntValue();
2525 // Element types smaller than 32 bits are not legal, so use i32 elements.
2526 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002527 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002528 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002529 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002530}
2531
2532static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002533 return N->getOpcode() == ISD::SIGN_EXTEND ||
2534 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002535}
2536
2537static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002538 return N->getOpcode() == ISD::ZERO_EXTEND ||
2539 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002540}
2541
2542static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2543 unsigned Opcode = N->getOpcode();
2544 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2545 SDNode *N0 = N->getOperand(0).getNode();
2546 SDNode *N1 = N->getOperand(1).getNode();
2547 return N0->hasOneUse() && N1->hasOneUse() &&
2548 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2549 }
2550 return false;
2551}
2552
2553static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2554 unsigned Opcode = N->getOpcode();
2555 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2556 SDNode *N0 = N->getOperand(0).getNode();
2557 SDNode *N1 = N->getOperand(1).getNode();
2558 return N0->hasOneUse() && N1->hasOneUse() &&
2559 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2560 }
2561 return false;
2562}
2563
Tim Northover70666e72018-06-20 12:09:01 +00002564SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2565 SelectionDAG &DAG) const {
2566 // The rounding mode is in bits 23:22 of the FPSCR.
2567 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2568 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2569 // so that the shift + and get folded into a bitfield extract.
2570 SDLoc dl(Op);
2571
2572 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2573 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2574 MVT::i64));
2575 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2576 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2577 DAG.getConstant(1U << 22, dl, MVT::i32));
2578 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2579 DAG.getConstant(22, dl, MVT::i32));
2580 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2581 DAG.getConstant(3, dl, MVT::i32));
2582}
2583
Chad Rosierd9d0f862014-10-08 02:31:24 +00002584static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2585 // Multiplications are only custom-lowered for 128-bit vectors so that
2586 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2587 EVT VT = Op.getValueType();
2588 assert(VT.is128BitVector() && VT.isInteger() &&
2589 "unexpected type for custom-lowering ISD::MUL");
2590 SDNode *N0 = Op.getOperand(0).getNode();
2591 SDNode *N1 = Op.getOperand(1).getNode();
2592 unsigned NewOpc = 0;
2593 bool isMLA = false;
2594 bool isN0SExt = isSignExtended(N0, DAG);
2595 bool isN1SExt = isSignExtended(N1, DAG);
2596 if (isN0SExt && isN1SExt)
2597 NewOpc = AArch64ISD::SMULL;
2598 else {
2599 bool isN0ZExt = isZeroExtended(N0, DAG);
2600 bool isN1ZExt = isZeroExtended(N1, DAG);
2601 if (isN0ZExt && isN1ZExt)
2602 NewOpc = AArch64ISD::UMULL;
2603 else if (isN1SExt || isN1ZExt) {
2604 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2605 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2606 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2607 NewOpc = AArch64ISD::SMULL;
2608 isMLA = true;
2609 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2610 NewOpc = AArch64ISD::UMULL;
2611 isMLA = true;
2612 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2613 std::swap(N0, N1);
2614 NewOpc = AArch64ISD::UMULL;
2615 isMLA = true;
2616 }
2617 }
2618
2619 if (!NewOpc) {
2620 if (VT == MVT::v2i64)
2621 // Fall through to expand this. It is not legal.
2622 return SDValue();
2623 else
2624 // Other vector multiplications are legal.
2625 return Op;
2626 }
2627 }
2628
2629 // Legalize to a S/UMULL instruction
2630 SDLoc DL(Op);
2631 SDValue Op0;
2632 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2633 if (!isMLA) {
2634 Op0 = skipExtensionForVectorMULL(N0, DAG);
2635 assert(Op0.getValueType().is64BitVector() &&
2636 Op1.getValueType().is64BitVector() &&
2637 "unexpected types for extended operands to VMULL");
2638 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2639 }
2640 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2641 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2642 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2643 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2644 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2645 EVT Op1VT = Op1.getValueType();
2646 return DAG.getNode(N0->getOpcode(), DL, VT,
2647 DAG.getNode(NewOpc, DL, VT,
2648 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2649 DAG.getNode(NewOpc, DL, VT,
2650 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2651}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002652
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +00002653// Lower vector multiply high (ISD::MULHS and ISD::MULHU).
2654static SDValue LowerMULH(SDValue Op, SelectionDAG &DAG) {
2655 // Multiplications are only custom-lowered for 128-bit vectors so that
2656 // {S,U}MULL{2} can be detected. Otherwise v2i64 multiplications are not
2657 // legal.
2658 EVT VT = Op.getValueType();
2659 assert(VT.is128BitVector() && VT.isInteger() &&
2660 "unexpected type for custom-lowering ISD::MULH{U,S}");
2661
2662 SDValue V0 = Op.getOperand(0);
2663 SDValue V1 = Op.getOperand(1);
2664
2665 SDLoc DL(Op);
2666
2667 EVT ExtractVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
2668
2669 // We turn (V0 mulhs/mulhu V1) to:
2670 //
2671 // (uzp2 (smull (extract_subvector (ExtractVT V128:V0, (i64 0)),
2672 // (extract_subvector (ExtractVT V128:V1, (i64 0))))),
2673 // (smull (extract_subvector (ExtractVT V128:V0, (i64 VMull2Idx)),
2674 // (extract_subvector (ExtractVT V128:V2, (i64 VMull2Idx))))))
2675 //
2676 // Where ExtractVT is a subvector with half number of elements, and
2677 // VMullIdx2 is the index of the middle element (the high part).
2678 //
2679 // The vector hight part extract and multiply will be matched against
2680 // {S,U}MULL{v16i8_v8i16,v8i16_v4i32,v4i32_v2i64} which in turn will
2681 // issue a {s}mull2 instruction.
2682 //
2683 // This basically multiply the lower subvector with '{s,u}mull', the high
2684 // subvector with '{s,u}mull2', and shuffle both results high part in
2685 // resulting vector.
2686 unsigned Mull2VectorIdx = VT.getVectorNumElements () / 2;
2687 SDValue VMullIdx = DAG.getConstant(0, DL, MVT::i64);
2688 SDValue VMull2Idx = DAG.getConstant(Mull2VectorIdx, DL, MVT::i64);
2689
2690 SDValue VMullV0 =
2691 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMullIdx);
2692 SDValue VMullV1 =
2693 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMullIdx);
2694
2695 SDValue VMull2V0 =
2696 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMull2Idx);
2697 SDValue VMull2V1 =
2698 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMull2Idx);
2699
2700 unsigned MullOpc = Op.getOpcode() == ISD::MULHS ? AArch64ISD::SMULL
2701 : AArch64ISD::UMULL;
2702
2703 EVT MullVT = ExtractVT.widenIntegerVectorElementType(*DAG.getContext());
2704 SDValue Mull = DAG.getNode(MullOpc, DL, MullVT, VMullV0, VMullV1);
2705 SDValue Mull2 = DAG.getNode(MullOpc, DL, MullVT, VMull2V0, VMull2V1);
2706
2707 Mull = DAG.getNode(ISD::BITCAST, DL, VT, Mull);
2708 Mull2 = DAG.getNode(ISD::BITCAST, DL, VT, Mull2);
2709
2710 return DAG.getNode(AArch64ISD::UZP2, DL, VT, Mull, Mull2);
2711}
2712
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002713SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2714 SelectionDAG &DAG) const {
2715 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2716 SDLoc dl(Op);
2717 switch (IntNo) {
2718 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002719 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002720 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2722 }
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +00002723 case Intrinsic::aarch64_neon_abs:
2724 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2725 Op.getOperand(1));
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002726 case Intrinsic::aarch64_neon_smax:
2727 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2728 Op.getOperand(1), Op.getOperand(2));
2729 case Intrinsic::aarch64_neon_umax:
2730 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2731 Op.getOperand(1), Op.getOperand(2));
2732 case Intrinsic::aarch64_neon_smin:
2733 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2734 Op.getOperand(1), Op.getOperand(2));
2735 case Intrinsic::aarch64_neon_umin:
2736 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2737 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002738 }
2739}
2740
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002741// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2742static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2743 EVT VT, EVT MemVT,
2744 SelectionDAG &DAG) {
2745 assert(VT.isVector() && "VT should be a vector type");
2746 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2747
2748 SDValue Value = ST->getValue();
2749
2750 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2751 // the word lane which represent the v4i8 subvector. It optimizes the store
2752 // to:
2753 //
2754 // xtn v0.8b, v0.8h
2755 // str s0, [x0]
2756
2757 SDValue Undef = DAG.getUNDEF(MVT::i16);
2758 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2759 {Undef, Undef, Undef, Undef});
2760
2761 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2762 Value, UndefVec);
2763 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2764
2765 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2766 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2767 Trunc, DAG.getConstant(0, DL, MVT::i64));
2768
2769 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2770 ST->getBasePtr(), ST->getMemOperand());
2771}
2772
2773// Custom lowering for any store, vector or scalar and/or default or with
2774// a truncate operations. Currently only custom lower truncate operation
2775// from vector v4i16 to v4i8.
2776SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2777 SelectionDAG &DAG) const {
2778 SDLoc Dl(Op);
2779 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2780 assert (StoreNode && "Can only custom lower store nodes");
2781
2782 SDValue Value = StoreNode->getValue();
2783
2784 EVT VT = Value.getValueType();
2785 EVT MemVT = StoreNode->getMemoryVT();
2786
2787 assert (VT.isVector() && "Can only custom lower vector store types");
2788
2789 unsigned AS = StoreNode->getAddressSpace();
2790 unsigned Align = StoreNode->getAlignment();
2791 if (Align < MemVT.getStoreSize() &&
2792 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2793 return scalarizeVectorStore(StoreNode, DAG);
2794 }
2795
2796 if (StoreNode->isTruncatingStore()) {
2797 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2798 }
2799
2800 return SDValue();
2801}
2802
Tim Northover3b0846e2014-05-24 12:50:23 +00002803SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2804 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002805 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2806 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002807
Tim Northover3b0846e2014-05-24 12:50:23 +00002808 switch (Op.getOpcode()) {
2809 default:
2810 llvm_unreachable("unimplemented operand");
2811 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002812 case ISD::BITCAST:
2813 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002814 case ISD::GlobalAddress:
2815 return LowerGlobalAddress(Op, DAG);
2816 case ISD::GlobalTLSAddress:
2817 return LowerGlobalTLSAddress(Op, DAG);
2818 case ISD::SETCC:
2819 return LowerSETCC(Op, DAG);
2820 case ISD::BR_CC:
2821 return LowerBR_CC(Op, DAG);
2822 case ISD::SELECT:
2823 return LowerSELECT(Op, DAG);
2824 case ISD::SELECT_CC:
2825 return LowerSELECT_CC(Op, DAG);
2826 case ISD::JumpTable:
2827 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002828 case ISD::BR_JT:
2829 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002830 case ISD::ConstantPool:
2831 return LowerConstantPool(Op, DAG);
2832 case ISD::BlockAddress:
2833 return LowerBlockAddress(Op, DAG);
2834 case ISD::VASTART:
2835 return LowerVASTART(Op, DAG);
2836 case ISD::VACOPY:
2837 return LowerVACOPY(Op, DAG);
2838 case ISD::VAARG:
2839 return LowerVAARG(Op, DAG);
2840 case ISD::ADDC:
2841 case ISD::ADDE:
2842 case ISD::SUBC:
2843 case ISD::SUBE:
2844 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2845 case ISD::SADDO:
2846 case ISD::UADDO:
2847 case ISD::SSUBO:
2848 case ISD::USUBO:
2849 case ISD::SMULO:
2850 case ISD::UMULO:
2851 return LowerXALUO(Op, DAG);
2852 case ISD::FADD:
2853 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2854 case ISD::FSUB:
2855 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2856 case ISD::FMUL:
2857 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2858 case ISD::FDIV:
2859 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2860 case ISD::FP_ROUND:
2861 return LowerFP_ROUND(Op, DAG);
2862 case ISD::FP_EXTEND:
2863 return LowerFP_EXTEND(Op, DAG);
2864 case ISD::FRAMEADDR:
2865 return LowerFRAMEADDR(Op, DAG);
2866 case ISD::RETURNADDR:
2867 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002868 case ISD::ADDROFRETURNADDR:
2869 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002870 case ISD::INSERT_VECTOR_ELT:
2871 return LowerINSERT_VECTOR_ELT(Op, DAG);
2872 case ISD::EXTRACT_VECTOR_ELT:
2873 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2874 case ISD::BUILD_VECTOR:
2875 return LowerBUILD_VECTOR(Op, DAG);
2876 case ISD::VECTOR_SHUFFLE:
2877 return LowerVECTOR_SHUFFLE(Op, DAG);
2878 case ISD::EXTRACT_SUBVECTOR:
2879 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2880 case ISD::SRA:
2881 case ISD::SRL:
2882 case ISD::SHL:
2883 return LowerVectorSRA_SRL_SHL(Op, DAG);
2884 case ISD::SHL_PARTS:
2885 return LowerShiftLeftParts(Op, DAG);
2886 case ISD::SRL_PARTS:
2887 case ISD::SRA_PARTS:
2888 return LowerShiftRightParts(Op, DAG);
2889 case ISD::CTPOP:
2890 return LowerCTPOP(Op, DAG);
2891 case ISD::FCOPYSIGN:
2892 return LowerFCOPYSIGN(Op, DAG);
2893 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002894 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002895 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002896 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002897 case ISD::XOR:
2898 return LowerXOR(Op, DAG);
2899 case ISD::PREFETCH:
2900 return LowerPREFETCH(Op, DAG);
2901 case ISD::SINT_TO_FP:
2902 case ISD::UINT_TO_FP:
2903 return LowerINT_TO_FP(Op, DAG);
2904 case ISD::FP_TO_SINT:
2905 case ISD::FP_TO_UINT:
2906 return LowerFP_TO_INT(Op, DAG);
2907 case ISD::FSINCOS:
2908 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002909 case ISD::FLT_ROUNDS_:
2910 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002911 case ISD::MUL:
2912 return LowerMUL(Op, DAG);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +00002913 case ISD::MULHS:
2914 case ISD::MULHU:
2915 return LowerMULH(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002916 case ISD::INTRINSIC_WO_CHAIN:
2917 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002918 case ISD::STORE:
2919 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002920 case ISD::VECREDUCE_ADD:
2921 case ISD::VECREDUCE_SMAX:
2922 case ISD::VECREDUCE_SMIN:
2923 case ISD::VECREDUCE_UMAX:
2924 case ISD::VECREDUCE_UMIN:
2925 case ISD::VECREDUCE_FMAX:
2926 case ISD::VECREDUCE_FMIN:
2927 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002928 case ISD::ATOMIC_LOAD_SUB:
2929 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002930 case ISD::ATOMIC_LOAD_AND:
2931 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002932 case ISD::DYNAMIC_STACKALLOC:
2933 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002934 }
2935}
2936
Tim Northover3b0846e2014-05-24 12:50:23 +00002937//===----------------------------------------------------------------------===//
2938// Calling Convention Implementation
2939//===----------------------------------------------------------------------===//
2940
2941#include "AArch64GenCallingConv.inc"
2942
Robin Morisset039781e2014-08-29 21:53:01 +00002943/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002944CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2945 bool IsVarArg) const {
2946 switch (CC) {
2947 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002948 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002949 case CallingConv::WebKit_JS:
2950 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002951 case CallingConv::GHC:
2952 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002953 case CallingConv::C:
2954 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002955 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002956 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002957 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002958 if (Subtarget->isTargetWindows() && IsVarArg)
2959 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002960 if (!Subtarget->isTargetDarwin())
2961 return CC_AArch64_AAPCS;
2962 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002963 case CallingConv::Win64:
2964 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00002965 case CallingConv::AArch64_VectorCall:
2966 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002967 }
2968}
2969
Tim Northover406024a2016-08-10 21:44:01 +00002970CCAssignFn *
2971AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2972 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2973 : RetCC_AArch64_AAPCS;
2974}
2975
Tim Northover3b0846e2014-05-24 12:50:23 +00002976SDValue AArch64TargetLowering::LowerFormalArguments(
2977 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002978 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2979 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002980 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002981 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00002982 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002983
2984 // Assign locations to all of the incoming arguments.
2985 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002986 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2987 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002988
2989 // At this point, Ins[].VT may already be promoted to i32. To correctly
2990 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2991 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2992 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2993 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2994 // LocVT.
2995 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00002996 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00002997 unsigned CurArgIdx = 0;
2998 for (unsigned i = 0; i != NumArgs; ++i) {
2999 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003000 if (Ins[i].isOrigArg()) {
3001 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3002 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003003
Andrew Trick05938a52015-02-16 18:10:47 +00003004 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003005 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3006 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003007 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3008 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3009 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3010 ValVT = MVT::i8;
3011 else if (ActualMVT == MVT::i16)
3012 ValVT = MVT::i16;
3013 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003014 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3015 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003016 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003017 assert(!Res && "Call operand has unhandled type");
3018 (void)Res;
3019 }
3020 assert(ArgLocs.size() == Ins.size());
3021 SmallVector<SDValue, 16> ArgValues;
3022 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3023 CCValAssign &VA = ArgLocs[i];
3024
3025 if (Ins[i].Flags.isByVal()) {
3026 // Byval is used for HFAs in the PCS, but the system should work in a
3027 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003028 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003029 int Size = Ins[i].Flags.getByValSize();
3030 unsigned NumRegs = (Size + 7) / 8;
3031
3032 // FIXME: This works on big-endian for composite byvals, which are the common
3033 // case. It should also work for fundamental types too.
3034 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003035 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003036 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003037 InVals.push_back(FrameIdxN);
3038
3039 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003040 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003041
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003042 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003043 // Arguments stored in registers.
3044 EVT RegVT = VA.getLocVT();
3045
3046 SDValue ArgValue;
3047 const TargetRegisterClass *RC;
3048
3049 if (RegVT == MVT::i32)
3050 RC = &AArch64::GPR32RegClass;
3051 else if (RegVT == MVT::i64)
3052 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003053 else if (RegVT == MVT::f16)
3054 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003055 else if (RegVT == MVT::f32)
3056 RC = &AArch64::FPR32RegClass;
3057 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3058 RC = &AArch64::FPR64RegClass;
3059 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3060 RC = &AArch64::FPR128RegClass;
3061 else
3062 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3063
3064 // Transform the arguments in physical registers into virtual ones.
3065 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3066 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3067
3068 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3069 // to 64 bits. Insert an assert[sz]ext to capture this, then
3070 // truncate to the right size.
3071 switch (VA.getLocInfo()) {
3072 default:
3073 llvm_unreachable("Unknown loc info!");
3074 case CCValAssign::Full:
3075 break;
3076 case CCValAssign::BCvt:
3077 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3078 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003079 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003080 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003081 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003082 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3083 // nodes after our lowering.
3084 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003085 break;
3086 }
3087
3088 InVals.push_back(ArgValue);
3089
3090 } else { // VA.isRegLoc()
3091 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3092 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003093 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003094
3095 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003096 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3097 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003098 BEAlign = 8 - ArgSize;
3099
Matthias Braun941a7052016-07-28 18:40:00 +00003100 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003101
3102 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003103 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003104 SDValue ArgValue;
3105
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003106 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003107 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003108 MVT MemVT = VA.getValVT();
3109
Tim Northover47e003c2014-05-26 17:21:53 +00003110 switch (VA.getLocInfo()) {
3111 default:
3112 break;
Tim Northover6890add2014-06-03 13:54:53 +00003113 case CCValAssign::BCvt:
3114 MemVT = VA.getLocVT();
3115 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003116 case CCValAssign::SExt:
3117 ExtType = ISD::SEXTLOAD;
3118 break;
3119 case CCValAssign::ZExt:
3120 ExtType = ISD::ZEXTLOAD;
3121 break;
3122 case CCValAssign::AExt:
3123 ExtType = ISD::EXTLOAD;
3124 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003125 }
3126
Alex Lorenze40c8a22015-08-11 23:09:45 +00003127 ArgValue = DAG.getExtLoad(
3128 ExtType, DL, VA.getLocVT(), Chain, FIN,
3129 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003130 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003131
Tim Northover3b0846e2014-05-24 12:50:23 +00003132 InVals.push_back(ArgValue);
3133 }
3134 }
3135
3136 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003137 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003138 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003139 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003140 // The AAPCS variadic function ABI is identical to the non-variadic
3141 // one. As a result there may be more arguments in registers and we should
3142 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003143 // Win64 variadic functions also pass arguments in registers, but all float
3144 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003145 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3146 }
3147
Tim Northover3b0846e2014-05-24 12:50:23 +00003148 // This will point to the next argument passed via stack.
3149 unsigned StackOffset = CCInfo.getNextStackOffset();
3150 // We currently pass all varargs at 8-byte alignment.
3151 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003152 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003153
3154 if (MFI.hasMustTailInVarArgFunc()) {
3155 SmallVector<MVT, 2> RegParmTypes;
3156 RegParmTypes.push_back(MVT::i64);
3157 RegParmTypes.push_back(MVT::f128);
3158 // Compute the set of forwarded registers. The rest are scratch.
3159 SmallVectorImpl<ForwardedRegister> &Forwards =
3160 FuncInfo->getForwardedMustTailRegParms();
3161 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3162 CC_AArch64_AAPCS);
3163 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003164 }
3165
Tim Northover3b0846e2014-05-24 12:50:23 +00003166 unsigned StackArgSize = CCInfo.getNextStackOffset();
3167 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3168 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3169 // This is a non-standard ABI so by fiat I say we're allowed to make full
3170 // use of the stack area to be popped, which must be aligned to 16 bytes in
3171 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003172 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003173
3174 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3175 // a multiple of 16.
3176 FuncInfo->setArgumentStackToRestore(StackArgSize);
3177
3178 // This realignment carries over to the available bytes below. Our own
3179 // callers will guarantee the space is free by giving an aligned value to
3180 // CALLSEQ_START.
3181 }
3182 // Even if we're not expected to free up the space, it's useful to know how
3183 // much is there while considering tail calls (because we can reuse it).
3184 FuncInfo->setBytesInStackArgArea(StackArgSize);
3185
Tri Vo6c47c622018-09-22 22:17:50 +00003186 if (Subtarget->hasCustomCallingConv())
3187 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3188
Tim Northover3b0846e2014-05-24 12:50:23 +00003189 return Chain;
3190}
3191
3192void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003193 SelectionDAG &DAG,
3194 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003195 SDValue &Chain) const {
3196 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003197 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003198 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003199 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003200 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003201
3202 SmallVector<SDValue, 8> MemOps;
3203
3204 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3205 AArch64::X3, AArch64::X4, AArch64::X5,
3206 AArch64::X6, AArch64::X7 };
3207 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003208 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003209
3210 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3211 int GPRIdx = 0;
3212 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003213 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003214 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003215 if (GPRSaveSize & 15)
3216 // The extra size here, if triggered, will always be 8.
3217 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3218 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003219 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003220
Mehdi Amini44ede332015-07-09 02:09:04 +00003221 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003222
3223 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3224 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3225 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003226 SDValue Store = DAG.getStore(
3227 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003228 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003229 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3230 GPRIdx,
3231 (i - FirstVariadicGPR) * 8)
3232 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003233 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003234 FIN =
3235 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003236 }
3237 }
3238 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3239 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3240
Martin Storsjo2f24e932017-07-17 20:05:19 +00003241 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003242 static const MCPhysReg FPRArgRegs[] = {
3243 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3244 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3245 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003246 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003247
3248 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3249 int FPRIdx = 0;
3250 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003251 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003252
Mehdi Amini44ede332015-07-09 02:09:04 +00003253 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003254
3255 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3256 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3257 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3258
Alex Lorenze40c8a22015-08-11 23:09:45 +00003259 SDValue Store = DAG.getStore(
3260 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003261 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003262 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003263 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3264 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003265 }
3266 }
3267 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3268 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3269 }
3270
3271 if (!MemOps.empty()) {
3272 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3273 }
3274}
3275
3276/// LowerCallResult - Lower the result values of a call into the
3277/// appropriate copies out of appropriate physical registers.
3278SDValue AArch64TargetLowering::LowerCallResult(
3279 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003280 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3281 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003282 SDValue ThisVal) const {
3283 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3284 ? RetCC_AArch64_WebKit_JS
3285 : RetCC_AArch64_AAPCS;
3286 // Assign locations to each value returned by this call.
3287 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003288 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3289 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003290 CCInfo.AnalyzeCallResult(Ins, RetCC);
3291
3292 // Copy all of the result registers out of their specified physreg.
3293 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3294 CCValAssign VA = RVLocs[i];
3295
3296 // Pass 'this' value directly from the argument to return value, to avoid
3297 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003298 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003299 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3300 "unexpected return calling convention register assignment");
3301 InVals.push_back(ThisVal);
3302 continue;
3303 }
3304
3305 SDValue Val =
3306 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3307 Chain = Val.getValue(1);
3308 InFlag = Val.getValue(2);
3309
3310 switch (VA.getLocInfo()) {
3311 default:
3312 llvm_unreachable("Unknown loc info!");
3313 case CCValAssign::Full:
3314 break;
3315 case CCValAssign::BCvt:
3316 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3317 break;
3318 }
3319
3320 InVals.push_back(Val);
3321 }
3322
3323 return Chain;
3324}
3325
Matthias Braun1af14142016-09-13 19:27:38 +00003326/// Return true if the calling convention is one that we can guarantee TCO for.
3327static bool canGuaranteeTCO(CallingConv::ID CC) {
3328 return CC == CallingConv::Fast;
3329}
3330
3331/// Return true if we might ever do TCO for calls with this calling convention.
3332static bool mayTailCallThisCC(CallingConv::ID CC) {
3333 switch (CC) {
3334 case CallingConv::C:
3335 case CallingConv::PreserveMost:
3336 case CallingConv::Swift:
3337 return true;
3338 default:
3339 return canGuaranteeTCO(CC);
3340 }
3341}
3342
Tim Northover3b0846e2014-05-24 12:50:23 +00003343bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3344 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003345 const SmallVectorImpl<ISD::OutputArg> &Outs,
3346 const SmallVectorImpl<SDValue> &OutVals,
3347 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003348 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003349 return false;
3350
Matthias Braun8d414362016-03-30 22:46:04 +00003351 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003352 const Function &CallerF = MF.getFunction();
3353 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003354 bool CCMatch = CallerCC == CalleeCC;
3355
3356 // Byval parameters hand the function a pointer directly into the stack area
3357 // we want to reuse during a tail call. Working around this *is* possible (see
3358 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003359 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3360 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003361 i != e; ++i)
3362 if (i->hasByValAttr())
3363 return false;
3364
Matthias Braun1af14142016-09-13 19:27:38 +00003365 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3366 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003367
Oliver Stannard12993dd2014-08-18 12:42:15 +00003368 // Externally-defined functions with weak linkage should not be
3369 // tail-called on AArch64 when the OS does not support dynamic
3370 // pre-emption of symbols, as the AAELF spec requires normal calls
3371 // to undefined weak functions to be replaced with a NOP or jump to the
3372 // next instruction. The behaviour of branch instructions in this
3373 // situation (as used for tail calls) is implementation-defined, so we
3374 // cannot rely on the linker replacing the tail call with a return.
3375 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3376 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003377 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003378 if (GV->hasExternalWeakLinkage() &&
3379 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003380 return false;
3381 }
3382
Tim Northover3b0846e2014-05-24 12:50:23 +00003383 // Now we search for cases where we can use a tail call without changing the
3384 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3385 // concept.
3386
3387 // I want anyone implementing a new calling convention to think long and hard
3388 // about this assert.
3389 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3390 "Unexpected variadic calling convention");
3391
Matthias Braun8d414362016-03-30 22:46:04 +00003392 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003393 if (isVarArg && !Outs.empty()) {
3394 // At least two cases here: if caller is fastcc then we can't have any
3395 // memory arguments (we'd be expected to clean up the stack afterwards). If
3396 // caller is C then we could potentially use its argument area.
3397
3398 // FIXME: for now we take the most conservative of these in both cases:
3399 // disallow all variadic memory operands.
3400 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003401 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003402
3403 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003404 for (const CCValAssign &ArgLoc : ArgLocs)
3405 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003406 return false;
3407 }
3408
Matthias Braun8d414362016-03-30 22:46:04 +00003409 // Check that the call results are passed in the same way.
3410 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3411 CCAssignFnForCall(CalleeCC, isVarArg),
3412 CCAssignFnForCall(CallerCC, isVarArg)))
3413 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003414 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003415 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3416 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003417 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003418 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003419 if (Subtarget->hasCustomCallingConv()) {
3420 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3421 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3422 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003423 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003424 return false;
3425 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003426
3427 // Nothing more to check if the callee is taking no arguments
3428 if (Outs.empty())
3429 return true;
3430
3431 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003432 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003433
3434 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3435
3436 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3437
Matthias Braun74a0bd32016-04-13 21:43:16 +00003438 // If the stack arguments for this call do not fit into our own save area then
3439 // the call cannot be made tail.
3440 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3441 return false;
3442
Matthias Braun46b0f032016-04-14 01:10:42 +00003443 const MachineRegisterInfo &MRI = MF.getRegInfo();
3444 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3445 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003446
3447 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003448}
3449
3450SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3451 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003452 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003453 int ClobberedFI) const {
3454 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003455 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3456 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003457
3458 // Include the original chain at the beginning of the list. When this is
3459 // used by target LowerCall hooks, this helps legalize find the
3460 // CALLSEQ_BEGIN node.
3461 ArgChains.push_back(Chain);
3462
3463 // Add a chain value for each stack argument corresponding
3464 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3465 UE = DAG.getEntryNode().getNode()->use_end();
3466 U != UE; ++U)
3467 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3468 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3469 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003470 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003471 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003472 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003473
3474 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3475 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3476 ArgChains.push_back(SDValue(L, 1));
3477 }
3478
3479 // Build a tokenfactor for all the chains.
3480 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3481}
3482
3483bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3484 bool TailCallOpt) const {
3485 return CallCC == CallingConv::Fast && TailCallOpt;
3486}
3487
Tim Northover3b0846e2014-05-24 12:50:23 +00003488/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3489/// and add input and output parameter nodes.
3490SDValue
3491AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3492 SmallVectorImpl<SDValue> &InVals) const {
3493 SelectionDAG &DAG = CLI.DAG;
3494 SDLoc &DL = CLI.DL;
3495 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3496 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3497 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3498 SDValue Chain = CLI.Chain;
3499 SDValue Callee = CLI.Callee;
3500 bool &IsTailCall = CLI.IsTailCall;
3501 CallingConv::ID CallConv = CLI.CallConv;
3502 bool IsVarArg = CLI.IsVarArg;
3503
3504 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003505 bool IsThisReturn = false;
3506
3507 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3508 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3509 bool IsSibCall = false;
3510
3511 if (IsTailCall) {
3512 // Check if it's really possible to do a tail call.
3513 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003514 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003515 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003516 report_fatal_error("failed to perform tail call elimination on a call "
3517 "site marked musttail");
3518
3519 // A sibling call is one where we're under the usual C ABI and not planning
3520 // to change that but can still do a tail call:
3521 if (!TailCallOpt && IsTailCall)
3522 IsSibCall = true;
3523
3524 if (IsTailCall)
3525 ++NumTailCalls;
3526 }
3527
3528 // Analyze operands of the call, assigning locations to each operand.
3529 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003530 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3531 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003532
3533 if (IsVarArg) {
3534 // Handle fixed and variable vector arguments differently.
3535 // Variable vector arguments always go into memory.
3536 unsigned NumArgs = Outs.size();
3537
3538 for (unsigned i = 0; i != NumArgs; ++i) {
3539 MVT ArgVT = Outs[i].VT;
3540 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3541 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3542 /*IsVarArg=*/ !Outs[i].IsFixed);
3543 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3544 assert(!Res && "Call operand has unhandled type");
3545 (void)Res;
3546 }
3547 } else {
3548 // At this point, Outs[].VT may already be promoted to i32. To correctly
3549 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3550 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3551 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3552 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3553 // LocVT.
3554 unsigned NumArgs = Outs.size();
3555 for (unsigned i = 0; i != NumArgs; ++i) {
3556 MVT ValVT = Outs[i].VT;
3557 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003558 EVT ActualVT = getValueType(DAG.getDataLayout(),
3559 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003560 /*AllowUnknown*/ true);
3561 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3562 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3563 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003564 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003565 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003566 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003567 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003568
3569 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003570 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003571 assert(!Res && "Call operand has unhandled type");
3572 (void)Res;
3573 }
3574 }
3575
3576 // Get a count of how many bytes are to be pushed on the stack.
3577 unsigned NumBytes = CCInfo.getNextStackOffset();
3578
3579 if (IsSibCall) {
3580 // Since we're not changing the ABI to make this a tail call, the memory
3581 // operands are already available in the caller's incoming argument space.
3582 NumBytes = 0;
3583 }
3584
3585 // FPDiff is the byte offset of the call's argument area from the callee's.
3586 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3587 // by this amount for a tail call. In a sibling call it must be 0 because the
3588 // caller will deallocate the entire stack and the callee still expects its
3589 // arguments to begin at SP+0. Completely unused for non-tail calls.
3590 int FPDiff = 0;
3591
3592 if (IsTailCall && !IsSibCall) {
3593 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3594
3595 // Since callee will pop argument stack as a tail call, we must keep the
3596 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003597 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003598
3599 // FPDiff will be negative if this tail call requires more space than we
3600 // would automatically have in our incoming argument space. Positive if we
3601 // can actually shrink the stack.
3602 FPDiff = NumReusableBytes - NumBytes;
3603
3604 // The stack pointer must be 16-byte aligned at all times it's used for a
3605 // memory operation, which in practice means at *all* times and in
3606 // particular across call boundaries. Therefore our own arguments started at
3607 // a 16-byte aligned SP and the delta applied for the tail call should
3608 // satisfy the same constraint.
3609 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3610 }
3611
3612 // Adjust the stack pointer for the new arguments...
3613 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003614 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003615 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003616
Mehdi Amini44ede332015-07-09 02:09:04 +00003617 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3618 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003619
3620 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3621 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003622 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003623
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003624 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3625 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3626 for (const auto &F : Forwards) {
3627 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3628 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3629 }
3630 }
3631
Tim Northover3b0846e2014-05-24 12:50:23 +00003632 // Walk the register/memloc assignments, inserting copies/loads.
3633 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3634 ++i, ++realArgIdx) {
3635 CCValAssign &VA = ArgLocs[i];
3636 SDValue Arg = OutVals[realArgIdx];
3637 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3638
3639 // Promote the value if needed.
3640 switch (VA.getLocInfo()) {
3641 default:
3642 llvm_unreachable("Unknown loc info!");
3643 case CCValAssign::Full:
3644 break;
3645 case CCValAssign::SExt:
3646 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3647 break;
3648 case CCValAssign::ZExt:
3649 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3650 break;
3651 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003652 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3653 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3654 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3655 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3656 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003657 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3658 break;
3659 case CCValAssign::BCvt:
3660 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3661 break;
3662 case CCValAssign::FPExt:
3663 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3664 break;
3665 }
3666
3667 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003668 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3669 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003670 assert(VA.getLocVT() == MVT::i64 &&
3671 "unexpected calling convention register assignment");
3672 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3673 "unexpected use of 'returned'");
3674 IsThisReturn = true;
3675 }
3676 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3677 } else {
3678 assert(VA.isMemLoc());
3679
3680 SDValue DstAddr;
3681 MachinePointerInfo DstInfo;
3682
3683 // FIXME: This works on big-endian for composite byvals, which are the
3684 // common case. It should also work for fundamental types too.
3685 uint32_t BEAlign = 0;
3686 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003687 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003688 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003689 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3690 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003691 if (OpSize < 8)
3692 BEAlign = 8 - OpSize;
3693 }
3694 unsigned LocMemOffset = VA.getLocMemOffset();
3695 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003696 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003697 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003698
3699 if (IsTailCall) {
3700 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003701 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003702
Mehdi Amini44ede332015-07-09 02:09:04 +00003703 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003704 DstInfo =
3705 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003706
3707 // Make sure any stack arguments overlapping with where we're storing
3708 // are loaded before this eventual operation. Otherwise they'll be
3709 // clobbered.
3710 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3711 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003712 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003713
Mehdi Amini44ede332015-07-09 02:09:04 +00003714 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003715 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3716 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003717 }
3718
3719 if (Outs[i].Flags.isByVal()) {
3720 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003721 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003722 SDValue Cpy = DAG.getMemcpy(
3723 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003724 /*isVol = */ false, /*AlwaysInline = */ false,
3725 /*isTailCall = */ false,
3726 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003727
3728 MemOpChains.push_back(Cpy);
3729 } else {
3730 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3731 // promoted to a legal register type i32, we should truncate Arg back to
3732 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003733 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3734 VA.getValVT() == MVT::i16)
3735 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003736
Justin Lebar9c375812016-07-15 18:27:10 +00003737 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003738 MemOpChains.push_back(Store);
3739 }
3740 }
3741 }
3742
3743 if (!MemOpChains.empty())
3744 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3745
3746 // Build a sequence of copy-to-reg nodes chained together with token chain
3747 // and flag operands which copy the outgoing args into the appropriate regs.
3748 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003749 for (auto &RegToPass : RegsToPass) {
3750 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3751 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003752 InFlag = Chain.getValue(1);
3753 }
3754
3755 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3756 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3757 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003758 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3759 auto GV = G->getGlobal();
3760 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3761 AArch64II::MO_GOT) {
3762 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3763 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003764 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3765 assert(Subtarget->isTargetWindows() &&
3766 "Windows is the only supported COFF target");
3767 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003768 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003769 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003770 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3771 }
3772 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3773 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3774 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003775 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003776 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3777 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003778 } else {
3779 const char *Sym = S->getSymbol();
3780 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003781 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003782 }
3783
3784 // We don't usually want to end the call-sequence here because we would tidy
3785 // the frame up *after* the call, however in the ABI-changing tail-call case
3786 // we've carefully laid out the parameters so that when sp is reset they'll be
3787 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003788 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003789 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3790 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003791 InFlag = Chain.getValue(1);
3792 }
3793
3794 std::vector<SDValue> Ops;
3795 Ops.push_back(Chain);
3796 Ops.push_back(Callee);
3797
3798 if (IsTailCall) {
3799 // Each tail call may have to adjust the stack by a different amount, so
3800 // this information must travel along with the operation for eventual
3801 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003802 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003803 }
3804
3805 // Add argument registers to the end of the list so that they are known live
3806 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003807 for (auto &RegToPass : RegsToPass)
3808 Ops.push_back(DAG.getRegister(RegToPass.first,
3809 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003810
3811 // Add a register mask operand representing the call-preserved registers.
3812 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003813 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003814 if (IsThisReturn) {
3815 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003816 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003817 if (!Mask) {
3818 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003819 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003820 }
3821 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003822 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003823
Tri Vo6c47c622018-09-22 22:17:50 +00003824 if (Subtarget->hasCustomCallingConv())
3825 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3826
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003827 if (TRI->isAnyArgRegReserved(MF))
3828 TRI->emitReservedArgRegCallError(MF);
3829
Tim Northover3b0846e2014-05-24 12:50:23 +00003830 assert(Mask && "Missing call preserved mask for calling convention");
3831 Ops.push_back(DAG.getRegisterMask(Mask));
3832
3833 if (InFlag.getNode())
3834 Ops.push_back(InFlag);
3835
3836 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3837
3838 // If we're doing a tall call, use a TC_RETURN here rather than an
3839 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003840 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003841 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003842 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003843 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003844
3845 // Returns a chain and a flag for retval copy to use.
3846 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3847 InFlag = Chain.getValue(1);
3848
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003849 uint64_t CalleePopBytes =
3850 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003851
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003852 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3853 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3854 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003855 if (!Ins.empty())
3856 InFlag = Chain.getValue(1);
3857
3858 // Handle result values, copying them out of physregs into vregs that we
3859 // return.
3860 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3861 InVals, IsThisReturn,
3862 IsThisReturn ? OutVals[0] : SDValue());
3863}
3864
3865bool AArch64TargetLowering::CanLowerReturn(
3866 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3867 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3868 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3869 ? RetCC_AArch64_WebKit_JS
3870 : RetCC_AArch64_AAPCS;
3871 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003872 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003873 return CCInfo.CheckReturn(Outs, RetCC);
3874}
3875
3876SDValue
3877AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3878 bool isVarArg,
3879 const SmallVectorImpl<ISD::OutputArg> &Outs,
3880 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003881 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003882 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3883 ? RetCC_AArch64_WebKit_JS
3884 : RetCC_AArch64_AAPCS;
3885 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003886 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3887 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003888 CCInfo.AnalyzeReturn(Outs, RetCC);
3889
3890 // Copy the result values into the output registers.
3891 SDValue Flag;
3892 SmallVector<SDValue, 4> RetOps(1, Chain);
3893 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3894 ++i, ++realRVLocIdx) {
3895 CCValAssign &VA = RVLocs[i];
3896 assert(VA.isRegLoc() && "Can only return in registers!");
3897 SDValue Arg = OutVals[realRVLocIdx];
3898
3899 switch (VA.getLocInfo()) {
3900 default:
3901 llvm_unreachable("Unknown loc info!");
3902 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003903 if (Outs[i].ArgVT == MVT::i1) {
3904 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3905 // value. This is strictly redundant on Darwin (which uses "zeroext
3906 // i1"), but will be optimised out before ISel.
3907 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3908 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3909 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003910 break;
3911 case CCValAssign::BCvt:
3912 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3913 break;
3914 }
3915
3916 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3917 Flag = Chain.getValue(1);
3918 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3919 }
Manman Rencbe4f942015-12-16 21:04:19 +00003920 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3921 const MCPhysReg *I =
3922 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3923 if (I) {
3924 for (; *I; ++I) {
3925 if (AArch64::GPR64RegClass.contains(*I))
3926 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3927 else if (AArch64::FPR64RegClass.contains(*I))
3928 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3929 else
3930 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3931 }
3932 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003933
3934 RetOps[0] = Chain; // Update chain.
3935
3936 // Add the flag if we have it.
3937 if (Flag.getNode())
3938 RetOps.push_back(Flag);
3939
3940 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3941}
3942
3943//===----------------------------------------------------------------------===//
3944// Other Lowering Code
3945//===----------------------------------------------------------------------===//
3946
Joel Jonesa7c4a522017-04-21 17:31:03 +00003947SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3948 SelectionDAG &DAG,
3949 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003950 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3951 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003952}
3953
3954SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3955 SelectionDAG &DAG,
3956 unsigned Flag) const {
3957 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3958}
3959
3960SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3961 SelectionDAG &DAG,
3962 unsigned Flag) const {
3963 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3964 N->getOffset(), Flag);
3965}
3966
3967SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3968 SelectionDAG &DAG,
3969 unsigned Flag) const {
3970 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3971}
3972
3973// (loadGOT sym)
3974template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003975SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3976 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003977 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003978 SDLoc DL(N);
3979 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003980 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003981 // FIXME: Once remat is capable of dealing with instructions with register
3982 // operands, expand this into two nodes instead of using a wrapper node.
3983 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3984}
3985
3986// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3987template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003988SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3989 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003990 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003991 SDLoc DL(N);
3992 EVT Ty = getPointerTy(DAG.getDataLayout());
3993 const unsigned char MO_NC = AArch64II::MO_NC;
3994 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003995 AArch64ISD::WrapperLarge, DL, Ty,
3996 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3997 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3998 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3999 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004000}
4001
4002// (addlow (adrp %hi(sym)) %lo(sym))
4003template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004004SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4005 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004006 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004007 SDLoc DL(N);
4008 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004009 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004010 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004011 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004012 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4013 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4014}
4015
David Green9dd1d452018-08-22 11:31:39 +00004016// (adr sym)
4017template <class NodeTy>
4018SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4019 unsigned Flags) const {
4020 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4021 SDLoc DL(N);
4022 EVT Ty = getPointerTy(DAG.getDataLayout());
4023 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4024 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4025}
4026
Tim Northover3b0846e2014-05-24 12:50:23 +00004027SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4028 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004029 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004030 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004031 unsigned char OpFlags =
4032 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004033
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004034 if (OpFlags != AArch64II::MO_NO_FLAG)
4035 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4036 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004037
David Green9dd1d452018-08-22 11:31:39 +00004038 // This also catches the large code model case for Darwin, and tiny code
4039 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004040 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004041 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004042 }
4043
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004044 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004045 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004046 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004047 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004048 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004049 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004050 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004051 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004052 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4053 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004054 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004055 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4056 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4057 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004058}
4059
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004060/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004061/// and calls to compute the variable's address (for Darwin, currently) and
4062/// return an SDValue containing the final node.
4063
4064/// Darwin only has one TLS scheme which must be capable of dealing with the
4065/// fully general situation, in the worst case. This means:
4066/// + "extern __thread" declaration.
4067/// + Defined in a possibly unknown dynamic library.
4068///
4069/// The general system is that each __thread variable has a [3 x i64] descriptor
4070/// which contains information used by the runtime to calculate the address. The
4071/// only part of this the compiler needs to know about is the first xword, which
4072/// contains a function pointer that must be called with the address of the
4073/// entire descriptor in "x0".
4074///
4075/// Since this descriptor may be in a different unit, in general even the
4076/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4077/// is:
4078/// adrp x0, _var@TLVPPAGE
4079/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4080/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4081/// ; the function pointer
4082/// blr x1 ; Uses descriptor address in x0
4083/// ; Address of _var is now in x0.
4084///
4085/// If the address of _var's descriptor *is* known to the linker, then it can
4086/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4087/// a slight efficiency gain.
4088SDValue
4089AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4090 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004091 assert(Subtarget->isTargetDarwin() &&
4092 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004093
4094 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004095 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004096 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4097
4098 SDValue TLVPAddr =
4099 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4100 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4101
4102 // The first entry in the descriptor is a function pointer that we must call
4103 // to obtain the address of the variable.
4104 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004105 SDValue FuncTLVGet = DAG.getLoad(
4106 MVT::i64, DL, Chain, DescAddr,
4107 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4108 /* Alignment = */ 8,
4109 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4110 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004111 Chain = FuncTLVGet.getValue(1);
4112
Matthias Braun941a7052016-07-28 18:40:00 +00004113 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4114 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004115
4116 // TLS calls preserve all registers except those that absolutely must be
4117 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4118 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004119 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4120 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4121 if (Subtarget->hasCustomCallingConv())
4122 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004123
4124 // Finally, we can make the call. This is just a degenerate version of a
4125 // normal AArch64 call node: x0 takes the address of the descriptor, and
4126 // returns the address of the variable in this thread.
4127 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4128 Chain =
4129 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4130 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4131 DAG.getRegisterMask(Mask), Chain.getValue(1));
4132 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4133}
4134
4135/// When accessing thread-local variables under either the general-dynamic or
4136/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4137/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004138/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004139///
Kristof Beylsaea84612015-03-04 09:12:08 +00004140/// The sequence is:
4141/// adrp x0, :tlsdesc:var
4142/// ldr x1, [x0, #:tlsdesc_lo12:var]
4143/// add x0, x0, #:tlsdesc_lo12:var
4144/// .tlsdesccall var
4145/// blr x1
4146/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004147///
Kristof Beylsaea84612015-03-04 09:12:08 +00004148/// The above sequence must be produced unscheduled, to enable the linker to
4149/// optimize/relax this sequence.
4150/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4151/// above sequence, and expanded really late in the compilation flow, to ensure
4152/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004153SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4154 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004155 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004156 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004157
Kristof Beylsaea84612015-03-04 09:12:08 +00004158 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004159 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004160
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004161 Chain =
4162 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004163 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004164
4165 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4166}
4167
4168SDValue
4169AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4170 SelectionDAG &DAG) const {
4171 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004172 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4173 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004174 // Different choices can be made for the maximum size of the TLS area for a
4175 // module. For the small address model, the default TLS size is 16MiB and the
4176 // maximum TLS size is 4GiB.
4177 // FIXME: add -mtls-size command line option and make it control the 16MiB
4178 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004179 // FIXME: add tiny codemodel support. We currently generate the same code as
4180 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004181 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4182
4183 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004184
Kristof Beylsaea84612015-03-04 09:12:08 +00004185 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4186 if (Model == TLSModel::LocalDynamic)
4187 Model = TLSModel::GeneralDynamic;
4188 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004189
4190 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004191 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004192 SDLoc DL(Op);
4193 const GlobalValue *GV = GA->getGlobal();
4194
4195 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4196
4197 if (Model == TLSModel::LocalExec) {
4198 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004199 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004200 SDValue LoVar = DAG.getTargetGlobalAddress(
4201 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004202 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004203
Kristof Beylsaea84612015-03-04 09:12:08 +00004204 SDValue TPWithOff_lo =
4205 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004206 HiVar,
4207 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004208 0);
4209 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004210 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4211 LoVar,
4212 DAG.getTargetConstant(0, DL, MVT::i32)),
4213 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004214 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004215 } else if (Model == TLSModel::InitialExec) {
4216 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4217 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4218 } else if (Model == TLSModel::LocalDynamic) {
4219 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4220 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4221 // the beginning of the module's TLS region, followed by a DTPREL offset
4222 // calculation.
4223
4224 // These accesses will need deduplicating if there's more than one.
4225 AArch64FunctionInfo *MFI =
4226 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4227 MFI->incNumLocalDynamicTLSAccesses();
4228
Tim Northover3b0846e2014-05-24 12:50:23 +00004229 // The call needs a relocation too for linker relaxation. It doesn't make
4230 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4231 // the address.
4232 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4233 AArch64II::MO_TLS);
4234
4235 // Now we can calculate the offset from TPIDR_EL0 to this module's
4236 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004237 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004238
4239 // Now use :dtprel_whatever: operations to calculate this variable's offset
4240 // in its thread-storage area.
4241 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004242 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004243 SDValue LoVar = DAG.getTargetGlobalAddress(
4244 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004245 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4246
Kristof Beylsaea84612015-03-04 09:12:08 +00004247 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004248 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004249 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004250 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4251 DAG.getTargetConstant(0, DL, MVT::i32)),
4252 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004253 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004254 // The call needs a relocation too for linker relaxation. It doesn't make
4255 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4256 // the address.
4257 SDValue SymAddr =
4258 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4259
4260 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004261 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004262 } else
4263 llvm_unreachable("Unsupported ELF TLS access model");
4264
4265 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4266}
4267
Martin Storsjocc240962018-03-10 19:05:21 +00004268SDValue
4269AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4270 SelectionDAG &DAG) const {
4271 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4272
4273 SDValue Chain = DAG.getEntryNode();
4274 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4275 SDLoc DL(Op);
4276
4277 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4278
4279 // Load the ThreadLocalStoragePointer from the TEB
4280 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4281 SDValue TLSArray =
4282 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4283 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4284 Chain = TLSArray.getValue(1);
4285
4286 // Load the TLS index from the C runtime;
4287 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4288 // This also does the same as LOADgot, but using a generic i32 load,
4289 // while LOADgot only loads i64.
4290 SDValue TLSIndexHi =
4291 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4292 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4293 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4294 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4295 SDValue TLSIndex =
4296 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4297 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4298 Chain = TLSIndex.getValue(1);
4299
4300 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4301 // offset into the TLSArray.
4302 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4303 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4304 DAG.getConstant(3, DL, PtrVT));
4305 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4306 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4307 MachinePointerInfo());
4308 Chain = TLS.getValue(1);
4309
4310 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4311 const GlobalValue *GV = GA->getGlobal();
4312 SDValue TGAHi = DAG.getTargetGlobalAddress(
4313 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4314 SDValue TGALo = DAG.getTargetGlobalAddress(
4315 GV, DL, PtrVT, 0,
4316 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4317
4318 // Add the offset from the start of the .tls section (section base).
4319 SDValue Addr =
4320 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4321 DAG.getTargetConstant(0, DL, MVT::i32)),
4322 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004323 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004324 return Addr;
4325}
4326
Tim Northover3b0846e2014-05-24 12:50:23 +00004327SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4328 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004329 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004330 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004331 return LowerToTLSEmulatedModel(GA, DAG);
4332
Tim Northover3b0846e2014-05-24 12:50:23 +00004333 if (Subtarget->isTargetDarwin())
4334 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004335 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004336 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004337 if (Subtarget->isTargetWindows())
4338 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004339
4340 llvm_unreachable("Unexpected platform trying to use TLS");
4341}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004342
Tim Northover3b0846e2014-05-24 12:50:23 +00004343SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4344 SDValue Chain = Op.getOperand(0);
4345 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4346 SDValue LHS = Op.getOperand(2);
4347 SDValue RHS = Op.getOperand(3);
4348 SDValue Dest = Op.getOperand(4);
4349 SDLoc dl(Op);
4350
4351 // Handle f128 first, since lowering it will result in comparing the return
4352 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4353 // is expecting to deal with.
4354 if (LHS.getValueType() == MVT::f128) {
4355 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4356
4357 // If softenSetCCOperands returned a scalar, we need to compare the result
4358 // against zero to select between true and false values.
4359 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004360 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004361 CC = ISD::SETNE;
4362 }
4363 }
4364
4365 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4366 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004367 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4368 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004369 // Only lower legal XALUO ops.
4370 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4371 return SDValue();
4372
4373 // The actual operation with overflow check.
4374 AArch64CC::CondCode OFCC;
4375 SDValue Value, Overflow;
4376 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4377
4378 if (CC == ISD::SETNE)
4379 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004380 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004381
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004382 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4383 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004384 }
4385
4386 if (LHS.getValueType().isInteger()) {
4387 assert((LHS.getValueType() == RHS.getValueType()) &&
4388 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4389
4390 // If the RHS of the comparison is zero, we can potentially fold this
4391 // to a specialized branch.
4392 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4393 if (RHSC && RHSC->getZExtValue() == 0) {
4394 if (CC == ISD::SETEQ) {
4395 // See if we can use a TBZ to fold in an AND as well.
4396 // TBZ has a smaller branch displacement than CBZ. If the offset is
4397 // out of bounds, a late MI-layer pass rewrites branches.
4398 // 403.gcc is an example that hits this case.
4399 if (LHS.getOpcode() == ISD::AND &&
4400 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4401 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4402 SDValue Test = LHS.getOperand(0);
4403 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004404 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004405 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4406 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004407 }
4408
4409 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4410 } else if (CC == ISD::SETNE) {
4411 // See if we can use a TBZ to fold in an AND as well.
4412 // TBZ has a smaller branch displacement than CBZ. If the offset is
4413 // out of bounds, a late MI-layer pass rewrites branches.
4414 // 403.gcc is an example that hits this case.
4415 if (LHS.getOpcode() == ISD::AND &&
4416 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4417 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4418 SDValue Test = LHS.getOperand(0);
4419 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004420 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004421 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4422 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004423 }
4424
4425 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004426 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4427 // Don't combine AND since emitComparison converts the AND to an ANDS
4428 // (a.k.a. TST) and the test in the test bit and branch instruction
4429 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004430 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004431 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004432 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004433 }
4434 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004435 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4436 LHS.getOpcode() != ISD::AND) {
4437 // Don't combine AND since emitComparison converts the AND to an ANDS
4438 // (a.k.a. TST) and the test in the test bit and branch instruction
4439 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004440 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004441 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004442 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004443 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004444
4445 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004446 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004447 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4448 Cmp);
4449 }
4450
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004451 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4452 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004453
4454 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4455 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004456 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004457 AArch64CC::CondCode CC1, CC2;
4458 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004459 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004460 SDValue BR1 =
4461 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4462 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004463 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004464 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4465 Cmp);
4466 }
4467
4468 return BR1;
4469}
4470
4471SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4472 SelectionDAG &DAG) const {
4473 EVT VT = Op.getValueType();
4474 SDLoc DL(Op);
4475
4476 SDValue In1 = Op.getOperand(0);
4477 SDValue In2 = Op.getOperand(1);
4478 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004479
4480 if (SrcVT.bitsLT(VT))
4481 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4482 else if (SrcVT.bitsGT(VT))
4483 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004484
4485 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004486 uint64_t EltMask;
4487 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004488
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004489 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004490 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004491 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004492 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004493 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004494 DAG.getUNDEF(VecVT), In2);
4495 } else {
4496 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4497 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4498 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004499 };
4500
4501 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4502 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4503 EltMask = 0x80000000ULL;
4504 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004505 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004506 VecVT = MVT::v2i64;
4507
Eric Christopher572e03a2015-06-19 01:53:21 +00004508 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004509 // immediate moves cannot materialize that in a single instruction for
4510 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004511 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004512
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004513 setVecVal(AArch64::dsub);
4514 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4515 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4516 EltMask = 0x8000ULL;
4517 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004518 } else {
4519 llvm_unreachable("Invalid type for copysign!");
4520 }
4521
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004522 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004523
4524 // If we couldn't materialize the mask above, then the mask vector will be
4525 // the zero vector, and we need to negate it here.
4526 if (VT == MVT::f64 || VT == MVT::v2f64) {
4527 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4528 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4529 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4530 }
4531
4532 SDValue Sel =
4533 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4534
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004535 if (VT == MVT::f16)
4536 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004537 if (VT == MVT::f32)
4538 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4539 else if (VT == MVT::f64)
4540 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4541 else
4542 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4543}
4544
4545SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004546 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004547 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004548 return SDValue();
4549
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004550 if (!Subtarget->hasNEON())
4551 return SDValue();
4552
Tim Northover3b0846e2014-05-24 12:50:23 +00004553 // While there is no integer popcount instruction, it can
4554 // be more efficiently lowered to the following sequence that uses
4555 // AdvSIMD registers/instructions as long as the copies to/from
4556 // the AdvSIMD registers are cheap.
4557 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4558 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4559 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4560 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4561 SDValue Val = Op.getOperand(0);
4562 SDLoc DL(Op);
4563 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004564
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004565 if (VT == MVT::i32 || VT == MVT::i64) {
4566 if (VT == MVT::i32)
4567 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4568 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004569
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004570 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4571 SDValue UaddLV = DAG.getNode(
4572 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4573 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004574
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004575 if (VT == MVT::i64)
4576 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4577 return UaddLV;
4578 }
4579
4580 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4581 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4582 "Unexpected type for custom ctpop lowering");
4583
4584 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4585 Val = DAG.getBitcast(VT8Bit, Val);
4586 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4587
4588 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4589 unsigned EltSize = 8;
4590 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4591 while (EltSize != VT.getScalarSizeInBits()) {
4592 EltSize *= 2;
4593 NumElts /= 2;
4594 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4595 Val = DAG.getNode(
4596 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4597 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4598 }
4599
4600 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004601}
4602
4603SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4604
4605 if (Op.getValueType().isVector())
4606 return LowerVSETCC(Op, DAG);
4607
4608 SDValue LHS = Op.getOperand(0);
4609 SDValue RHS = Op.getOperand(1);
4610 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4611 SDLoc dl(Op);
4612
4613 // We chose ZeroOrOneBooleanContents, so use zero and one.
4614 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004615 SDValue TVal = DAG.getConstant(1, dl, VT);
4616 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004617
4618 // Handle f128 first, since one possible outcome is a normal integer
4619 // comparison which gets picked up by the next if statement.
4620 if (LHS.getValueType() == MVT::f128) {
4621 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4622
4623 // If softenSetCCOperands returned a scalar, use it.
4624 if (!RHS.getNode()) {
4625 assert(LHS.getValueType() == Op.getValueType() &&
4626 "Unexpected setcc expansion!");
4627 return LHS;
4628 }
4629 }
4630
4631 if (LHS.getValueType().isInteger()) {
4632 SDValue CCVal;
4633 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004634 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004635
4636 // Note that we inverted the condition above, so we reverse the order of
4637 // the true and false operands here. This will allow the setcc to be
4638 // matched to a single CSINC instruction.
4639 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4640 }
4641
4642 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004643 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4644 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004645
4646 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4647 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004648 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004649
4650 AArch64CC::CondCode CC1, CC2;
4651 changeFPCCToAArch64CC(CC, CC1, CC2);
4652 if (CC2 == AArch64CC::AL) {
4653 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004654 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004655
4656 // Note that we inverted the condition above, so we reverse the order of
4657 // the true and false operands here. This will allow the setcc to be
4658 // matched to a single CSINC instruction.
4659 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4660 } else {
4661 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4662 // totally clean. Some of them require two CSELs to implement. As is in
4663 // this case, we emit the first CSEL and then emit a second using the output
4664 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4665
4666 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004667 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004668 SDValue CS1 =
4669 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4670
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004671 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004672 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4673 }
4674}
4675
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004676SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4677 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004678 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004679 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004680 // Handle f128 first, because it will result in a comparison of some RTLIB
4681 // call result against zero.
4682 if (LHS.getValueType() == MVT::f128) {
4683 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4684
4685 // If softenSetCCOperands returned a scalar, we need to compare the result
4686 // against zero to select between true and false values.
4687 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004688 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004689 CC = ISD::SETNE;
4690 }
4691 }
4692
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004693 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004694 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004695 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4696 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4697 }
4698
4699 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004700 if (LHS.getValueType().isInteger()) {
4701 assert((LHS.getValueType() == RHS.getValueType()) &&
4702 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4703
4704 unsigned Opcode = AArch64ISD::CSEL;
4705
4706 // If both the TVal and the FVal are constants, see if we can swap them in
4707 // order to for a CSINV or CSINC out of them.
4708 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4709 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4710
4711 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4712 std::swap(TVal, FVal);
4713 std::swap(CTVal, CFVal);
4714 CC = ISD::getSetCCInverse(CC, true);
4715 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4716 std::swap(TVal, FVal);
4717 std::swap(CTVal, CFVal);
4718 CC = ISD::getSetCCInverse(CC, true);
4719 } else if (TVal.getOpcode() == ISD::XOR) {
4720 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4721 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004722 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004723 std::swap(TVal, FVal);
4724 std::swap(CTVal, CFVal);
4725 CC = ISD::getSetCCInverse(CC, true);
4726 }
4727 } else if (TVal.getOpcode() == ISD::SUB) {
4728 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4729 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004730 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004731 std::swap(TVal, FVal);
4732 std::swap(CTVal, CFVal);
4733 CC = ISD::getSetCCInverse(CC, true);
4734 }
4735 } else if (CTVal && CFVal) {
4736 const int64_t TrueVal = CTVal->getSExtValue();
4737 const int64_t FalseVal = CFVal->getSExtValue();
4738 bool Swap = false;
4739
4740 // If both TVal and FVal are constants, see if FVal is the
4741 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4742 // instead of a CSEL in that case.
4743 if (TrueVal == ~FalseVal) {
4744 Opcode = AArch64ISD::CSINV;
4745 } else if (TrueVal == -FalseVal) {
4746 Opcode = AArch64ISD::CSNEG;
4747 } else if (TVal.getValueType() == MVT::i32) {
4748 // If our operands are only 32-bit wide, make sure we use 32-bit
4749 // arithmetic for the check whether we can use CSINC. This ensures that
4750 // the addition in the check will wrap around properly in case there is
4751 // an overflow (which would not be the case if we do the check with
4752 // 64-bit arithmetic).
4753 const uint32_t TrueVal32 = CTVal->getZExtValue();
4754 const uint32_t FalseVal32 = CFVal->getZExtValue();
4755
4756 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4757 Opcode = AArch64ISD::CSINC;
4758
4759 if (TrueVal32 > FalseVal32) {
4760 Swap = true;
4761 }
4762 }
4763 // 64-bit check whether we can use CSINC.
4764 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4765 Opcode = AArch64ISD::CSINC;
4766
4767 if (TrueVal > FalseVal) {
4768 Swap = true;
4769 }
4770 }
4771
4772 // Swap TVal and FVal if necessary.
4773 if (Swap) {
4774 std::swap(TVal, FVal);
4775 std::swap(CTVal, CFVal);
4776 CC = ISD::getSetCCInverse(CC, true);
4777 }
4778
4779 if (Opcode != AArch64ISD::CSEL) {
4780 // Drop FVal since we can get its value by simply inverting/negating
4781 // TVal.
4782 FVal = TVal;
4783 }
4784 }
4785
Chad Rosier58f505b2016-08-26 18:05:50 +00004786 // Avoid materializing a constant when possible by reusing a known value in
4787 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004788 // is one, zero or negative one in the case of a CSEL. We can always
4789 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4790 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004791 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4792 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4793 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4794 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4795 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4796 // "a != C ? x : a" to avoid materializing C.
4797 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4798 TVal = LHS;
4799 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4800 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004801 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4802 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4803 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4804 // avoid materializing C.
4805 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4806 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4807 Opcode = AArch64ISD::CSINV;
4808 TVal = LHS;
4809 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4810 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004811 }
4812
Tim Northover3b0846e2014-05-24 12:50:23 +00004813 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004814 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004815 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004816 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4817 }
4818
4819 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004820 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4821 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004822 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004823 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004824 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004825
4826 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4827 // clean. Some of them require two CSELs to implement.
4828 AArch64CC::CondCode CC1, CC2;
4829 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004830
4831 if (DAG.getTarget().Options.UnsafeFPMath) {
4832 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4833 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4834 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4835 if (RHSVal && RHSVal->isZero()) {
4836 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4837 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4838
4839 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004840 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004841 TVal = LHS;
4842 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004843 CFVal && CFVal->isZero() &&
4844 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004845 FVal = LHS;
4846 }
4847 }
4848
4849 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004850 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004851 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4852
4853 // If we need a second CSEL, emit it, using the output of the first as the
4854 // RHS. We're effectively OR'ing the two CC's together.
4855 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004856 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004857 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4858 }
4859
4860 // Otherwise, return the output of the first CSEL.
4861 return CS1;
4862}
4863
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004864SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4865 SelectionDAG &DAG) const {
4866 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4867 SDValue LHS = Op.getOperand(0);
4868 SDValue RHS = Op.getOperand(1);
4869 SDValue TVal = Op.getOperand(2);
4870 SDValue FVal = Op.getOperand(3);
4871 SDLoc DL(Op);
4872 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4873}
4874
4875SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4876 SelectionDAG &DAG) const {
4877 SDValue CCVal = Op->getOperand(0);
4878 SDValue TVal = Op->getOperand(1);
4879 SDValue FVal = Op->getOperand(2);
4880 SDLoc DL(Op);
4881
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004882 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4883 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004884 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004885 // Only lower legal XALUO ops.
4886 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4887 return SDValue();
4888
4889 AArch64CC::CondCode OFCC;
4890 SDValue Value, Overflow;
4891 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004892 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004893
4894 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4895 CCVal, Overflow);
4896 }
4897
4898 // Lower it the same way as we would lower a SELECT_CC node.
4899 ISD::CondCode CC;
4900 SDValue LHS, RHS;
4901 if (CCVal.getOpcode() == ISD::SETCC) {
4902 LHS = CCVal.getOperand(0);
4903 RHS = CCVal.getOperand(1);
4904 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4905 } else {
4906 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004907 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004908 CC = ISD::SETNE;
4909 }
4910 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4911}
4912
Tim Northover3b0846e2014-05-24 12:50:23 +00004913SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4914 SelectionDAG &DAG) const {
4915 // Jump table entries as PC relative offsets. No additional tweaking
4916 // is necessary here. Just get the address of the jump table.
4917 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004918
4919 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4920 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004921 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004922 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4923 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004924 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004925 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004926}
4927
Tim Northover1c353412018-10-24 20:19:09 +00004928SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4929 SelectionDAG &DAG) const {
4930 // Jump table entries as PC relative offsets. No additional tweaking
4931 // is necessary here. Just get the address of the jump table.
4932 SDLoc DL(Op);
4933 SDValue JT = Op.getOperand(1);
4934 SDValue Entry = Op.getOperand(2);
4935 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4936
4937 SDNode *Dest =
4938 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4939 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4940 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4941 SDValue(Dest, 0));
4942}
4943
Tim Northover3b0846e2014-05-24 12:50:23 +00004944SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4945 SelectionDAG &DAG) const {
4946 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004947
4948 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4949 // Use the GOT for the large code model on iOS.
4950 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004951 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004952 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004953 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004954 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4955 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004956 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004957 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004958 }
4959}
4960
4961SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4962 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004963 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004964 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4965 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004966 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004967 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4968 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004969 }
David Green9dd1d452018-08-22 11:31:39 +00004970 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004971}
4972
4973SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4974 SelectionDAG &DAG) const {
4975 AArch64FunctionInfo *FuncInfo =
4976 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4977
4978 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004979 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4980 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004981 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4982 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004983 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004984}
4985
Martin Storsjo68266fa2017-07-13 17:03:12 +00004986SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4987 SelectionDAG &DAG) const {
4988 AArch64FunctionInfo *FuncInfo =
4989 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4990
4991 SDLoc DL(Op);
4992 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4993 ? FuncInfo->getVarArgsGPRIndex()
4994 : FuncInfo->getVarArgsStackIndex(),
4995 getPointerTy(DAG.getDataLayout()));
4996 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4997 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4998 MachinePointerInfo(SV));
4999}
5000
Tim Northover3b0846e2014-05-24 12:50:23 +00005001SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5002 SelectionDAG &DAG) const {
5003 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5004 // Standard, section B.3.
5005 MachineFunction &MF = DAG.getMachineFunction();
5006 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005007 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005008 SDLoc DL(Op);
5009
5010 SDValue Chain = Op.getOperand(0);
5011 SDValue VAList = Op.getOperand(1);
5012 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5013 SmallVector<SDValue, 4> MemOps;
5014
5015 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005016 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005017 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005018 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005019
5020 // void *__gr_top at offset 8
5021 int GPRSize = FuncInfo->getVarArgsGPRSize();
5022 if (GPRSize > 0) {
5023 SDValue GRTop, GRTopAddr;
5024
Mehdi Amini44ede332015-07-09 02:09:04 +00005025 GRTopAddr =
5026 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005027
Mehdi Amini44ede332015-07-09 02:09:04 +00005028 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5029 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5030 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005031
5032 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005033 MachinePointerInfo(SV, 8),
5034 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005035 }
5036
5037 // void *__vr_top at offset 16
5038 int FPRSize = FuncInfo->getVarArgsFPRSize();
5039 if (FPRSize > 0) {
5040 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005041 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5042 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005043
Mehdi Amini44ede332015-07-09 02:09:04 +00005044 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5045 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5046 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005047
5048 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005049 MachinePointerInfo(SV, 16),
5050 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005051 }
5052
5053 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005054 SDValue GROffsAddr =
5055 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005056 MemOps.push_back(DAG.getStore(
5057 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5058 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005059
5060 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005061 SDValue VROffsAddr =
5062 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005063 MemOps.push_back(DAG.getStore(
5064 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5065 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005066
5067 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5068}
5069
5070SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5071 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005072 MachineFunction &MF = DAG.getMachineFunction();
5073
Matthias Braunf1caa282017-12-15 22:22:58 +00005074 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005075 return LowerWin64_VASTART(Op, DAG);
5076 else if (Subtarget->isTargetDarwin())
5077 return LowerDarwin_VASTART(Op, DAG);
5078 else
5079 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005080}
5081
5082SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5083 SelectionDAG &DAG) const {
5084 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5085 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005086 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005087 unsigned VaListSize =
5088 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005089 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5090 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5091
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005092 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5093 Op.getOperand(2),
5094 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005095 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005096 MachinePointerInfo(SrcSV));
5097}
5098
5099SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5100 assert(Subtarget->isTargetDarwin() &&
5101 "automatic va_arg instruction only works on Darwin");
5102
5103 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5104 EVT VT = Op.getValueType();
5105 SDLoc DL(Op);
5106 SDValue Chain = Op.getOperand(0);
5107 SDValue Addr = Op.getOperand(1);
5108 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005109 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005110
Justin Lebar9c375812016-07-15 18:27:10 +00005111 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005112 Chain = VAList.getValue(1);
5113
5114 if (Align > 8) {
5115 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005116 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5117 DAG.getConstant(Align - 1, DL, PtrVT));
5118 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5119 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005120 }
5121
5122 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005123 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005124
5125 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5126 // up to 64 bits. At the very least, we have to increase the striding of the
5127 // vaargs list to match this, and for FP values we need to introduce
5128 // FP_ROUND nodes as well.
5129 if (VT.isInteger() && !VT.isVector())
5130 ArgSize = 8;
5131 bool NeedFPTrunc = false;
5132 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5133 ArgSize = 8;
5134 NeedFPTrunc = true;
5135 }
5136
5137 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005138 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5139 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005140 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005141 SDValue APStore =
5142 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005143
5144 // Load the actual argument out of the pointer VAList
5145 if (NeedFPTrunc) {
5146 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005147 SDValue WideFP =
5148 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005149 // Round the value down to an f32.
5150 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005151 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005152 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5153 // Merge the rounded value with the chain output of the load.
5154 return DAG.getMergeValues(Ops, DL);
5155 }
5156
Justin Lebar9c375812016-07-15 18:27:10 +00005157 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005158}
5159
5160SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5161 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005162 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5163 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005164
5165 EVT VT = Op.getValueType();
5166 SDLoc DL(Op);
5167 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5168 SDValue FrameAddr =
5169 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5170 while (Depth--)
5171 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005172 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005173 return FrameAddr;
5174}
5175
5176// FIXME? Maybe this could be a TableGen attribute on some registers and
5177// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005178unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5179 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005180 unsigned Reg = StringSwitch<unsigned>(RegName)
5181 .Case("sp", AArch64::SP)
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005182 .Case("x1", AArch64::X1)
5183 .Case("w1", AArch64::W1)
5184 .Case("x2", AArch64::X2)
5185 .Case("w2", AArch64::W2)
5186 .Case("x3", AArch64::X3)
5187 .Case("w3", AArch64::W3)
5188 .Case("x4", AArch64::X4)
5189 .Case("w4", AArch64::W4)
5190 .Case("x5", AArch64::X5)
5191 .Case("w5", AArch64::W5)
5192 .Case("x6", AArch64::X6)
5193 .Case("w6", AArch64::W6)
5194 .Case("x7", AArch64::X7)
5195 .Case("w7", AArch64::W7)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005196 .Case("x18", AArch64::X18)
5197 .Case("w18", AArch64::W18)
Petr Hosek72509082018-06-12 20:00:50 +00005198 .Case("x20", AArch64::X20)
5199 .Case("w20", AArch64::W20)
Tim Northover3b0846e2014-05-24 12:50:23 +00005200 .Default(0);
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005201 if (((Reg == AArch64::X1 || Reg == AArch64::W1) &&
5202 !Subtarget->isXRegisterReserved(1)) ||
5203 ((Reg == AArch64::X2 || Reg == AArch64::W2) &&
5204 !Subtarget->isXRegisterReserved(2)) ||
5205 ((Reg == AArch64::X3 || Reg == AArch64::W3) &&
5206 !Subtarget->isXRegisterReserved(3)) ||
5207 ((Reg == AArch64::X4 || Reg == AArch64::W4) &&
5208 !Subtarget->isXRegisterReserved(4)) ||
5209 ((Reg == AArch64::X5 || Reg == AArch64::W5) &&
5210 !Subtarget->isXRegisterReserved(5)) ||
5211 ((Reg == AArch64::X6 || Reg == AArch64::W6) &&
5212 !Subtarget->isXRegisterReserved(6)) ||
5213 ((Reg == AArch64::X7 || Reg == AArch64::W7) &&
5214 !Subtarget->isXRegisterReserved(7)) ||
5215 ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
5216 !Subtarget->isXRegisterReserved(18)) ||
Petr Hosek72509082018-06-12 20:00:50 +00005217 ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005218 !Subtarget->isXRegisterReserved(20)))
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005219 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00005220 if (Reg)
5221 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005222 report_fatal_error(Twine("Invalid register name \""
5223 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005224}
5225
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005226SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5227 SelectionDAG &DAG) const {
5228 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5229
5230 EVT VT = Op.getValueType();
5231 SDLoc DL(Op);
5232
5233 SDValue FrameAddr =
5234 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5235 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5236
5237 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5238}
5239
Tim Northover3b0846e2014-05-24 12:50:23 +00005240SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5241 SelectionDAG &DAG) const {
5242 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005243 MachineFrameInfo &MFI = MF.getFrameInfo();
5244 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005245
5246 EVT VT = Op.getValueType();
5247 SDLoc DL(Op);
5248 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5249 if (Depth) {
5250 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005251 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005252 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5253 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005254 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005255 }
5256
5257 // Return LR, which contains the return address. Mark it an implicit live-in.
5258 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5259 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5260}
5261
5262/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5263/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5264SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5265 SelectionDAG &DAG) const {
5266 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5267 EVT VT = Op.getValueType();
5268 unsigned VTBits = VT.getSizeInBits();
5269 SDLoc dl(Op);
5270 SDValue ShOpLo = Op.getOperand(0);
5271 SDValue ShOpHi = Op.getOperand(1);
5272 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005273 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5274
5275 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5276
5277 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005278 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005279 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5280
5281 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5282 // is "undef". We wanted 0, so CSEL it directly.
5283 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5284 ISD::SETEQ, dl, DAG);
5285 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5286 HiBitsForLo =
5287 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5288 HiBitsForLo, CCVal, Cmp);
5289
Tim Northover3b0846e2014-05-24 12:50:23 +00005290 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005291 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005292
Tim Northoverf3be9d52015-12-02 00:33:54 +00005293 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5294 SDValue LoForNormalShift =
5295 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005296
Tim Northoverf3be9d52015-12-02 00:33:54 +00005297 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5298 dl, DAG);
5299 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5300 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5301 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5302 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005303
5304 // AArch64 shifts larger than the register width are wrapped rather than
5305 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005306 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5307 SDValue HiForBigShift =
5308 Opc == ISD::SRA
5309 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5310 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5311 : DAG.getConstant(0, dl, VT);
5312 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5313 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005314
5315 SDValue Ops[2] = { Lo, Hi };
5316 return DAG.getMergeValues(Ops, dl);
5317}
5318
5319/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5320/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5321SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005322 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005323 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5324 EVT VT = Op.getValueType();
5325 unsigned VTBits = VT.getSizeInBits();
5326 SDLoc dl(Op);
5327 SDValue ShOpLo = Op.getOperand(0);
5328 SDValue ShOpHi = Op.getOperand(1);
5329 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005330
5331 assert(Op.getOpcode() == ISD::SHL_PARTS);
5332 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005333 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005334 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5335
5336 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5337 // is "undef". We wanted 0, so CSEL it directly.
5338 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5339 ISD::SETEQ, dl, DAG);
5340 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5341 LoBitsForHi =
5342 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5343 LoBitsForHi, CCVal, Cmp);
5344
Tim Northover3b0846e2014-05-24 12:50:23 +00005345 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005346 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005347 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5348 SDValue HiForNormalShift =
5349 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005350
Tim Northoverf3be9d52015-12-02 00:33:54 +00005351 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005352
Tim Northoverf3be9d52015-12-02 00:33:54 +00005353 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5354 dl, DAG);
5355 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5356 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5357 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005358
5359 // AArch64 shifts of larger than register sizes are wrapped rather than
5360 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005361 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5362 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5363 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5364 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005365
5366 SDValue Ops[2] = { Lo, Hi };
5367 return DAG.getMergeValues(Ops, dl);
5368}
5369
5370bool AArch64TargetLowering::isOffsetFoldingLegal(
5371 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005372 // Offsets are folded in the DAG combine rather than here so that we can
5373 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005374 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005375}
5376
5377bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
5378 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
5379 // FIXME: We should be able to handle f128 as well with a clever lowering.
Sjoerd Meijer5ea465d2018-02-08 08:39:05 +00005380 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
5381 (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
JF Bastienda339002018-09-05 23:38:11 +00005382 LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString() << " imm value: 0\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005383 return true;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005384 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005385
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005386 bool IsLegal = false;
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00005387 SmallString<128> ImmStrVal;
5388 Imm.toString(ImmStrVal);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005389
JF Bastienda339002018-09-05 23:38:11 +00005390 if (VT == MVT::f64)
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005391 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
JF Bastienda339002018-09-05 23:38:11 +00005392 else if (VT == MVT::f32)
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005393 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
JF Bastienda339002018-09-05 23:38:11 +00005394 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005395 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005396
5397 if (IsLegal) {
JF Bastienda339002018-09-05 23:38:11 +00005398 LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString()
5399 << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005400 return true;
5401 }
5402
JF Bastienda339002018-09-05 23:38:11 +00005403 LLVM_DEBUG(dbgs() << "Illegal " << VT.getEVTString()
5404 << " imm value: " << ImmStrVal << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005405 return false;
5406}
5407
5408//===----------------------------------------------------------------------===//
5409// AArch64 Optimization Hooks
5410//===----------------------------------------------------------------------===//
5411
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005412static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5413 SDValue Operand, SelectionDAG &DAG,
5414 int &ExtraSteps) {
5415 EVT VT = Operand.getValueType();
5416 if (ST->hasNEON() &&
5417 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5418 VT == MVT::f32 || VT == MVT::v1f32 ||
5419 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5420 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5421 // For the reciprocal estimates, convergence is quadratic, so the number
5422 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5423 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5424 // the result for float (23 mantissa bits) is 2 and for double (52
5425 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005426 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005427
5428 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5429 }
5430
5431 return SDValue();
5432}
5433
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005434SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5435 SelectionDAG &DAG, int Enabled,
5436 int &ExtraSteps,
5437 bool &UseOneConst,
5438 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005439 if (Enabled == ReciprocalEstimate::Enabled ||
5440 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5441 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5442 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005443 SDLoc DL(Operand);
5444 EVT VT = Operand.getValueType();
5445
5446 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005447 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005448
5449 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5450 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5451 for (int i = ExtraSteps; i > 0; --i) {
5452 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005453 Flags);
5454 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5455 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005456 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005457 if (!Reciprocal) {
5458 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5459 VT);
5460 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5461 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5462
Amara Emersond28f0cd42017-05-01 15:17:51 +00005463 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005464 // Correct the result if the operand is 0.0.
5465 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5466 VT, Eq, Operand, Estimate);
5467 }
5468
5469 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005470 return Estimate;
5471 }
5472
5473 return SDValue();
5474}
5475
5476SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5477 SelectionDAG &DAG, int Enabled,
5478 int &ExtraSteps) const {
5479 if (Enabled == ReciprocalEstimate::Enabled)
5480 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005481 DAG, ExtraSteps)) {
5482 SDLoc DL(Operand);
5483 EVT VT = Operand.getValueType();
5484
5485 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005486 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005487
5488 // Newton reciprocal iteration: E * (2 - X * E)
5489 // AArch64 reciprocal iteration instruction: (2 - M * N)
5490 for (int i = ExtraSteps; i > 0; --i) {
5491 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005492 Estimate, Flags);
5493 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005494 }
5495
5496 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005497 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005498 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005499
5500 return SDValue();
5501}
5502
Tim Northover3b0846e2014-05-24 12:50:23 +00005503//===----------------------------------------------------------------------===//
5504// AArch64 Inline Assembly Support
5505//===----------------------------------------------------------------------===//
5506
5507// Table of Constraints
5508// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005509// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005510//
5511// r - A general register
5512// w - An FP/SIMD register of some size in the range v0-v31
5513// x - An FP/SIMD register of some size in the range v0-v15
5514// I - Constant that can be used with an ADD instruction
5515// J - Constant that can be used with a SUB instruction
5516// K - Constant that can be used with a 32-bit logical instruction
5517// L - Constant that can be used with a 64-bit logical instruction
5518// M - Constant that can be used as a 32-bit MOV immediate
5519// N - Constant that can be used as a 64-bit MOV immediate
5520// Q - A memory reference with base register and no offset
5521// S - A symbolic address
5522// Y - Floating point constant zero
5523// Z - Integer constant zero
5524//
5525// Note that general register operands will be output using their 64-bit x
5526// register name, whatever the size of the variable, unless the asm operand
5527// is prefixed by the %w modifier. Floating-point and SIMD register operands
5528// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5529// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005530const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5531 // At this point, we have to lower this constraint to something else, so we
5532 // lower it to an "r" or "w". However, by doing this we will force the result
5533 // to be in register, while the X constraint is much more permissive.
5534 //
5535 // Although we are correct (we are free to emit anything, without
5536 // constraints), we might break use cases that would expect us to be more
5537 // efficient and emit something else.
5538 if (!Subtarget->hasFPARMv8())
5539 return "r";
5540
5541 if (ConstraintVT.isFloatingPoint())
5542 return "w";
5543
5544 if (ConstraintVT.isVector() &&
5545 (ConstraintVT.getSizeInBits() == 64 ||
5546 ConstraintVT.getSizeInBits() == 128))
5547 return "w";
5548
5549 return "r";
5550}
Tim Northover3b0846e2014-05-24 12:50:23 +00005551
5552/// getConstraintType - Given a constraint letter, return the type of
5553/// constraint it is for this target.
5554AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005555AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005556 if (Constraint.size() == 1) {
5557 switch (Constraint[0]) {
5558 default:
5559 break;
5560 case 'z':
5561 return C_Other;
5562 case 'x':
5563 case 'w':
5564 return C_RegisterClass;
5565 // An address with a single base register. Due to the way we
5566 // currently handle addresses it is the same as 'r'.
5567 case 'Q':
5568 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005569 case 'S': // A symbolic address
5570 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005571 }
5572 }
5573 return TargetLowering::getConstraintType(Constraint);
5574}
5575
5576/// Examine constraint type and operand type and determine a weight value.
5577/// This object must already have been set up with the operand type
5578/// and the current alternative constraint selected.
5579TargetLowering::ConstraintWeight
5580AArch64TargetLowering::getSingleConstraintMatchWeight(
5581 AsmOperandInfo &info, const char *constraint) const {
5582 ConstraintWeight weight = CW_Invalid;
5583 Value *CallOperandVal = info.CallOperandVal;
5584 // If we don't have a value, we can't do a match,
5585 // but allow it at the lowest weight.
5586 if (!CallOperandVal)
5587 return CW_Default;
5588 Type *type = CallOperandVal->getType();
5589 // Look at the constraint type.
5590 switch (*constraint) {
5591 default:
5592 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5593 break;
5594 case 'x':
5595 case 'w':
5596 if (type->isFloatingPointTy() || type->isVectorTy())
5597 weight = CW_Register;
5598 break;
5599 case 'z':
5600 weight = CW_Constant;
5601 break;
5602 }
5603 return weight;
5604}
5605
5606std::pair<unsigned, const TargetRegisterClass *>
5607AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005608 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005609 if (Constraint.size() == 1) {
5610 switch (Constraint[0]) {
5611 case 'r':
5612 if (VT.getSizeInBits() == 64)
5613 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5614 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5615 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005616 if (!Subtarget->hasFPARMv8())
5617 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005618 if (VT.getSizeInBits() == 16)
5619 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005620 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005621 return std::make_pair(0U, &AArch64::FPR32RegClass);
5622 if (VT.getSizeInBits() == 64)
5623 return std::make_pair(0U, &AArch64::FPR64RegClass);
5624 if (VT.getSizeInBits() == 128)
5625 return std::make_pair(0U, &AArch64::FPR128RegClass);
5626 break;
5627 // The instructions that this constraint is designed for can
5628 // only take 128-bit registers so just use that regclass.
5629 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005630 if (!Subtarget->hasFPARMv8())
5631 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005632 if (VT.getSizeInBits() == 128)
5633 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5634 break;
5635 }
5636 }
5637 if (StringRef("{cc}").equals_lower(Constraint))
5638 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5639
5640 // Use the default implementation in TargetLowering to convert the register
5641 // constraint into a member of a register class.
5642 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005643 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005644
5645 // Not found as a standard register?
5646 if (!Res.second) {
5647 unsigned Size = Constraint.size();
5648 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5649 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005650 int RegNo;
5651 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5652 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005653 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005654 // By default we'll emit v0-v31 for this unless there's a modifier where
5655 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005656 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5657 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5658 Res.second = &AArch64::FPR64RegClass;
5659 } else {
5660 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5661 Res.second = &AArch64::FPR128RegClass;
5662 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005663 }
5664 }
5665 }
5666
Eli Friedman071203b2018-08-24 19:12:13 +00005667 if (Res.second && !Subtarget->hasFPARMv8() &&
5668 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5669 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5670 return std::make_pair(0U, nullptr);
5671
Tim Northover3b0846e2014-05-24 12:50:23 +00005672 return Res;
5673}
5674
5675/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5676/// vector. If it is invalid, don't add anything to Ops.
5677void AArch64TargetLowering::LowerAsmOperandForConstraint(
5678 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5679 SelectionDAG &DAG) const {
5680 SDValue Result;
5681
5682 // Currently only support length 1 constraints.
5683 if (Constraint.length() != 1)
5684 return;
5685
5686 char ConstraintLetter = Constraint[0];
5687 switch (ConstraintLetter) {
5688 default:
5689 break;
5690
5691 // This set of constraints deal with valid constants for various instructions.
5692 // Validate and return a target constant for them if we can.
5693 case 'z': {
5694 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005695 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005696 return;
5697
5698 if (Op.getValueType() == MVT::i64)
5699 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5700 else
5701 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5702 break;
5703 }
Peter Smithc8117582018-05-16 09:33:25 +00005704 case 'S': {
5705 // An absolute symbolic address or label reference.
5706 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5707 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5708 GA->getValueType(0));
5709 } else if (const BlockAddressSDNode *BA =
5710 dyn_cast<BlockAddressSDNode>(Op)) {
5711 Result =
5712 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5713 } else if (const ExternalSymbolSDNode *ES =
5714 dyn_cast<ExternalSymbolSDNode>(Op)) {
5715 Result =
5716 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5717 } else
5718 return;
5719 break;
5720 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005721
5722 case 'I':
5723 case 'J':
5724 case 'K':
5725 case 'L':
5726 case 'M':
5727 case 'N':
5728 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5729 if (!C)
5730 return;
5731
5732 // Grab the value and do some validation.
5733 uint64_t CVal = C->getZExtValue();
5734 switch (ConstraintLetter) {
5735 // The I constraint applies only to simple ADD or SUB immediate operands:
5736 // i.e. 0 to 4095 with optional shift by 12
5737 // The J constraint applies only to ADD or SUB immediates that would be
5738 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5739 // instruction [or vice versa], in other words -1 to -4095 with optional
5740 // left shift by 12.
5741 case 'I':
5742 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5743 break;
5744 return;
5745 case 'J': {
5746 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005747 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5748 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005749 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005750 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005751 return;
5752 }
5753 // The K and L constraints apply *only* to logical immediates, including
5754 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5755 // been removed and MOV should be used). So these constraints have to
5756 // distinguish between bit patterns that are valid 32-bit or 64-bit
5757 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5758 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5759 // versa.
5760 case 'K':
5761 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5762 break;
5763 return;
5764 case 'L':
5765 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5766 break;
5767 return;
5768 // The M and N constraints are a superset of K and L respectively, for use
5769 // with the MOV (immediate) alias. As well as the logical immediates they
5770 // also match 32 or 64-bit immediates that can be loaded either using a
5771 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5772 // (M) or 64-bit 0x1234000000000000 (N) etc.
5773 // As a note some of this code is liberally stolen from the asm parser.
5774 case 'M': {
5775 if (!isUInt<32>(CVal))
5776 return;
5777 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5778 break;
5779 if ((CVal & 0xFFFF) == CVal)
5780 break;
5781 if ((CVal & 0xFFFF0000ULL) == CVal)
5782 break;
5783 uint64_t NCVal = ~(uint32_t)CVal;
5784 if ((NCVal & 0xFFFFULL) == NCVal)
5785 break;
5786 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5787 break;
5788 return;
5789 }
5790 case 'N': {
5791 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5792 break;
5793 if ((CVal & 0xFFFFULL) == CVal)
5794 break;
5795 if ((CVal & 0xFFFF0000ULL) == CVal)
5796 break;
5797 if ((CVal & 0xFFFF00000000ULL) == CVal)
5798 break;
5799 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5800 break;
5801 uint64_t NCVal = ~CVal;
5802 if ((NCVal & 0xFFFFULL) == NCVal)
5803 break;
5804 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5805 break;
5806 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5807 break;
5808 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5809 break;
5810 return;
5811 }
5812 default:
5813 return;
5814 }
5815
5816 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005817 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005818 break;
5819 }
5820
5821 if (Result.getNode()) {
5822 Ops.push_back(Result);
5823 return;
5824 }
5825
5826 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5827}
5828
5829//===----------------------------------------------------------------------===//
5830// AArch64 Advanced SIMD Support
5831//===----------------------------------------------------------------------===//
5832
5833/// WidenVector - Given a value in the V64 register class, produce the
5834/// equivalent value in the V128 register class.
5835static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5836 EVT VT = V64Reg.getValueType();
5837 unsigned NarrowSize = VT.getVectorNumElements();
5838 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5839 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5840 SDLoc DL(V64Reg);
5841
5842 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005843 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005844}
5845
5846/// getExtFactor - Determine the adjustment factor for the position when
5847/// generating an "extract from vector registers" instruction.
5848static unsigned getExtFactor(SDValue &V) {
5849 EVT EltType = V.getValueType().getVectorElementType();
5850 return EltType.getSizeInBits() / 8;
5851}
5852
5853/// NarrowVector - Given a value in the V128 register class, produce the
5854/// equivalent value in the V64 register class.
5855static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5856 EVT VT = V128Reg.getValueType();
5857 unsigned WideSize = VT.getVectorNumElements();
5858 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5859 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5860 SDLoc DL(V128Reg);
5861
5862 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5863}
5864
5865// Gather data to see if the operation can be modelled as a
5866// shuffle in combination with VEXTs.
5867SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5868 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005869 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005870 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005871 SDLoc dl(Op);
5872 EVT VT = Op.getValueType();
5873 unsigned NumElts = VT.getVectorNumElements();
5874
Tim Northover7324e842014-07-24 15:39:55 +00005875 struct ShuffleSourceInfo {
5876 SDValue Vec;
5877 unsigned MinElt;
5878 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005879
Tim Northover7324e842014-07-24 15:39:55 +00005880 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5881 // be compatible with the shuffle we intend to construct. As a result
5882 // ShuffleVec will be some sliding window into the original Vec.
5883 SDValue ShuffleVec;
5884
5885 // Code should guarantee that element i in Vec starts at element "WindowBase
5886 // + i * WindowScale in ShuffleVec".
5887 int WindowBase;
5888 int WindowScale;
5889
Tim Northover7324e842014-07-24 15:39:55 +00005890 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005891 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5892 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5893
5894 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005895 };
5896
5897 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5898 // node.
5899 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005900 for (unsigned i = 0; i < NumElts; ++i) {
5901 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005902 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005903 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005904 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5905 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005906 LLVM_DEBUG(
5907 dbgs() << "Reshuffle failed: "
5908 "a shuffle can only come from building a vector from "
5909 "various elements of other vectors, provided their "
5910 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005911 return SDValue();
5912 }
5913
Tim Northover7324e842014-07-24 15:39:55 +00005914 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005915 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005916 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005917 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005918 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005919
Tim Northover7324e842014-07-24 15:39:55 +00005920 // Update the minimum and maximum lane number seen.
5921 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5922 Source->MinElt = std::min(Source->MinElt, EltNo);
5923 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005924 }
5925
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005926 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005927 LLVM_DEBUG(
5928 dbgs() << "Reshuffle failed: currently only do something sane when at "
5929 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005930 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005931 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005932
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005933 // Find out the smallest element size among result and two sources, and use
5934 // it as element size to build the shuffle_vector.
5935 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005936 for (auto &Source : Sources) {
5937 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005938 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5939 SmallestEltTy = SrcEltTy;
5940 }
5941 }
5942 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005943 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005944 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5945 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005946
Tim Northover7324e842014-07-24 15:39:55 +00005947 // If the source vector is too wide or too narrow, we may nevertheless be able
5948 // to construct a compatible shuffle either by concatenating it with UNDEF or
5949 // extracting a suitable range of elements.
5950 for (auto &Src : Sources) {
5951 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005952
Tim Northover7324e842014-07-24 15:39:55 +00005953 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005954 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005955
5956 // This stage of the search produces a source with the same element type as
5957 // the original, but with a total width matching the BUILD_VECTOR output.
5958 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005959 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5960 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005961
5962 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5963 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005964 // We can pad out the smaller vector for free, so if it's part of a
5965 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005966 Src.ShuffleVec =
5967 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5968 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005969 continue;
5970 }
5971
Tim Northover7324e842014-07-24 15:39:55 +00005972 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005973
James Molloyf497d552014-10-17 17:06:31 +00005974 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005975 LLVM_DEBUG(
5976 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005977 return SDValue();
5978 }
5979
James Molloyf497d552014-10-17 17:06:31 +00005980 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005981 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005982 Src.ShuffleVec =
5983 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005984 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005985 Src.WindowBase = -NumSrcElts;
5986 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005987 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005988 Src.ShuffleVec =
5989 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005990 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005991 } else {
5992 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005993 SDValue VEXTSrc1 =
5994 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005995 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005996 SDValue VEXTSrc2 =
5997 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005998 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005999 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6000
6001 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006002 VEXTSrc2,
6003 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006004 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006005 }
6006 }
6007
Tim Northover7324e842014-07-24 15:39:55 +00006008 // Another possible incompatibility occurs from the vector element types. We
6009 // can fix this by bitcasting the source vectors to the same type we intend
6010 // for the shuffle.
6011 for (auto &Src : Sources) {
6012 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6013 if (SrcEltTy == SmallestEltTy)
6014 continue;
6015 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6016 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6017 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6018 Src.WindowBase *= Src.WindowScale;
6019 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006020
Tim Northover7324e842014-07-24 15:39:55 +00006021 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006022 LLVM_DEBUG(for (auto Src
6023 : Sources)
6024 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006025
6026 // The stars all align, our next step is to produce the mask for the shuffle.
6027 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006028 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006029 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006030 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006031 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006032 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006033
David Majnemer0d955d02016-08-11 22:21:41 +00006034 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006035 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6036
6037 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6038 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6039 // segment.
6040 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006041 int BitsDefined =
6042 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006043 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6044
6045 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6046 // starting at the appropriate offset.
6047 int *LaneMask = &Mask[i * ResMultiplier];
6048
6049 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6050 ExtractBase += NumElts * (Src - Sources.begin());
6051 for (int j = 0; j < LanesDefined; ++j)
6052 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006053 }
6054
6055 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006056 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006057 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006058 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006059 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006060
Tim Northover7324e842014-07-24 15:39:55 +00006061 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6062 for (unsigned i = 0; i < Sources.size(); ++i)
6063 ShuffleOps[i] = Sources[i].ShuffleVec;
6064
6065 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006066 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006067 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6068
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006069 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6070 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006071
6072 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006073}
6074
6075// check if an EXT instruction can handle the shuffle mask when the
6076// vector sources of the shuffle are the same.
6077static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6078 unsigned NumElts = VT.getVectorNumElements();
6079
6080 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6081 if (M[0] < 0)
6082 return false;
6083
6084 Imm = M[0];
6085
6086 // If this is a VEXT shuffle, the immediate value is the index of the first
6087 // element. The other shuffle indices must be the successive elements after
6088 // the first one.
6089 unsigned ExpectedElt = Imm;
6090 for (unsigned i = 1; i < NumElts; ++i) {
6091 // Increment the expected index. If it wraps around, just follow it
6092 // back to index zero and keep going.
6093 ++ExpectedElt;
6094 if (ExpectedElt == NumElts)
6095 ExpectedElt = 0;
6096
6097 if (M[i] < 0)
6098 continue; // ignore UNDEF indices
6099 if (ExpectedElt != static_cast<unsigned>(M[i]))
6100 return false;
6101 }
6102
6103 return true;
6104}
6105
6106// check if an EXT instruction can handle the shuffle mask when the
6107// vector sources of the shuffle are different.
6108static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6109 unsigned &Imm) {
6110 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006111 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006112
6113 // Benefit form APInt to handle overflow when calculating expected element.
6114 unsigned NumElts = VT.getVectorNumElements();
6115 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6116 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6117 // The following shuffle indices must be the successive elements after the
6118 // first real element.
6119 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6120 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6121 if (FirstWrongElt != M.end())
6122 return false;
6123
6124 // The index of an EXT is the first element if it is not UNDEF.
6125 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006126 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006127 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6128 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6129 // ExpectedElt is the last mask index plus 1.
6130 Imm = ExpectedElt.getZExtValue();
6131
6132 // There are two difference cases requiring to reverse input vectors.
6133 // For example, for vector <4 x i32> we have the following cases,
6134 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6135 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6136 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6137 // to reverse two input vectors.
6138 if (Imm < NumElts)
6139 ReverseEXT = true;
6140 else
6141 Imm -= NumElts;
6142
6143 return true;
6144}
6145
6146/// isREVMask - Check if a vector shuffle corresponds to a REV
6147/// instruction with the specified blocksize. (The order of the elements
6148/// within each block of the vector is reversed.)
6149static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6150 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6151 "Only possible block sizes for REV are: 16, 32, 64");
6152
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006153 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006154 if (EltSz == 64)
6155 return false;
6156
6157 unsigned NumElts = VT.getVectorNumElements();
6158 unsigned BlockElts = M[0] + 1;
6159 // If the first shuffle index is UNDEF, be optimistic.
6160 if (M[0] < 0)
6161 BlockElts = BlockSize / EltSz;
6162
6163 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6164 return false;
6165
6166 for (unsigned i = 0; i < NumElts; ++i) {
6167 if (M[i] < 0)
6168 continue; // ignore UNDEF indices
6169 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6170 return false;
6171 }
6172
6173 return true;
6174}
6175
6176static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6177 unsigned NumElts = VT.getVectorNumElements();
6178 WhichResult = (M[0] == 0 ? 0 : 1);
6179 unsigned Idx = WhichResult * NumElts / 2;
6180 for (unsigned i = 0; i != NumElts; i += 2) {
6181 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6182 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6183 return false;
6184 Idx += 1;
6185 }
6186
6187 return true;
6188}
6189
6190static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6191 unsigned NumElts = VT.getVectorNumElements();
6192 WhichResult = (M[0] == 0 ? 0 : 1);
6193 for (unsigned i = 0; i != NumElts; ++i) {
6194 if (M[i] < 0)
6195 continue; // ignore UNDEF indices
6196 if ((unsigned)M[i] != 2 * i + WhichResult)
6197 return false;
6198 }
6199
6200 return true;
6201}
6202
6203static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6204 unsigned NumElts = VT.getVectorNumElements();
6205 WhichResult = (M[0] == 0 ? 0 : 1);
6206 for (unsigned i = 0; i < NumElts; i += 2) {
6207 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6208 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6209 return false;
6210 }
6211 return true;
6212}
6213
6214/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6215/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6216/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6217static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6218 unsigned NumElts = VT.getVectorNumElements();
6219 WhichResult = (M[0] == 0 ? 0 : 1);
6220 unsigned Idx = WhichResult * NumElts / 2;
6221 for (unsigned i = 0; i != NumElts; i += 2) {
6222 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6223 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6224 return false;
6225 Idx += 1;
6226 }
6227
6228 return true;
6229}
6230
6231/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6232/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6233/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6234static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6235 unsigned Half = VT.getVectorNumElements() / 2;
6236 WhichResult = (M[0] == 0 ? 0 : 1);
6237 for (unsigned j = 0; j != 2; ++j) {
6238 unsigned Idx = WhichResult;
6239 for (unsigned i = 0; i != Half; ++i) {
6240 int MIdx = M[i + j * Half];
6241 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6242 return false;
6243 Idx += 2;
6244 }
6245 }
6246
6247 return true;
6248}
6249
6250/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6251/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6252/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6253static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6254 unsigned NumElts = VT.getVectorNumElements();
6255 WhichResult = (M[0] == 0 ? 0 : 1);
6256 for (unsigned i = 0; i < NumElts; i += 2) {
6257 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6258 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6259 return false;
6260 }
6261 return true;
6262}
6263
6264static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6265 bool &DstIsLeft, int &Anomaly) {
6266 if (M.size() != static_cast<size_t>(NumInputElements))
6267 return false;
6268
6269 int NumLHSMatch = 0, NumRHSMatch = 0;
6270 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6271
6272 for (int i = 0; i < NumInputElements; ++i) {
6273 if (M[i] == -1) {
6274 ++NumLHSMatch;
6275 ++NumRHSMatch;
6276 continue;
6277 }
6278
6279 if (M[i] == i)
6280 ++NumLHSMatch;
6281 else
6282 LastLHSMismatch = i;
6283
6284 if (M[i] == i + NumInputElements)
6285 ++NumRHSMatch;
6286 else
6287 LastRHSMismatch = i;
6288 }
6289
6290 if (NumLHSMatch == NumInputElements - 1) {
6291 DstIsLeft = true;
6292 Anomaly = LastLHSMismatch;
6293 return true;
6294 } else if (NumRHSMatch == NumInputElements - 1) {
6295 DstIsLeft = false;
6296 Anomaly = LastRHSMismatch;
6297 return true;
6298 }
6299
6300 return false;
6301}
6302
6303static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6304 if (VT.getSizeInBits() != 128)
6305 return false;
6306
6307 unsigned NumElts = VT.getVectorNumElements();
6308
6309 for (int I = 0, E = NumElts / 2; I != E; I++) {
6310 if (Mask[I] != I)
6311 return false;
6312 }
6313
6314 int Offset = NumElts / 2;
6315 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6316 if (Mask[I] != I + SplitLHS * Offset)
6317 return false;
6318 }
6319
6320 return true;
6321}
6322
6323static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6324 SDLoc DL(Op);
6325 EVT VT = Op.getValueType();
6326 SDValue V0 = Op.getOperand(0);
6327 SDValue V1 = Op.getOperand(1);
6328 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6329
6330 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6331 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6332 return SDValue();
6333
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006334 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006335
6336 if (!isConcatMask(Mask, VT, SplitV0))
6337 return SDValue();
6338
6339 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6340 VT.getVectorNumElements() / 2);
6341 if (SplitV0) {
6342 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006343 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006344 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006345 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006346 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006347 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006348 }
6349 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6350}
6351
6352/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6353/// the specified operations to build the shuffle.
6354static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6355 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006356 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006357 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6358 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6359 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6360
6361 enum {
6362 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6363 OP_VREV,
6364 OP_VDUP0,
6365 OP_VDUP1,
6366 OP_VDUP2,
6367 OP_VDUP3,
6368 OP_VEXT1,
6369 OP_VEXT2,
6370 OP_VEXT3,
6371 OP_VUZPL, // VUZP, left result
6372 OP_VUZPR, // VUZP, right result
6373 OP_VZIPL, // VZIP, left result
6374 OP_VZIPR, // VZIP, right result
6375 OP_VTRNL, // VTRN, left result
6376 OP_VTRNR // VTRN, right result
6377 };
6378
6379 if (OpNum == OP_COPY) {
6380 if (LHSID == (1 * 9 + 2) * 9 + 3)
6381 return LHS;
6382 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6383 return RHS;
6384 }
6385
6386 SDValue OpLHS, OpRHS;
6387 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6388 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6389 EVT VT = OpLHS.getValueType();
6390
6391 switch (OpNum) {
6392 default:
6393 llvm_unreachable("Unknown shuffle opcode!");
6394 case OP_VREV:
6395 // VREV divides the vector in half and swaps within the half.
6396 if (VT.getVectorElementType() == MVT::i32 ||
6397 VT.getVectorElementType() == MVT::f32)
6398 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6399 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006400 if (VT.getVectorElementType() == MVT::i16 ||
6401 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006402 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6403 // vrev <4 x i8> -> REV16
6404 assert(VT.getVectorElementType() == MVT::i8);
6405 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6406 case OP_VDUP0:
6407 case OP_VDUP1:
6408 case OP_VDUP2:
6409 case OP_VDUP3: {
6410 EVT EltTy = VT.getVectorElementType();
6411 unsigned Opcode;
6412 if (EltTy == MVT::i8)
6413 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006414 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006415 Opcode = AArch64ISD::DUPLANE16;
6416 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6417 Opcode = AArch64ISD::DUPLANE32;
6418 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6419 Opcode = AArch64ISD::DUPLANE64;
6420 else
6421 llvm_unreachable("Invalid vector element type?");
6422
6423 if (VT.getSizeInBits() == 64)
6424 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006425 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006426 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6427 }
6428 case OP_VEXT1:
6429 case OP_VEXT2:
6430 case OP_VEXT3: {
6431 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6432 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006433 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006434 }
6435 case OP_VUZPL:
6436 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6437 OpRHS);
6438 case OP_VUZPR:
6439 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6440 OpRHS);
6441 case OP_VZIPL:
6442 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6443 OpRHS);
6444 case OP_VZIPR:
6445 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6446 OpRHS);
6447 case OP_VTRNL:
6448 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6449 OpRHS);
6450 case OP_VTRNR:
6451 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6452 OpRHS);
6453 }
6454}
6455
6456static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6457 SelectionDAG &DAG) {
6458 // Check to see if we can use the TBL instruction.
6459 SDValue V1 = Op.getOperand(0);
6460 SDValue V2 = Op.getOperand(1);
6461 SDLoc DL(Op);
6462
6463 EVT EltVT = Op.getValueType().getVectorElementType();
6464 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6465
6466 SmallVector<SDValue, 8> TBLMask;
6467 for (int Val : ShuffleMask) {
6468 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6469 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006470 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006471 }
6472 }
6473
6474 MVT IndexVT = MVT::v8i8;
6475 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006476 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006477 IndexVT = MVT::v16i8;
6478 IndexLen = 16;
6479 }
6480
6481 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6482 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6483
6484 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006485 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006486 if (IndexLen == 8)
6487 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6488 Shuffle = DAG.getNode(
6489 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006490 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006491 DAG.getBuildVector(IndexVT, DL,
6492 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006493 } else {
6494 if (IndexLen == 8) {
6495 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6496 Shuffle = DAG.getNode(
6497 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006498 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006499 DAG.getBuildVector(IndexVT, DL,
6500 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006501 } else {
6502 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6503 // cannot currently represent the register constraints on the input
6504 // table registers.
6505 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006506 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6507 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006508 Shuffle = DAG.getNode(
6509 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006510 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6511 V2Cst, DAG.getBuildVector(IndexVT, DL,
6512 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006513 }
6514 }
6515 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6516}
6517
6518static unsigned getDUPLANEOp(EVT EltType) {
6519 if (EltType == MVT::i8)
6520 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006521 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006522 return AArch64ISD::DUPLANE16;
6523 if (EltType == MVT::i32 || EltType == MVT::f32)
6524 return AArch64ISD::DUPLANE32;
6525 if (EltType == MVT::i64 || EltType == MVT::f64)
6526 return AArch64ISD::DUPLANE64;
6527
6528 llvm_unreachable("Invalid vector element type?");
6529}
6530
6531SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6532 SelectionDAG &DAG) const {
6533 SDLoc dl(Op);
6534 EVT VT = Op.getValueType();
6535
6536 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6537
6538 // Convert shuffles that are directly supported on NEON to target-specific
6539 // DAG nodes, instead of keeping them as shuffles and matching them again
6540 // during code selection. This is more efficient and avoids the possibility
6541 // of inconsistencies between legalization and selection.
6542 ArrayRef<int> ShuffleMask = SVN->getMask();
6543
6544 SDValue V1 = Op.getOperand(0);
6545 SDValue V2 = Op.getOperand(1);
6546
Craig Topperbc56e3b2016-06-30 04:38:51 +00006547 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006548 int Lane = SVN->getSplatIndex();
6549 // If this is undef splat, generate it via "just" vdup, if possible.
6550 if (Lane == -1)
6551 Lane = 0;
6552
6553 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6554 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6555 V1.getOperand(0));
6556 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6557 // constant. If so, we can just reference the lane's definition directly.
6558 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6559 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6560 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6561
6562 // Otherwise, duplicate from the lane of the input vector.
6563 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6564
6565 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6566 // to make a vector of the same size as this SHUFFLE. We can ignore the
6567 // extract entirely, and canonicalise the concat using WidenVector.
6568 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6569 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6570 V1 = V1.getOperand(0);
6571 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6572 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6573 Lane -= Idx * VT.getVectorNumElements() / 2;
6574 V1 = WidenVector(V1.getOperand(Idx), DAG);
6575 } else if (VT.getSizeInBits() == 64)
6576 V1 = WidenVector(V1, DAG);
6577
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006578 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006579 }
6580
6581 if (isREVMask(ShuffleMask, VT, 64))
6582 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6583 if (isREVMask(ShuffleMask, VT, 32))
6584 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6585 if (isREVMask(ShuffleMask, VT, 16))
6586 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6587
6588 bool ReverseEXT = false;
6589 unsigned Imm;
6590 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6591 if (ReverseEXT)
6592 std::swap(V1, V2);
6593 Imm *= getExtFactor(V1);
6594 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006595 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006596 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006597 Imm *= getExtFactor(V1);
6598 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006599 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006600 }
6601
6602 unsigned WhichResult;
6603 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6604 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6605 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6606 }
6607 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6608 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6609 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6610 }
6611 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6612 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6613 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6614 }
6615
6616 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6617 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6618 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6619 }
6620 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6621 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6622 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6623 }
6624 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6625 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6626 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6627 }
6628
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006629 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006630 return Concat;
6631
6632 bool DstIsLeft;
6633 int Anomaly;
6634 int NumInputElements = V1.getValueType().getVectorNumElements();
6635 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6636 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006637 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006638
6639 SDValue SrcVec = V1;
6640 int SrcLane = ShuffleMask[Anomaly];
6641 if (SrcLane >= NumInputElements) {
6642 SrcVec = V2;
6643 SrcLane -= VT.getVectorNumElements();
6644 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006645 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006646
6647 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006648
6649 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006650 ScalarVT = MVT::i32;
6651
6652 return DAG.getNode(
6653 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6654 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6655 DstLaneV);
6656 }
6657
6658 // If the shuffle is not directly supported and it has 4 elements, use
6659 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6660 unsigned NumElts = VT.getVectorNumElements();
6661 if (NumElts == 4) {
6662 unsigned PFIndexes[4];
6663 for (unsigned i = 0; i != 4; ++i) {
6664 if (ShuffleMask[i] < 0)
6665 PFIndexes[i] = 8;
6666 else
6667 PFIndexes[i] = ShuffleMask[i];
6668 }
6669
6670 // Compute the index in the perfect shuffle table.
6671 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6672 PFIndexes[2] * 9 + PFIndexes[3];
6673 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6674 unsigned Cost = (PFEntry >> 30);
6675
6676 if (Cost <= 4)
6677 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6678 }
6679
6680 return GenerateTBL(Op, ShuffleMask, DAG);
6681}
6682
6683static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6684 APInt &UndefBits) {
6685 EVT VT = BVN->getValueType(0);
6686 APInt SplatBits, SplatUndef;
6687 unsigned SplatBitSize;
6688 bool HasAnyUndefs;
6689 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6690 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6691
6692 for (unsigned i = 0; i < NumSplats; ++i) {
6693 CnstBits <<= SplatBitSize;
6694 UndefBits <<= SplatBitSize;
6695 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6696 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6697 }
6698
6699 return true;
6700 }
6701
6702 return false;
6703}
6704
Evandro Menezes72f39832018-02-20 20:31:45 +00006705// Try 64-bit splatted SIMD immediate.
6706static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6707 const APInt &Bits) {
6708 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6709 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6710 EVT VT = Op.getValueType();
6711 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6712
6713 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6714 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6715
6716 SDLoc dl(Op);
6717 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6718 DAG.getConstant(Value, dl, MVT::i32));
6719 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6720 }
6721 }
6722
6723 return SDValue();
6724}
6725
6726// Try 32-bit splatted SIMD immediate.
6727static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6728 const APInt &Bits,
6729 const SDValue *LHS = nullptr) {
6730 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6731 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6732 EVT VT = Op.getValueType();
6733 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6734 bool isAdvSIMDModImm = false;
6735 uint64_t Shift;
6736
6737 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6738 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6739 Shift = 0;
6740 }
6741 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6742 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6743 Shift = 8;
6744 }
6745 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6746 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6747 Shift = 16;
6748 }
6749 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6750 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6751 Shift = 24;
6752 }
6753
6754 if (isAdvSIMDModImm) {
6755 SDLoc dl(Op);
6756 SDValue Mov;
6757
6758 if (LHS)
6759 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6760 DAG.getConstant(Value, dl, MVT::i32),
6761 DAG.getConstant(Shift, dl, MVT::i32));
6762 else
6763 Mov = DAG.getNode(NewOp, dl, MovTy,
6764 DAG.getConstant(Value, dl, MVT::i32),
6765 DAG.getConstant(Shift, dl, MVT::i32));
6766
6767 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6768 }
6769 }
6770
6771 return SDValue();
6772}
6773
6774// Try 16-bit splatted SIMD immediate.
6775static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6776 const APInt &Bits,
6777 const SDValue *LHS = nullptr) {
6778 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6779 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6780 EVT VT = Op.getValueType();
6781 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6782 bool isAdvSIMDModImm = false;
6783 uint64_t Shift;
6784
6785 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6786 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6787 Shift = 0;
6788 }
6789 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6790 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6791 Shift = 8;
6792 }
6793
6794 if (isAdvSIMDModImm) {
6795 SDLoc dl(Op);
6796 SDValue Mov;
6797
6798 if (LHS)
6799 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006800 DAG.getConstant(Value, dl, MVT::i32),
6801 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006802 else
6803 Mov = DAG.getNode(NewOp, dl, MovTy,
6804 DAG.getConstant(Value, dl, MVT::i32),
6805 DAG.getConstant(Shift, dl, MVT::i32));
6806
6807 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6808 }
6809 }
6810
6811 return SDValue();
6812}
6813
6814// Try 32-bit splatted SIMD immediate with shifted ones.
6815static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6816 SelectionDAG &DAG, const APInt &Bits) {
6817 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6818 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6819 EVT VT = Op.getValueType();
6820 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6821 bool isAdvSIMDModImm = false;
6822 uint64_t Shift;
6823
6824 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6825 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6826 Shift = 264;
6827 }
6828 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6829 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6830 Shift = 272;
6831 }
6832
6833 if (isAdvSIMDModImm) {
6834 SDLoc dl(Op);
6835 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6836 DAG.getConstant(Value, dl, MVT::i32),
6837 DAG.getConstant(Shift, dl, MVT::i32));
6838 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6839 }
6840 }
6841
6842 return SDValue();
6843}
6844
6845// Try 8-bit splatted SIMD immediate.
6846static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6847 const APInt &Bits) {
6848 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6849 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6850 EVT VT = Op.getValueType();
6851 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6852
6853 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6854 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6855
6856 SDLoc dl(Op);
6857 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6858 DAG.getConstant(Value, dl, MVT::i32));
6859 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6860 }
6861 }
6862
6863 return SDValue();
6864}
6865
6866// Try FP splatted SIMD immediate.
6867static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6868 const APInt &Bits) {
6869 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6870 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6871 EVT VT = Op.getValueType();
6872 bool isWide = (VT.getSizeInBits() == 128);
6873 MVT MovTy;
6874 bool isAdvSIMDModImm = false;
6875
6876 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6877 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6878 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6879 }
6880 else if (isWide &&
6881 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6882 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6883 MovTy = MVT::v2f64;
6884 }
6885
6886 if (isAdvSIMDModImm) {
6887 SDLoc dl(Op);
6888 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6889 DAG.getConstant(Value, dl, MVT::i32));
6890 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6891 }
6892 }
6893
6894 return SDValue();
6895}
6896
Tim Northover3b0846e2014-05-24 12:50:23 +00006897SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6898 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006899 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006900 EVT VT = Op.getValueType();
6901
Evandro Menezes72f39832018-02-20 20:31:45 +00006902 BuildVectorSDNode *BVN =
6903 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6904 if (!BVN) {
6905 // AND commutes, so try swapping the operands.
6906 LHS = Op.getOperand(1);
6907 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6908 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006909 if (!BVN)
6910 return Op;
6911
Evandro Menezes72f39832018-02-20 20:31:45 +00006912 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006913 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006914 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6915 SDValue NewOp;
6916
Tim Northover3b0846e2014-05-24 12:50:23 +00006917 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006918 DefBits = ~DefBits;
6919 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6920 DefBits, &LHS)) ||
6921 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6922 DefBits, &LHS)))
6923 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006924
6925 UndefBits = ~UndefBits;
6926 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6927 UndefBits, &LHS)) ||
6928 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6929 UndefBits, &LHS)))
6930 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006931 }
6932
Evandro Menezes72f39832018-02-20 20:31:45 +00006933 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006934 return Op;
6935}
6936
6937// Specialized code to quickly find if PotentialBVec is a BuildVector that
6938// consists of only the same constant int value, returned in reference arg
6939// ConstVal
6940static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6941 uint64_t &ConstVal) {
6942 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6943 if (!Bvec)
6944 return false;
6945 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6946 if (!FirstElt)
6947 return false;
6948 EVT VT = Bvec->getValueType(0);
6949 unsigned NumElts = VT.getVectorNumElements();
6950 for (unsigned i = 1; i < NumElts; ++i)
6951 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6952 return false;
6953 ConstVal = FirstElt->getZExtValue();
6954 return true;
6955}
6956
6957static unsigned getIntrinsicID(const SDNode *N) {
6958 unsigned Opcode = N->getOpcode();
6959 switch (Opcode) {
6960 default:
6961 return Intrinsic::not_intrinsic;
6962 case ISD::INTRINSIC_WO_CHAIN: {
6963 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6964 if (IID < Intrinsic::num_intrinsics)
6965 return IID;
6966 return Intrinsic::not_intrinsic;
6967 }
6968 }
6969}
6970
6971// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6972// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6973// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6974// Also, logical shift right -> sri, with the same structure.
6975static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6976 EVT VT = N->getValueType(0);
6977
6978 if (!VT.isVector())
6979 return SDValue();
6980
6981 SDLoc DL(N);
6982
6983 // Is the first op an AND?
6984 const SDValue And = N->getOperand(0);
6985 if (And.getOpcode() != ISD::AND)
6986 return SDValue();
6987
6988 // Is the second op an shl or lshr?
6989 SDValue Shift = N->getOperand(1);
6990 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6991 // or AArch64ISD::VLSHR vector, #shift
6992 unsigned ShiftOpc = Shift.getOpcode();
6993 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6994 return SDValue();
6995 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6996
6997 // Is the shift amount constant?
6998 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6999 if (!C2node)
7000 return SDValue();
7001
7002 // Is the and mask vector all constant?
7003 uint64_t C1;
7004 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7005 return SDValue();
7006
7007 // Is C1 == ~C2, taking into account how much one can shift elements of a
7008 // particular size?
7009 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007010 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007011 if (C2 > ElemSizeInBits)
7012 return SDValue();
7013 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7014 if ((C1 & ElemMask) != (~C2 & ElemMask))
7015 return SDValue();
7016
7017 SDValue X = And.getOperand(0);
7018 SDValue Y = Shift.getOperand(0);
7019
7020 unsigned Intrin =
7021 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7022 SDValue ResultSLI =
7023 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007024 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7025 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007026
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007027 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7028 LLVM_DEBUG(N->dump(&DAG));
7029 LLVM_DEBUG(dbgs() << "into: \n");
7030 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007031
7032 ++NumShiftInserts;
7033 return ResultSLI;
7034}
7035
7036SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7037 SelectionDAG &DAG) const {
7038 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7039 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007040 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007041 return Res;
7042 }
7043
Tim Northover3b0846e2014-05-24 12:50:23 +00007044 EVT VT = Op.getValueType();
7045
Evandro Menezescd855f72018-03-05 17:02:47 +00007046 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007047 BuildVectorSDNode *BVN =
7048 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007049 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007050 // OR commutes, so try swapping the operands.
7051 LHS = Op.getOperand(1);
7052 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007053 }
7054 if (!BVN)
7055 return Op;
7056
Evandro Menezes72f39832018-02-20 20:31:45 +00007057 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007058 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007059 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7060 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007061
Evandro Menezes72f39832018-02-20 20:31:45 +00007062 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7063 DefBits, &LHS)) ||
7064 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7065 DefBits, &LHS)))
7066 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007067
7068 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7069 UndefBits, &LHS)) ||
7070 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7071 UndefBits, &LHS)))
7072 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007073 }
7074
Evandro Menezes72f39832018-02-20 20:31:45 +00007075 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007076 return Op;
7077}
7078
Kevin Qin4473c192014-07-07 02:45:40 +00007079// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7080// be truncated to fit element width.
7081static SDValue NormalizeBuildVector(SDValue Op,
7082 SelectionDAG &DAG) {
7083 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007084 SDLoc dl(Op);
7085 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007086 EVT EltTy= VT.getVectorElementType();
7087
7088 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7089 return Op;
7090
7091 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007092 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007093 // For integer vectors, type legalization would have promoted the
7094 // operands already. Otherwise, if Op is a floating-point splat
7095 // (with operands cast to integers), then the only possibilities
7096 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007097 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007098 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007099 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007100 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007101 } else if (Lane.getNode()->isUndef()) {
7102 Lane = DAG.getUNDEF(MVT::i32);
7103 } else {
7104 assert(Lane.getValueType() == MVT::i32 &&
7105 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007106 }
7107 Ops.push_back(Lane);
7108 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007109 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007110}
7111
Evandro Menezescd855f72018-03-05 17:02:47 +00007112static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007113 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007114
Evandro Menezes72f39832018-02-20 20:31:45 +00007115 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007116 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007117 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007118 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007119 SDValue NewOp;
7120 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7121 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7122 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7123 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7124 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7125 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7126 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007127
Evandro Menezes72f39832018-02-20 20:31:45 +00007128 DefBits = ~DefBits;
7129 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7130 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7131 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7132 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007133
Evandro Menezes72f39832018-02-20 20:31:45 +00007134 DefBits = UndefBits;
7135 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7136 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7137 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7138 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7139 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7140 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7141 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007142
Evandro Menezes72f39832018-02-20 20:31:45 +00007143 DefBits = ~UndefBits;
7144 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7145 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7146 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7147 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007148 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007149
Evandro Menezescd855f72018-03-05 17:02:47 +00007150 return SDValue();
7151}
7152
7153SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7154 SelectionDAG &DAG) const {
7155 EVT VT = Op.getValueType();
7156
7157 // Try to build a simple constant vector.
7158 Op = NormalizeBuildVector(Op, DAG);
7159 if (VT.isInteger()) {
7160 // Certain vector constants, used to express things like logical NOT and
7161 // arithmetic NEG, are passed through unmodified. This allows special
7162 // patterns for these operations to match, which will lower these constants
7163 // to whatever is proven necessary.
7164 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7165 if (BVN->isConstant())
7166 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7167 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7168 APInt Val(BitSize,
7169 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7170 if (Val.isNullValue() || Val.isAllOnesValue())
7171 return Op;
7172 }
7173 }
7174
7175 if (SDValue V = ConstantBuildVector(Op, DAG))
7176 return V;
7177
Tim Northover3b0846e2014-05-24 12:50:23 +00007178 // Scan through the operands to find some interesting properties we can
7179 // exploit:
7180 // 1) If only one value is used, we can use a DUP, or
7181 // 2) if only the low element is not undef, we can just insert that, or
7182 // 3) if only one constant value is used (w/ some non-constant lanes),
7183 // we can splat the constant value into the whole vector then fill
7184 // in the non-constant lanes.
7185 // 4) FIXME: If different constant values are used, but we can intelligently
7186 // select the values we'll be overwriting for the non-constant
7187 // lanes such that we can directly materialize the vector
7188 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007189 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007190 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007191 unsigned NumElts = VT.getVectorNumElements();
7192 bool isOnlyLowElement = true;
7193 bool usesOnlyOneValue = true;
7194 bool usesOnlyOneConstantValue = true;
7195 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007196 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007197 unsigned NumConstantLanes = 0;
7198 SDValue Value;
7199 SDValue ConstantValue;
7200 for (unsigned i = 0; i < NumElts; ++i) {
7201 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007202 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7203 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007204 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007205 continue;
7206 if (i > 0)
7207 isOnlyLowElement = false;
7208 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7209 isConstant = false;
7210
7211 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7212 ++NumConstantLanes;
7213 if (!ConstantValue.getNode())
7214 ConstantValue = V;
7215 else if (ConstantValue != V)
7216 usesOnlyOneConstantValue = false;
7217 }
7218
7219 if (!Value.getNode())
7220 Value = V;
7221 else if (V != Value)
7222 usesOnlyOneValue = false;
7223 }
7224
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007225 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007226 LLVM_DEBUG(
7227 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007228 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007229 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007230
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007231 if (isOnlyLowElement) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007232 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7233 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007234 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007235 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007236
Sebastian Popc33af712018-03-01 15:47:39 +00007237 if (AllLanesExtractElt) {
7238 SDNode *Vector = nullptr;
7239 bool Even = false;
7240 bool Odd = false;
7241 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7242 // the Odd pattern <1,3,5,...>.
7243 for (unsigned i = 0; i < NumElts; ++i) {
7244 SDValue V = Op.getOperand(i);
7245 const SDNode *N = V.getNode();
7246 if (!isa<ConstantSDNode>(N->getOperand(1)))
7247 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007248 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007249
7250 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007251 if (!Vector) {
7252 Vector = N0.getNode();
7253 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7254 // BUILD_VECTOR.
7255 if (VT.getVectorElementType() !=
7256 N0.getValueType().getVectorElementType())
7257 break;
7258 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007259 Odd = false;
7260 Even = false;
7261 break;
7262 }
7263
7264 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7265 // indices <1,3,5,...>.
7266 uint64_t Val = N->getConstantOperandVal(1);
7267 if (Val == 2 * i) {
7268 Even = true;
7269 continue;
7270 }
7271 if (Val - 1 == 2 * i) {
7272 Odd = true;
7273 continue;
7274 }
7275
7276 // Something does not match: abort.
7277 Odd = false;
7278 Even = false;
7279 break;
7280 }
7281 if (Even || Odd) {
7282 SDValue LHS =
7283 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7284 DAG.getConstant(0, dl, MVT::i64));
7285 SDValue RHS =
7286 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7287 DAG.getConstant(NumElts, dl, MVT::i64));
7288
7289 if (Even && !Odd)
7290 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7291 RHS);
7292 if (Odd && !Even)
7293 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7294 RHS);
7295 }
7296 }
7297
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007298 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007299 // i32 and try again.
7300 if (usesOnlyOneValue) {
7301 if (!isConstant) {
7302 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007303 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007304 LLVM_DEBUG(
7305 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007306 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007307 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007308
7309 // This is actually a DUPLANExx operation, which keeps everything vectory.
7310
Tim Northover3b0846e2014-05-24 12:50:23 +00007311 SDValue Lane = Value.getOperand(1);
7312 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007313 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007314 LLVM_DEBUG(
7315 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7316 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007317 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007318 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007319
7320 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7321 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7322 }
7323
7324 if (VT.getVectorElementType().isFloatingPoint()) {
7325 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007326 EVT EltTy = VT.getVectorElementType();
7327 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7328 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007329 LLVM_DEBUG(
7330 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7331 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007332 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007333 for (unsigned i = 0; i < NumElts; ++i)
7334 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7335 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007336 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007337 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7338 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007339 Val = LowerBUILD_VECTOR(Val, DAG);
7340 if (Val.getNode())
7341 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7342 }
7343 }
7344
7345 // If there was only one constant value used and for more than one lane,
7346 // start by splatting that value, then replace the non-constant lanes. This
7347 // is better than the default, which will perform a separate initialization
7348 // for each lane.
7349 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007350 // Firstly, try to materialize the splat constant.
7351 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7352 Val = ConstantBuildVector(Vec, DAG);
7353 if (!Val) {
7354 // Otherwise, materialize the constant and splat it.
7355 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7356 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7357 }
7358
Tim Northover3b0846e2014-05-24 12:50:23 +00007359 // Now insert the non-constant lanes.
7360 for (unsigned i = 0; i < NumElts; ++i) {
7361 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007362 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007363 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007364 // Note that type legalization likely mucked about with the VT of the
7365 // source operand, so we may have to convert it here before inserting.
7366 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007367 }
7368 return Val;
7369 }
7370
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007371 // This will generate a load from the constant pool.
7372 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007373 LLVM_DEBUG(
7374 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7375 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007376 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007377 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007378
7379 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7380 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007381 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007382 return shuffle;
7383 }
7384
7385 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7386 // know the default expansion would otherwise fall back on something even
7387 // worse. For a vector with one or two non-undef values, that's
7388 // scalar_to_vector for the elements followed by a shuffle (provided the
7389 // shuffle is valid for the target) and materialization element by element
7390 // on the stack followed by a load for everything else.
7391 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007392 LLVM_DEBUG(
7393 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7394 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007395
Tim Northover3b0846e2014-05-24 12:50:23 +00007396 SDValue Vec = DAG.getUNDEF(VT);
7397 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007398 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007399
7400 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007401 // a) Avoid a RMW dependency on the full vector register, and
7402 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007403 // value is already in an S or D register, and we're forced to emit an
7404 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007405 //
7406 // We also allow types like i8 and i16 which are illegal scalar but legal
7407 // vector element types. After type-legalization the inserted value is
7408 // extended (i32) and it is safe to cast them to the vector type by ignoring
7409 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7410 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007411 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007412 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007413 ++i;
7414 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007415 LLVM_DEBUG(if (i < NumElts) dbgs()
7416 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007417 for (; i < NumElts; ++i) {
7418 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007419 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007420 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007421 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007422 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7423 }
7424 return Vec;
7425 }
7426
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007427 LLVM_DEBUG(
7428 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7429 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007430 return SDValue();
7431}
7432
7433SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7434 SelectionDAG &DAG) const {
7435 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7436
Tim Northovere4b8e132014-07-15 10:00:26 +00007437 // Check for non-constant or out of range lane.
7438 EVT VT = Op.getOperand(0).getValueType();
7439 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7440 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007441 return SDValue();
7442
Tim Northover3b0846e2014-05-24 12:50:23 +00007443
7444 // Insertion/extraction are legal for V128 types.
7445 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007446 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7447 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007448 return Op;
7449
7450 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007451 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007452 return SDValue();
7453
7454 // For V64 types, we perform insertion by expanding the value
7455 // to a V128 type and perform the insertion on that.
7456 SDLoc DL(Op);
7457 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7458 EVT WideTy = WideVec.getValueType();
7459
7460 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7461 Op.getOperand(1), Op.getOperand(2));
7462 // Re-narrow the resultant vector.
7463 return NarrowVector(Node, DAG);
7464}
7465
7466SDValue
7467AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7468 SelectionDAG &DAG) const {
7469 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7470
Tim Northovere4b8e132014-07-15 10:00:26 +00007471 // Check for non-constant or out of range lane.
7472 EVT VT = Op.getOperand(0).getValueType();
7473 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7474 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007475 return SDValue();
7476
Tim Northover3b0846e2014-05-24 12:50:23 +00007477
7478 // Insertion/extraction are legal for V128 types.
7479 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007480 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7481 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007482 return Op;
7483
7484 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007485 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007486 return SDValue();
7487
7488 // For V64 types, we perform extraction by expanding the value
7489 // to a V128 type and perform the extraction on that.
7490 SDLoc DL(Op);
7491 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7492 EVT WideTy = WideVec.getValueType();
7493
7494 EVT ExtrTy = WideTy.getVectorElementType();
7495 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7496 ExtrTy = MVT::i32;
7497
7498 // For extractions, we just return the result directly.
7499 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7500 Op.getOperand(1));
7501}
7502
7503SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7504 SelectionDAG &DAG) const {
7505 EVT VT = Op.getOperand(0).getValueType();
7506 SDLoc dl(Op);
7507 // Just in case...
7508 if (!VT.isVector())
7509 return SDValue();
7510
7511 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7512 if (!Cst)
7513 return SDValue();
7514 unsigned Val = Cst->getZExtValue();
7515
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007516 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007517
7518 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7519 if (Val == 0)
7520 return Op;
7521
Tim Northover3b0846e2014-05-24 12:50:23 +00007522 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7523 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007524 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007525 return Op;
7526
7527 return SDValue();
7528}
7529
Zvi Rackover1b736822017-07-26 08:06:58 +00007530bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007531 if (VT.getVectorNumElements() == 4 &&
7532 (VT.is128BitVector() || VT.is64BitVector())) {
7533 unsigned PFIndexes[4];
7534 for (unsigned i = 0; i != 4; ++i) {
7535 if (M[i] < 0)
7536 PFIndexes[i] = 8;
7537 else
7538 PFIndexes[i] = M[i];
7539 }
7540
7541 // Compute the index in the perfect shuffle table.
7542 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7543 PFIndexes[2] * 9 + PFIndexes[3];
7544 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7545 unsigned Cost = (PFEntry >> 30);
7546
7547 if (Cost <= 4)
7548 return true;
7549 }
7550
7551 bool DummyBool;
7552 int DummyInt;
7553 unsigned DummyUnsigned;
7554
7555 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7556 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7557 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7558 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7559 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7560 isZIPMask(M, VT, DummyUnsigned) ||
7561 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7562 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7563 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7564 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7565 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7566}
7567
7568/// getVShiftImm - Check if this is a valid build_vector for the immediate
7569/// operand of a vector shift operation, where all the elements of the
7570/// build_vector must have the same constant integer value.
7571static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7572 // Ignore bit_converts.
7573 while (Op.getOpcode() == ISD::BITCAST)
7574 Op = Op.getOperand(0);
7575 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7576 APInt SplatBits, SplatUndef;
7577 unsigned SplatBitSize;
7578 bool HasAnyUndefs;
7579 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7580 HasAnyUndefs, ElementBits) ||
7581 SplatBitSize > ElementBits)
7582 return false;
7583 Cnt = SplatBits.getSExtValue();
7584 return true;
7585}
7586
7587/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7588/// operand of a vector shift left operation. That value must be in the range:
7589/// 0 <= Value < ElementBits for a left shift; or
7590/// 0 <= Value <= ElementBits for a long left shift.
7591static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7592 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007593 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007594 if (!getVShiftImm(Op, ElementBits, Cnt))
7595 return false;
7596 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7597}
7598
7599/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007600/// operand of a vector shift right operation. The value must be in the range:
7601/// 1 <= Value <= ElementBits for a right shift; or
7602static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007603 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007604 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007605 if (!getVShiftImm(Op, ElementBits, Cnt))
7606 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007607 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7608}
7609
7610SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7611 SelectionDAG &DAG) const {
7612 EVT VT = Op.getValueType();
7613 SDLoc DL(Op);
7614 int64_t Cnt;
7615
7616 if (!Op.getOperand(1).getValueType().isVector())
7617 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007618 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007619
7620 switch (Op.getOpcode()) {
7621 default:
7622 llvm_unreachable("unexpected shift opcode");
7623
7624 case ISD::SHL:
7625 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007626 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7627 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007628 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007629 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7630 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007631 Op.getOperand(0), Op.getOperand(1));
7632 case ISD::SRA:
7633 case ISD::SRL:
7634 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007635 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007636 unsigned Opc =
7637 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007638 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7639 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007640 }
7641
7642 // Right shift register. Note, there is not a shift right register
7643 // instruction, but the shift left register instruction takes a signed
7644 // value, where negative numbers specify a right shift.
7645 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7646 : Intrinsic::aarch64_neon_ushl;
7647 // negate the shift amount
7648 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7649 SDValue NegShiftLeft =
7650 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007651 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7652 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007653 return NegShiftLeft;
7654 }
7655
7656 return SDValue();
7657}
7658
7659static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7660 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007661 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007662 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007663 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7664 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007665
7666 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7667 APInt CnstBits(VT.getSizeInBits(), 0);
7668 APInt UndefBits(VT.getSizeInBits(), 0);
7669 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7670 bool IsZero = IsCnst && (CnstBits == 0);
7671
7672 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7673 switch (CC) {
7674 default:
7675 return SDValue();
7676 case AArch64CC::NE: {
7677 SDValue Fcmeq;
7678 if (IsZero)
7679 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7680 else
7681 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7682 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7683 }
7684 case AArch64CC::EQ:
7685 if (IsZero)
7686 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7687 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7688 case AArch64CC::GE:
7689 if (IsZero)
7690 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7691 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7692 case AArch64CC::GT:
7693 if (IsZero)
7694 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7695 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7696 case AArch64CC::LS:
7697 if (IsZero)
7698 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7699 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7700 case AArch64CC::LT:
7701 if (!NoNans)
7702 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007703 // If we ignore NaNs then we can use to the MI implementation.
7704 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007705 case AArch64CC::MI:
7706 if (IsZero)
7707 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7708 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7709 }
7710 }
7711
7712 switch (CC) {
7713 default:
7714 return SDValue();
7715 case AArch64CC::NE: {
7716 SDValue Cmeq;
7717 if (IsZero)
7718 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7719 else
7720 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7721 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7722 }
7723 case AArch64CC::EQ:
7724 if (IsZero)
7725 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7726 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7727 case AArch64CC::GE:
7728 if (IsZero)
7729 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7730 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7731 case AArch64CC::GT:
7732 if (IsZero)
7733 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7734 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7735 case AArch64CC::LE:
7736 if (IsZero)
7737 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7738 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7739 case AArch64CC::LS:
7740 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7741 case AArch64CC::LO:
7742 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7743 case AArch64CC::LT:
7744 if (IsZero)
7745 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7746 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7747 case AArch64CC::HI:
7748 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7749 case AArch64CC::HS:
7750 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7751 }
7752}
7753
7754SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7755 SelectionDAG &DAG) const {
7756 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7757 SDValue LHS = Op.getOperand(0);
7758 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007759 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007760 SDLoc dl(Op);
7761
7762 if (LHS.getValueType().getVectorElementType().isInteger()) {
7763 assert(LHS.getValueType() == RHS.getValueType());
7764 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007765 SDValue Cmp =
7766 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7767 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007768 }
7769
Carey Williamsda15b5b2018-01-22 14:16:11 +00007770 const bool FullFP16 =
7771 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7772
7773 // Make v4f16 (only) fcmp operations utilise vector instructions
7774 // v8f16 support will be a litle more complicated
7775 if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7776 if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7777 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7778 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7779 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7780 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7781 CmpVT = MVT::v4i32;
7782 } else
7783 return SDValue();
7784 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007785
Tim Northover3b0846e2014-05-24 12:50:23 +00007786 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7787 LHS.getValueType().getVectorElementType() == MVT::f64);
7788
7789 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7790 // clean. Some of them require two branches to implement.
7791 AArch64CC::CondCode CC1, CC2;
7792 bool ShouldInvert;
7793 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7794
7795 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7796 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007797 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007798 if (!Cmp.getNode())
7799 return SDValue();
7800
7801 if (CC2 != AArch64CC::AL) {
7802 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007803 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007804 if (!Cmp2.getNode())
7805 return SDValue();
7806
Tim Northover45aa89c2015-02-08 00:50:47 +00007807 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007808 }
7809
Tim Northover45aa89c2015-02-08 00:50:47 +00007810 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7811
Tim Northover3b0846e2014-05-24 12:50:23 +00007812 if (ShouldInvert)
7813 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7814
7815 return Cmp;
7816}
7817
Amara Emersonc9916d72017-05-16 21:29:22 +00007818static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7819 SelectionDAG &DAG) {
7820 SDValue VecOp = ScalarOp.getOperand(0);
7821 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7822 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7823 DAG.getConstant(0, DL, MVT::i64));
7824}
7825
7826SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7827 SelectionDAG &DAG) const {
7828 SDLoc dl(Op);
7829 switch (Op.getOpcode()) {
7830 case ISD::VECREDUCE_ADD:
7831 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7832 case ISD::VECREDUCE_SMAX:
7833 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7834 case ISD::VECREDUCE_SMIN:
7835 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7836 case ISD::VECREDUCE_UMAX:
7837 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7838 case ISD::VECREDUCE_UMIN:
7839 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7840 case ISD::VECREDUCE_FMAX: {
7841 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7842 return DAG.getNode(
7843 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7844 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7845 Op.getOperand(0));
7846 }
7847 case ISD::VECREDUCE_FMIN: {
7848 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7849 return DAG.getNode(
7850 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7851 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7852 Op.getOperand(0));
7853 }
7854 default:
7855 llvm_unreachable("Unhandled reduction");
7856 }
7857}
7858
Oliver Stannard42699172018-02-12 14:22:03 +00007859SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7860 SelectionDAG &DAG) const {
7861 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7862 if (!Subtarget.hasLSE())
7863 return SDValue();
7864
7865 // LSE has an atomic load-add instruction, but not a load-sub.
7866 SDLoc dl(Op);
7867 MVT VT = Op.getSimpleValueType();
7868 SDValue RHS = Op.getOperand(2);
7869 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7870 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7871 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7872 Op.getOperand(0), Op.getOperand(1), RHS,
7873 AN->getMemOperand());
7874}
7875
Oliver Stannard02f08c92018-02-12 17:03:11 +00007876SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7877 SelectionDAG &DAG) const {
7878 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7879 if (!Subtarget.hasLSE())
7880 return SDValue();
7881
7882 // LSE has an atomic load-clear instruction, but not a load-and.
7883 SDLoc dl(Op);
7884 MVT VT = Op.getSimpleValueType();
7885 SDValue RHS = Op.getOperand(2);
7886 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7887 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7888 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7889 Op.getOperand(0), Op.getOperand(1), RHS,
7890 AN->getMemOperand());
7891}
7892
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007893SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7894 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7895 SDLoc dl(Op);
7896 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7897 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7898
Tri Vo6c47c622018-09-22 22:17:50 +00007899 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7900 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7901 if (Subtarget->hasCustomCallingConv())
7902 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007903
7904 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7905 DAG.getConstant(4, dl, MVT::i64));
7906 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7907 Chain =
7908 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7909 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7910 DAG.getRegisterMask(Mask), Chain.getValue(1));
7911 // To match the actual intent better, we should read the output from X15 here
7912 // again (instead of potentially spilling it to the stack), but rereading Size
7913 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7914 // here.
7915
7916 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7917 DAG.getConstant(4, dl, MVT::i64));
7918 return Chain;
7919}
7920
7921SDValue
7922AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7923 SelectionDAG &DAG) const {
7924 assert(Subtarget->isTargetWindows() &&
7925 "Only Windows alloca probing supported");
7926 SDLoc dl(Op);
7927 // Get the inputs.
7928 SDNode *Node = Op.getNode();
7929 SDValue Chain = Op.getOperand(0);
7930 SDValue Size = Op.getOperand(1);
7931 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7932 EVT VT = Node->getValueType(0);
7933
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007934 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7935 "no-stack-arg-probe")) {
7936 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7937 Chain = SP.getValue(1);
7938 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7939 if (Align)
7940 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7941 DAG.getConstant(-(uint64_t)Align, dl, VT));
7942 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7943 SDValue Ops[2] = {SP, Chain};
7944 return DAG.getMergeValues(Ops, dl);
7945 }
7946
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007947 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7948
7949 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7950
7951 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7952 Chain = SP.getValue(1);
7953 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00007954 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007955 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7956 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00007957 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007958
7959 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7960 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7961
7962 SDValue Ops[2] = {SP, Chain};
7963 return DAG.getMergeValues(Ops, dl);
7964}
7965
Tim Northover3b0846e2014-05-24 12:50:23 +00007966/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7967/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7968/// specified in the intrinsic calls.
7969bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7970 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00007971 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00007972 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007973 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007974 switch (Intrinsic) {
7975 case Intrinsic::aarch64_neon_ld2:
7976 case Intrinsic::aarch64_neon_ld3:
7977 case Intrinsic::aarch64_neon_ld4:
7978 case Intrinsic::aarch64_neon_ld1x2:
7979 case Intrinsic::aarch64_neon_ld1x3:
7980 case Intrinsic::aarch64_neon_ld1x4:
7981 case Intrinsic::aarch64_neon_ld2lane:
7982 case Intrinsic::aarch64_neon_ld3lane:
7983 case Intrinsic::aarch64_neon_ld4lane:
7984 case Intrinsic::aarch64_neon_ld2r:
7985 case Intrinsic::aarch64_neon_ld3r:
7986 case Intrinsic::aarch64_neon_ld4r: {
7987 Info.opc = ISD::INTRINSIC_W_CHAIN;
7988 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007989 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007990 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7991 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7992 Info.offset = 0;
7993 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00007994 // volatile loads with NEON intrinsics not supported
7995 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00007996 return true;
7997 }
7998 case Intrinsic::aarch64_neon_st2:
7999 case Intrinsic::aarch64_neon_st3:
8000 case Intrinsic::aarch64_neon_st4:
8001 case Intrinsic::aarch64_neon_st1x2:
8002 case Intrinsic::aarch64_neon_st1x3:
8003 case Intrinsic::aarch64_neon_st1x4:
8004 case Intrinsic::aarch64_neon_st2lane:
8005 case Intrinsic::aarch64_neon_st3lane:
8006 case Intrinsic::aarch64_neon_st4lane: {
8007 Info.opc = ISD::INTRINSIC_VOID;
8008 // Conservatively set memVT to the entire set of vectors stored.
8009 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008010 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008011 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8012 if (!ArgTy->isVectorTy())
8013 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008014 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008015 }
8016 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8017 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8018 Info.offset = 0;
8019 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008020 // volatile stores with NEON intrinsics not supported
8021 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008022 return true;
8023 }
8024 case Intrinsic::aarch64_ldaxr:
8025 case Intrinsic::aarch64_ldxr: {
8026 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8027 Info.opc = ISD::INTRINSIC_W_CHAIN;
8028 Info.memVT = MVT::getVT(PtrTy->getElementType());
8029 Info.ptrVal = I.getArgOperand(0);
8030 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008031 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008032 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008033 return true;
8034 }
8035 case Intrinsic::aarch64_stlxr:
8036 case Intrinsic::aarch64_stxr: {
8037 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8038 Info.opc = ISD::INTRINSIC_W_CHAIN;
8039 Info.memVT = MVT::getVT(PtrTy->getElementType());
8040 Info.ptrVal = I.getArgOperand(1);
8041 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008042 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008043 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008044 return true;
8045 }
8046 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008047 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008048 Info.opc = ISD::INTRINSIC_W_CHAIN;
8049 Info.memVT = MVT::i128;
8050 Info.ptrVal = I.getArgOperand(0);
8051 Info.offset = 0;
8052 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008053 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008054 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008055 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008056 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008057 Info.opc = ISD::INTRINSIC_W_CHAIN;
8058 Info.memVT = MVT::i128;
8059 Info.ptrVal = I.getArgOperand(2);
8060 Info.offset = 0;
8061 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008062 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008063 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008064 default:
8065 break;
8066 }
8067
8068 return false;
8069}
8070
John Brawne3b44f92018-03-23 14:47:07 +00008071bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8072 ISD::LoadExtType ExtTy,
8073 EVT NewVT) const {
8074 // If we're reducing the load width in order to avoid having to use an extra
8075 // instruction to do extension then it's probably a good idea.
8076 if (ExtTy != ISD::NON_EXTLOAD)
8077 return true;
8078 // Don't reduce load width if it would prevent us from combining a shift into
8079 // the offset.
8080 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8081 assert(Mem);
8082 const SDValue &Base = Mem->getBasePtr();
8083 if (Base.getOpcode() == ISD::ADD &&
8084 Base.getOperand(1).getOpcode() == ISD::SHL &&
8085 Base.getOperand(1).hasOneUse() &&
8086 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8087 // The shift can be combined if it matches the size of the value being
8088 // loaded (and so reducing the width would make it not match).
8089 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8090 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8091 if (ShiftAmount == Log2_32(LoadBytes))
8092 return false;
8093 }
8094 // We have no reason to disallow reducing the load width, so allow it.
8095 return true;
8096}
8097
Tim Northover3b0846e2014-05-24 12:50:23 +00008098// Truncations from 64-bit GPR to 32-bit GPR is free.
8099bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8100 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8101 return false;
8102 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8103 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008104 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008105}
8106bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008107 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008108 return false;
8109 unsigned NumBits1 = VT1.getSizeInBits();
8110 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008111 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008112}
8113
Chad Rosier54390052015-02-23 19:15:16 +00008114/// Check if it is profitable to hoist instruction in then/else to if.
8115/// Not profitable if I and it's user can form a FMA instruction
8116/// because we prefer FMSUB/FMADD.
8117bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8118 if (I->getOpcode() != Instruction::FMul)
8119 return true;
8120
Davide Italiano3e9986f2017-04-18 00:29:54 +00008121 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008122 return true;
8123
8124 Instruction *User = I->user_back();
8125
8126 if (User &&
8127 !(User->getOpcode() == Instruction::FSub ||
8128 User->getOpcode() == Instruction::FAdd))
8129 return true;
8130
8131 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008132 const DataLayout &DL = I->getModule()->getDataLayout();
8133 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008134
Eric Christopher114fa1c2016-02-29 22:50:49 +00008135 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8136 isOperationLegalOrCustom(ISD::FMA, VT) &&
8137 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8138 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008139}
8140
Tim Northover3b0846e2014-05-24 12:50:23 +00008141// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8142// 64-bit GPR.
8143bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8144 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8145 return false;
8146 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8147 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008148 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008149}
8150bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008151 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008152 return false;
8153 unsigned NumBits1 = VT1.getSizeInBits();
8154 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008155 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008156}
8157
8158bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8159 EVT VT1 = Val.getValueType();
8160 if (isZExtFree(VT1, VT2)) {
8161 return true;
8162 }
8163
8164 if (Val.getOpcode() != ISD::LOAD)
8165 return false;
8166
8167 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008168 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8169 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8170 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008171}
8172
Quentin Colombet6843ac42015-03-31 20:52:32 +00008173bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8174 if (isa<FPExtInst>(Ext))
8175 return false;
8176
Haicheng Wu50692a22017-08-01 21:26:45 +00008177 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008178 if (Ext->getType()->isVectorTy())
8179 return false;
8180
8181 for (const Use &U : Ext->uses()) {
8182 // The extension is free if we can fold it with a left shift in an
8183 // addressing mode or an arithmetic operation: add, sub, and cmp.
8184
8185 // Is there a shift?
8186 const Instruction *Instr = cast<Instruction>(U.getUser());
8187
8188 // Is this a constant shift?
8189 switch (Instr->getOpcode()) {
8190 case Instruction::Shl:
8191 if (!isa<ConstantInt>(Instr->getOperand(1)))
8192 return false;
8193 break;
8194 case Instruction::GetElementPtr: {
8195 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008196 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008197 std::advance(GTI, U.getOperandNo()-1);
8198 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008199 // This extension will end up with a shift because of the scaling factor.
8200 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8201 // Get the shift amount based on the scaling factor:
8202 // log2(sizeof(IdxTy)) - log2(8).
8203 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008204 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008205 // Is the constant foldable in the shift of the addressing mode?
8206 // I.e., shift amount is between 1 and 4 inclusive.
8207 if (ShiftAmt == 0 || ShiftAmt > 4)
8208 return false;
8209 break;
8210 }
8211 case Instruction::Trunc:
8212 // Check if this is a noop.
8213 // trunc(sext ty1 to ty2) to ty1.
8214 if (Instr->getType() == Ext->getOperand(0)->getType())
8215 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008216 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008217 default:
8218 return false;
8219 }
8220
8221 // At this point we can use the bfm family, so this extension is free
8222 // for that use.
8223 }
8224 return true;
8225}
8226
Tim Northover3b0846e2014-05-24 12:50:23 +00008227bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8228 unsigned &RequiredAligment) const {
8229 if (!LoadedType.isSimple() ||
8230 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8231 return false;
8232 // Cyclone supports unaligned accesses.
8233 RequiredAligment = 0;
8234 unsigned NumBits = LoadedType.getSizeInBits();
8235 return NumBits == 32 || NumBits == 64;
8236}
8237
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008238/// A helper function for determining the number of interleaved accesses we
8239/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008240unsigned
8241AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8242 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008243 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8244}
8245
Geoff Berryb1e87142017-07-14 21:44:12 +00008246MachineMemOperand::Flags
8247AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8248 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8249 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8250 return MOStridedAccess;
8251 return MachineMemOperand::MONone;
8252}
8253
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008254bool AArch64TargetLowering::isLegalInterleavedAccessType(
8255 VectorType *VecTy, const DataLayout &DL) const {
8256
8257 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8258 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8259
8260 // Ensure the number of vector elements is greater than 1.
8261 if (VecTy->getNumElements() < 2)
8262 return false;
8263
8264 // Ensure the element type is legal.
8265 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8266 return false;
8267
8268 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8269 // 128 will be split into multiple interleaved accesses.
8270 return VecSize == 64 || VecSize % 128 == 0;
8271}
8272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008273/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008274///
8275/// E.g. Lower an interleaved load (Factor = 2):
8276/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8277/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8278/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8279///
8280/// Into:
8281/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8282/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8283/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8284bool AArch64TargetLowering::lowerInterleavedLoad(
8285 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8286 ArrayRef<unsigned> Indices, unsigned Factor) const {
8287 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8288 "Invalid interleave factor");
8289 assert(!Shuffles.empty() && "Empty shufflevector input");
8290 assert(Shuffles.size() == Indices.size() &&
8291 "Unmatched number of shufflevectors and indices");
8292
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008293 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008294
8295 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008296
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008297 // Skip if we do not have NEON and skip illegal vector types. We can
8298 // "legalize" wide vector types into multiple interleaved accesses as long as
8299 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008300 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008301 return false;
8302
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008303 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8304
Hao Liu7ec8ee32015-06-26 02:32:07 +00008305 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8306 // load integer vectors first and then convert to pointer vectors.
8307 Type *EltTy = VecTy->getVectorElementType();
8308 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008309 VecTy =
8310 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008311
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008312 IRBuilder<> Builder(LI);
8313
8314 // The base address of the load.
8315 Value *BaseAddr = LI->getPointerOperand();
8316
8317 if (NumLoads > 1) {
8318 // If we're going to generate more than one load, reset the sub-vector type
8319 // to something legal.
8320 VecTy = VectorType::get(VecTy->getVectorElementType(),
8321 VecTy->getVectorNumElements() / NumLoads);
8322
8323 // We will compute the pointer operand of each load from the original base
8324 // address using GEPs. Cast the base address to a pointer to the scalar
8325 // element type.
8326 BaseAddr = Builder.CreateBitCast(
8327 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8328 LI->getPointerAddressSpace()));
8329 }
8330
Hao Liu7ec8ee32015-06-26 02:32:07 +00008331 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8332 Type *Tys[2] = {VecTy, PtrTy};
8333 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8334 Intrinsic::aarch64_neon_ld3,
8335 Intrinsic::aarch64_neon_ld4};
8336 Function *LdNFunc =
8337 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8338
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008339 // Holds sub-vectors extracted from the load intrinsic return values. The
8340 // sub-vectors are associated with the shufflevector instructions they will
8341 // replace.
8342 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008343
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008344 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008345
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008346 // If we're generating more than one load, compute the base address of
8347 // subsequent loads as an offset from the previous.
8348 if (LoadCount > 0)
8349 BaseAddr = Builder.CreateConstGEP1_32(
8350 BaseAddr, VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008351
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008352 CallInst *LdN = Builder.CreateCall(
8353 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008354
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008355 // Extract and store the sub-vectors returned by the load intrinsic.
8356 for (unsigned i = 0; i < Shuffles.size(); i++) {
8357 ShuffleVectorInst *SVI = Shuffles[i];
8358 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008359
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008360 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8361
8362 // Convert the integer vector to pointer vector if the element is pointer.
8363 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008364 SubVec = Builder.CreateIntToPtr(
8365 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8366 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008367 SubVecs[SVI].push_back(SubVec);
8368 }
8369 }
8370
8371 // Replace uses of the shufflevector instructions with the sub-vectors
8372 // returned by the load intrinsic. If a shufflevector instruction is
8373 // associated with more than one sub-vector, those sub-vectors will be
8374 // concatenated into a single wide vector.
8375 for (ShuffleVectorInst *SVI : Shuffles) {
8376 auto &SubVec = SubVecs[SVI];
8377 auto *WideVec =
8378 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8379 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008380 }
8381
8382 return true;
8383}
8384
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008385/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008386///
8387/// E.g. Lower an interleaved store (Factor = 3):
8388/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008389/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008390/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8391///
8392/// Into:
8393/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8394/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8395/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8396/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8397///
8398/// Note that the new shufflevectors will be removed and we'll only generate one
8399/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008400///
8401/// Example for a more general valid mask (Factor 3). Lower:
8402/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8403/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8404/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8405///
8406/// Into:
8407/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8408/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8409/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8410/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008411bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8412 ShuffleVectorInst *SVI,
8413 unsigned Factor) const {
8414 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8415 "Invalid interleave factor");
8416
8417 VectorType *VecTy = SVI->getType();
8418 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8419 "Invalid interleaved store");
8420
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008421 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008422 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008423 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008424
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008425 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008426
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008427 // Skip if we do not have NEON and skip illegal vector types. We can
8428 // "legalize" wide vector types into multiple interleaved accesses as long as
8429 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008430 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008431 return false;
8432
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008433 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8434
Hao Liu7ec8ee32015-06-26 02:32:07 +00008435 Value *Op0 = SVI->getOperand(0);
8436 Value *Op1 = SVI->getOperand(1);
8437 IRBuilder<> Builder(SI);
8438
8439 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8440 // vectors to integer vectors.
8441 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008442 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008443 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008444
8445 // Convert to the corresponding integer vector.
8446 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8447 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8448 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8449
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008450 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008451 }
8452
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008453 // The base address of the store.
8454 Value *BaseAddr = SI->getPointerOperand();
8455
8456 if (NumStores > 1) {
8457 // If we're going to generate more than one store, reset the lane length
8458 // and sub-vector type to something legal.
8459 LaneLen /= NumStores;
8460 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8461
8462 // We will compute the pointer operand of each store from the original base
8463 // address using GEPs. Cast the base address to a pointer to the scalar
8464 // element type.
8465 BaseAddr = Builder.CreateBitCast(
8466 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8467 SI->getPointerAddressSpace()));
8468 }
8469
8470 auto Mask = SVI->getShuffleMask();
8471
Hao Liu7ec8ee32015-06-26 02:32:07 +00008472 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8473 Type *Tys[2] = {SubVecTy, PtrTy};
8474 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8475 Intrinsic::aarch64_neon_st3,
8476 Intrinsic::aarch64_neon_st4};
8477 Function *StNFunc =
8478 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8479
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008480 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008481
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008482 SmallVector<Value *, 5> Ops;
8483
8484 // Split the shufflevector operands into sub vectors for the new stN call.
8485 for (unsigned i = 0; i < Factor; i++) {
8486 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8487 if (Mask[IdxI] >= 0) {
8488 Ops.push_back(Builder.CreateShuffleVector(
8489 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8490 } else {
8491 unsigned StartMask = 0;
8492 for (unsigned j = 1; j < LaneLen; j++) {
8493 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8494 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8495 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8496 break;
8497 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008498 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008499 // Note: Filling undef gaps with random elements is ok, since
8500 // those elements were being written anyway (with undefs).
8501 // In the case of all undefs we're defaulting to using elems from 0
8502 // Note: StartMask cannot be negative, it's checked in
8503 // isReInterleaveMask
8504 Ops.push_back(Builder.CreateShuffleVector(
8505 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008506 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008507 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008508
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008509 // If we generating more than one store, we compute the base address of
8510 // subsequent stores as an offset from the previous.
8511 if (StoreCount > 0)
8512 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
8513
8514 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8515 Builder.CreateCall(StNFunc, Ops);
8516 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008517 return true;
8518}
8519
Tim Northover3b0846e2014-05-24 12:50:23 +00008520static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8521 unsigned AlignCheck) {
8522 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8523 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8524}
8525
8526EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8527 unsigned SrcAlign, bool IsMemset,
8528 bool ZeroMemset,
8529 bool MemcpyStrSrc,
8530 MachineFunction &MF) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008531 const Function &F = MF.getFunction();
JF Bastien29200612018-09-06 16:03:32 +00008532 bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8533 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8534 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8535 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8536 // taken one instruction to materialize the v2i64 zero and one store (with
8537 // restrictive addressing mode). Just do i64 stores.
8538 bool IsSmallMemset = IsMemset && Size < 32;
8539 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8540 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8541 return true;
8542 bool Fast;
8543 return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8544 };
8545
8546 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8547 AlignmentIsAcceptable(MVT::v2i64, 16))
8548 return MVT::v2i64;
8549 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008550 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008551 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008552 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008553 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008554 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008555 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008556}
8557
8558// 12-bit optionally shifted immediates are legal for adds.
8559bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008560 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008561 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8562 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008563 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008564 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008565 // Same encoding for add/sub, just flip the sign.
8566 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008567 bool IsLegal = ((Immed >> 12) == 0 ||
8568 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008569 LLVM_DEBUG(dbgs() << "Is " << Immed
8570 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008571 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008572}
8573
8574// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8575// immediates is the same as for an add or a sub.
8576bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008577 return isLegalAddImmediate(Immed);
8578}
8579
8580/// isLegalAddressingMode - Return true if the addressing mode represented
8581/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008582bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8583 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008584 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008585 // AArch64 has five basic addressing modes:
8586 // reg
8587 // reg + 9-bit signed offset
8588 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8589 // reg1 + reg2
8590 // reg + SIZE_IN_BYTES * reg
8591
8592 // No global is ever allowed as a base.
8593 if (AM.BaseGV)
8594 return false;
8595
8596 // No reg+reg+imm addressing.
8597 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8598 return false;
8599
8600 // check reg + imm case:
8601 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8602 uint64_t NumBytes = 0;
8603 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008604 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008605 NumBytes = NumBits / 8;
8606 if (!isPowerOf2_64(NumBits))
8607 NumBytes = 0;
8608 }
8609
8610 if (!AM.Scale) {
8611 int64_t Offset = AM.BaseOffs;
8612
8613 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008614 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008615 return true;
8616
8617 // 12-bit unsigned offset
8618 unsigned shift = Log2_64(NumBytes);
8619 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8620 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8621 (Offset >> shift) << shift == Offset)
8622 return true;
8623 return false;
8624 }
8625
8626 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8627
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008628 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008629}
8630
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008631bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8632 // Consider splitting large offset of struct or array.
8633 return true;
8634}
8635
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008636int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8637 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008638 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008639 // Scaling factors are not free at all.
8640 // Operands | Rt Latency
8641 // -------------------------------------------
8642 // Rt, [Xn, Xm] | 4
8643 // -------------------------------------------
8644 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8645 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008646 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008647 // Scale represents reg2 * scale, thus account for 1 if
8648 // it is not equal to 0 or 1.
8649 return AM.Scale != 0 && AM.Scale != 1;
8650 return -1;
8651}
8652
8653bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8654 VT = VT.getScalarType();
8655
8656 if (!VT.isSimple())
8657 return false;
8658
8659 switch (VT.getSimpleVT().SimpleTy) {
8660 case MVT::f32:
8661 case MVT::f64:
8662 return true;
8663 default:
8664 break;
8665 }
8666
8667 return false;
8668}
8669
8670const MCPhysReg *
8671AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8672 // LR is a callee-save register, but we must treat it as clobbered by any call
8673 // site. Hence we include LR in the scratch registers, which are in turn added
8674 // as implicit-defs for stackmaps and patchpoints.
8675 static const MCPhysReg ScratchRegs[] = {
8676 AArch64::X16, AArch64::X17, AArch64::LR, 0
8677 };
8678 return ScratchRegs;
8679}
8680
8681bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008682AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8683 CombineLevel Level) const {
8684 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008685 EVT VT = N->getValueType(0);
8686 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8687 // it with shift to let it be lowered to UBFX.
8688 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8689 isa<ConstantSDNode>(N->getOperand(1))) {
8690 uint64_t TruncMask = N->getConstantOperandVal(1);
8691 if (isMask_64(TruncMask) &&
8692 N->getOperand(0).getOpcode() == ISD::SRL &&
8693 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8694 return false;
8695 }
8696 return true;
8697}
8698
8699bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8700 Type *Ty) const {
8701 assert(Ty->isIntegerTy());
8702
8703 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8704 if (BitSize == 0)
8705 return false;
8706
8707 int64_t Val = Imm.getSExtValue();
8708 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8709 return true;
8710
8711 if ((int64_t)Val < 0)
8712 Val = ~Val;
8713 if (BitSize == 32)
8714 Val &= (1LL << 32) - 1;
8715
8716 unsigned LZ = countLeadingZeros((uint64_t)Val);
8717 unsigned Shift = (63 - LZ) / 16;
8718 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008719 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008720}
8721
Sebastian Pop41073e82018-03-06 16:54:55 +00008722bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8723 unsigned Index) const {
8724 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8725 return false;
8726
8727 return (Index == 0 || Index == ResVT.getVectorNumElements());
8728}
8729
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008730/// Turn vector tests of the signbit in the form of:
8731/// xor (sra X, elt_size(X)-1), -1
8732/// into:
8733/// cmge X, X, #0
8734static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8735 const AArch64Subtarget *Subtarget) {
8736 EVT VT = N->getValueType(0);
8737 if (!Subtarget->hasNEON() || !VT.isVector())
8738 return SDValue();
8739
8740 // There must be a shift right algebraic before the xor, and the xor must be a
8741 // 'not' operation.
8742 SDValue Shift = N->getOperand(0);
8743 SDValue Ones = N->getOperand(1);
8744 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8745 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8746 return SDValue();
8747
8748 // The shift should be smearing the sign bit across each vector element.
8749 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8750 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8751 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8752 return SDValue();
8753
8754 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8755}
8756
Tim Northover3b0846e2014-05-24 12:50:23 +00008757// Generate SUBS and CSEL for integer abs.
8758static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8759 EVT VT = N->getValueType(0);
8760
8761 SDValue N0 = N->getOperand(0);
8762 SDValue N1 = N->getOperand(1);
8763 SDLoc DL(N);
8764
8765 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8766 // and change it to SUB and CSEL.
8767 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8768 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8769 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8770 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8771 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008772 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008773 N0.getOperand(0));
8774 // Generate SUBS & CSEL.
8775 SDValue Cmp =
8776 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008777 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008778 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008779 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008780 SDValue(Cmp.getNode(), 1));
8781 }
8782 return SDValue();
8783}
8784
Tim Northover3b0846e2014-05-24 12:50:23 +00008785static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8786 TargetLowering::DAGCombinerInfo &DCI,
8787 const AArch64Subtarget *Subtarget) {
8788 if (DCI.isBeforeLegalizeOps())
8789 return SDValue();
8790
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008791 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8792 return Cmp;
8793
Tim Northover3b0846e2014-05-24 12:50:23 +00008794 return performIntegerAbsCombine(N, DAG);
8795}
8796
Chad Rosier17020f92014-07-23 14:57:52 +00008797SDValue
8798AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8799 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008800 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008801 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008802 if (isIntDivCheap(N->getValueType(0), Attr))
8803 return SDValue(N,0); // Lower SDIV as SDIV
8804
Chad Rosier17020f92014-07-23 14:57:52 +00008805 // fold (sdiv X, pow2)
8806 EVT VT = N->getValueType(0);
8807 if ((VT != MVT::i32 && VT != MVT::i64) ||
8808 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8809 return SDValue();
8810
8811 SDLoc DL(N);
8812 SDValue N0 = N->getOperand(0);
8813 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008814 SDValue Zero = DAG.getConstant(0, DL, VT);
8815 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008816
8817 // Add (N0 < 0) ? Pow2 - 1 : 0;
8818 SDValue CCVal;
8819 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8820 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8821 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8822
Craig Toppera568a272018-07-30 21:04:34 +00008823 Created.push_back(Cmp.getNode());
8824 Created.push_back(Add.getNode());
8825 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00008826
8827 // Divide by pow2.
8828 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008829 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008830
8831 // If we're dividing by a positive value, we're done. Otherwise, we must
8832 // negate the result.
8833 if (Divisor.isNonNegative())
8834 return SRA;
8835
Craig Toppera568a272018-07-30 21:04:34 +00008836 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008837 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008838}
8839
Tim Northover3b0846e2014-05-24 12:50:23 +00008840static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8841 TargetLowering::DAGCombinerInfo &DCI,
8842 const AArch64Subtarget *Subtarget) {
8843 if (DCI.isBeforeLegalizeOps())
8844 return SDValue();
8845
Chad Rosier31ee8132016-11-11 17:07:37 +00008846 // The below optimizations require a constant RHS.
8847 if (!isa<ConstantSDNode>(N->getOperand(1)))
8848 return SDValue();
8849
8850 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8851 const APInt &ConstValue = C->getAPIntValue();
8852
Tim Northover3b0846e2014-05-24 12:50:23 +00008853 // Multiplication of a power of two plus/minus one can be done more
8854 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8855 // future CPUs have a cheaper MADD instruction, this may need to be
8856 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8857 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008858 // More aggressively, some multiplications N0 * C can be lowered to
8859 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8860 // e.g. 6=3*2=(2+1)*2.
8861 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8862 // which equals to (1+2)*16-(1+2).
8863 SDValue N0 = N->getOperand(0);
8864 // TrailingZeroes is used to test if the mul can be lowered to
8865 // shift+add+shift.
8866 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8867 if (TrailingZeroes) {
8868 // Conservatively do not lower to shift+add+shift if the mul might be
8869 // folded into smul or umul.
8870 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8871 isZeroExtended(N0.getNode(), DAG)))
8872 return SDValue();
8873 // Conservatively do not lower to shift+add+shift if the mul might be
8874 // folded into madd or msub.
8875 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8876 N->use_begin()->getOpcode() == ISD::SUB))
8877 return SDValue();
8878 }
8879 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8880 // and shift+add+shift.
8881 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8882
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008883 unsigned ShiftAmt, AddSubOpc;
8884 // Is the shifted value the LHS operand of the add/sub?
8885 bool ShiftValUseIsN0 = true;
8886 // Do we need to negate the result?
8887 bool NegateResult = false;
8888
Chad Rosier31ee8132016-11-11 17:07:37 +00008889 if (ConstValue.isNonNegative()) {
8890 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00008891 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00008892 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8893 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008894 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00008895 if (SCVMinus1.isPowerOf2()) {
8896 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008897 AddSubOpc = ISD::ADD;
8898 } else if (CVPlus1.isPowerOf2()) {
8899 ShiftAmt = CVPlus1.logBase2();
8900 AddSubOpc = ISD::SUB;
8901 } else
8902 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00008903 } else {
8904 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00008905 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008906 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008907 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008908 if (CVNegPlus1.isPowerOf2()) {
8909 ShiftAmt = CVNegPlus1.logBase2();
8910 AddSubOpc = ISD::SUB;
8911 ShiftValUseIsN0 = false;
8912 } else if (CVNegMinus1.isPowerOf2()) {
8913 ShiftAmt = CVNegMinus1.logBase2();
8914 AddSubOpc = ISD::ADD;
8915 NegateResult = true;
8916 } else
8917 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008918 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008919
8920 SDLoc DL(N);
8921 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008922 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008923 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8924
8925 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8926 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8927 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008928 assert(!(NegateResult && TrailingZeroes) &&
8929 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008930 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008931 if (NegateResult)
8932 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8933 // Shift the result.
8934 if (TrailingZeroes)
8935 return DAG.getNode(ISD::SHL, DL, VT, Res,
8936 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8937 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00008938}
8939
Jim Grosbachf7502c42014-07-18 00:40:52 +00008940static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8941 SelectionDAG &DAG) {
8942 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8943 // optimize away operation when it's from a constant.
8944 //
8945 // The general transformation is:
8946 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8947 // AND(VECTOR_CMP(x,y), constant2)
8948 // constant2 = UNARYOP(constant)
8949
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008950 // Early exit if this isn't a vector operation, the operand of the
8951 // unary operation isn't a bitwise AND, or if the sizes of the operations
8952 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00008953 EVT VT = N->getValueType(0);
8954 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008955 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8956 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008957 return SDValue();
8958
Jim Grosbach724e4382014-07-23 20:41:43 +00008959 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00008960 // make the transformation for non-constant splats as well, but it's unclear
8961 // that would be a benefit as it would not eliminate any operations, just
8962 // perform one more step in scalar code before moving to the vector unit.
8963 if (BuildVectorSDNode *BV =
8964 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00008965 // Bail out if the vector isn't a constant.
8966 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008967 return SDValue();
8968
8969 // Everything checks out. Build up the new and improved node.
8970 SDLoc DL(N);
8971 EVT IntVT = BV->getValueType(0);
8972 // Create a new constant of the appropriate type for the transformed
8973 // DAG.
8974 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8975 // The AND node needs bitcasts to/from an integer vector type around it.
8976 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8977 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8978 N->getOperand(0)->getOperand(0), MaskConst);
8979 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8980 return Res;
8981 }
8982
8983 return SDValue();
8984}
8985
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008986static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8987 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00008988 // First try to optimize away the conversion when it's conditionally from
8989 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008990 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00008991 return Res;
8992
Tim Northover3b0846e2014-05-24 12:50:23 +00008993 EVT VT = N->getValueType(0);
8994 if (VT != MVT::f32 && VT != MVT::f64)
8995 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00008996
Tim Northover3b0846e2014-05-24 12:50:23 +00008997 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008998 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00008999 return SDValue();
9000
9001 // If the result of an integer load is only used by an integer-to-float
9002 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009003 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009004 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009005 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009006 // Do not change the width of a volatile load.
9007 !cast<LoadSDNode>(N0)->isVolatile()) {
9008 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9009 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009010 LN0->getPointerInfo(), LN0->getAlignment(),
9011 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009012
9013 // Make sure successors of the original load stay after it by updating them
9014 // to use the new Chain.
9015 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9016
9017 unsigned Opcode =
9018 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9019 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9020 }
9021
9022 return SDValue();
9023}
9024
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009025/// Fold a floating-point multiply by power of two into floating-point to
9026/// fixed-point conversion.
9027static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009028 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009029 const AArch64Subtarget *Subtarget) {
9030 if (!Subtarget->hasNEON())
9031 return SDValue();
9032
9033 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009034 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9035 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009036 return SDValue();
9037
9038 SDValue ConstVec = Op->getOperand(1);
9039 if (!isa<BuildVectorSDNode>(ConstVec))
9040 return SDValue();
9041
9042 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9043 uint32_t FloatBits = FloatTy.getSizeInBits();
9044 if (FloatBits != 32 && FloatBits != 64)
9045 return SDValue();
9046
9047 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9048 uint32_t IntBits = IntTy.getSizeInBits();
9049 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9050 return SDValue();
9051
9052 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9053 if (IntBits > FloatBits)
9054 return SDValue();
9055
9056 BitVector UndefElements;
9057 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9058 int32_t Bits = IntBits == 64 ? 64 : 32;
9059 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9060 if (C == -1 || C == 0 || C > Bits)
9061 return SDValue();
9062
9063 MVT ResTy;
9064 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9065 switch (NumLanes) {
9066 default:
9067 return SDValue();
9068 case 2:
9069 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9070 break;
9071 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009072 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009073 break;
9074 }
9075
Silviu Barangafa00ba32016-08-08 13:13:57 +00009076 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9077 return SDValue();
9078
9079 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9080 "Illegal vector type after legalization");
9081
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009082 SDLoc DL(N);
9083 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9084 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9085 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9086 SDValue FixConv =
9087 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9088 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9089 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9090 // We can handle smaller integers by generating an extra trunc.
9091 if (IntBits < FloatBits)
9092 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9093
9094 return FixConv;
9095}
9096
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009097/// Fold a floating-point divide by power of two into fixed-point to
9098/// floating-point conversion.
9099static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009100 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009101 const AArch64Subtarget *Subtarget) {
9102 if (!Subtarget->hasNEON())
9103 return SDValue();
9104
9105 SDValue Op = N->getOperand(0);
9106 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009107 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9108 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009109 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9110 return SDValue();
9111
9112 SDValue ConstVec = N->getOperand(1);
9113 if (!isa<BuildVectorSDNode>(ConstVec))
9114 return SDValue();
9115
9116 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9117 int32_t IntBits = IntTy.getSizeInBits();
9118 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9119 return SDValue();
9120
9121 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9122 int32_t FloatBits = FloatTy.getSizeInBits();
9123 if (FloatBits != 32 && FloatBits != 64)
9124 return SDValue();
9125
9126 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9127 if (IntBits > FloatBits)
9128 return SDValue();
9129
9130 BitVector UndefElements;
9131 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9132 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9133 if (C == -1 || C == 0 || C > FloatBits)
9134 return SDValue();
9135
9136 MVT ResTy;
9137 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9138 switch (NumLanes) {
9139 default:
9140 return SDValue();
9141 case 2:
9142 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9143 break;
9144 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009145 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009146 break;
9147 }
9148
Tim Northover85cf5642016-08-26 18:52:31 +00009149 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9150 return SDValue();
9151
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009152 SDLoc DL(N);
9153 SDValue ConvInput = Op.getOperand(0);
9154 bool IsSigned = Opc == ISD::SINT_TO_FP;
9155 if (IntBits < FloatBits)
9156 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9157 ResTy, ConvInput);
9158
9159 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9160 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9161 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9162 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9163 DAG.getConstant(C, DL, MVT::i32));
9164}
9165
Tim Northover3b0846e2014-05-24 12:50:23 +00009166/// An EXTR instruction is made up of two shifts, ORed together. This helper
9167/// searches for and classifies those shifts.
9168static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9169 bool &FromHi) {
9170 if (N.getOpcode() == ISD::SHL)
9171 FromHi = false;
9172 else if (N.getOpcode() == ISD::SRL)
9173 FromHi = true;
9174 else
9175 return false;
9176
9177 if (!isa<ConstantSDNode>(N.getOperand(1)))
9178 return false;
9179
9180 ShiftAmount = N->getConstantOperandVal(1);
9181 Src = N->getOperand(0);
9182 return true;
9183}
9184
9185/// EXTR instruction extracts a contiguous chunk of bits from two existing
9186/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009187/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9188/// with an EXTR. Can't quite be done in TableGen because the two immediates
9189/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009190static SDValue tryCombineToEXTR(SDNode *N,
9191 TargetLowering::DAGCombinerInfo &DCI) {
9192 SelectionDAG &DAG = DCI.DAG;
9193 SDLoc DL(N);
9194 EVT VT = N->getValueType(0);
9195
9196 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9197
9198 if (VT != MVT::i32 && VT != MVT::i64)
9199 return SDValue();
9200
9201 SDValue LHS;
9202 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009203 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009204 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9205 return SDValue();
9206
9207 SDValue RHS;
9208 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009209 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009210 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9211 return SDValue();
9212
9213 // If they're both trying to come from the high part of the register, they're
9214 // not really an EXTR.
9215 if (LHSFromHi == RHSFromHi)
9216 return SDValue();
9217
9218 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9219 return SDValue();
9220
9221 if (LHSFromHi) {
9222 std::swap(LHS, RHS);
9223 std::swap(ShiftLHS, ShiftRHS);
9224 }
9225
9226 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009227 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009228}
9229
9230static SDValue tryCombineToBSL(SDNode *N,
9231 TargetLowering::DAGCombinerInfo &DCI) {
9232 EVT VT = N->getValueType(0);
9233 SelectionDAG &DAG = DCI.DAG;
9234 SDLoc DL(N);
9235
9236 if (!VT.isVector())
9237 return SDValue();
9238
9239 SDValue N0 = N->getOperand(0);
9240 if (N0.getOpcode() != ISD::AND)
9241 return SDValue();
9242
9243 SDValue N1 = N->getOperand(1);
9244 if (N1.getOpcode() != ISD::AND)
9245 return SDValue();
9246
9247 // We only have to look for constant vectors here since the general, variable
9248 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009249 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009250 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9251 for (int i = 1; i >= 0; --i)
9252 for (int j = 1; j >= 0; --j) {
9253 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9254 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9255 if (!BVN0 || !BVN1)
9256 continue;
9257
9258 bool FoundMatch = true;
9259 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9260 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9261 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9262 if (!CN0 || !CN1 ||
9263 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9264 FoundMatch = false;
9265 break;
9266 }
9267 }
9268
9269 if (FoundMatch)
9270 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9271 N0->getOperand(1 - i), N1->getOperand(1 - j));
9272 }
9273
9274 return SDValue();
9275}
9276
9277static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9278 const AArch64Subtarget *Subtarget) {
9279 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009280 SelectionDAG &DAG = DCI.DAG;
9281 EVT VT = N->getValueType(0);
9282
9283 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9284 return SDValue();
9285
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009286 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009287 return Res;
9288
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009289 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009290 return Res;
9291
9292 return SDValue();
9293}
9294
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009295static SDValue performSRLCombine(SDNode *N,
9296 TargetLowering::DAGCombinerInfo &DCI) {
9297 SelectionDAG &DAG = DCI.DAG;
9298 EVT VT = N->getValueType(0);
9299 if (VT != MVT::i32 && VT != MVT::i64)
9300 return SDValue();
9301
9302 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9303 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9304 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9305 SDValue N0 = N->getOperand(0);
9306 if (N0.getOpcode() == ISD::BSWAP) {
9307 SDLoc DL(N);
9308 SDValue N1 = N->getOperand(1);
9309 SDValue N00 = N0.getOperand(0);
9310 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9311 uint64_t ShiftAmt = C->getZExtValue();
9312 if (VT == MVT::i32 && ShiftAmt == 16 &&
9313 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9314 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9315 if (VT == MVT::i64 && ShiftAmt == 32 &&
9316 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9317 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9318 }
9319 }
9320 return SDValue();
9321}
9322
Tim Northover3b0846e2014-05-24 12:50:23 +00009323static SDValue performBitcastCombine(SDNode *N,
9324 TargetLowering::DAGCombinerInfo &DCI,
9325 SelectionDAG &DAG) {
9326 // Wait 'til after everything is legalized to try this. That way we have
9327 // legal vector types and such.
9328 if (DCI.isBeforeLegalizeOps())
9329 return SDValue();
9330
9331 // Remove extraneous bitcasts around an extract_subvector.
9332 // For example,
9333 // (v4i16 (bitconvert
9334 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9335 // becomes
9336 // (extract_subvector ((v8i16 ...), (i64 4)))
9337
9338 // Only interested in 64-bit vectors as the ultimate result.
9339 EVT VT = N->getValueType(0);
9340 if (!VT.isVector())
9341 return SDValue();
9342 if (VT.getSimpleVT().getSizeInBits() != 64)
9343 return SDValue();
9344 // Is the operand an extract_subvector starting at the beginning or halfway
9345 // point of the vector? A low half may also come through as an
9346 // EXTRACT_SUBREG, so look for that, too.
9347 SDValue Op0 = N->getOperand(0);
9348 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9349 !(Op0->isMachineOpcode() &&
9350 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9351 return SDValue();
9352 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9353 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9354 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9355 return SDValue();
9356 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9357 if (idx != AArch64::dsub)
9358 return SDValue();
9359 // The dsub reference is equivalent to a lane zero subvector reference.
9360 idx = 0;
9361 }
9362 // Look through the bitcast of the input to the extract.
9363 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9364 return SDValue();
9365 SDValue Source = Op0->getOperand(0)->getOperand(0);
9366 // If the source type has twice the number of elements as our destination
9367 // type, we know this is an extract of the high or low half of the vector.
9368 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009369 if (!SVT.isVector() ||
9370 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009371 return SDValue();
9372
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009373 LLVM_DEBUG(
9374 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009375
9376 // Create the simplified form to just extract the low or high half of the
9377 // vector directly rather than bothering with the bitcasts.
9378 SDLoc dl(N);
9379 unsigned NumElements = VT.getVectorNumElements();
9380 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009381 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009382 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9383 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009384 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009385 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9386 Source, SubReg),
9387 0);
9388 }
9389}
9390
9391static SDValue performConcatVectorsCombine(SDNode *N,
9392 TargetLowering::DAGCombinerInfo &DCI,
9393 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009394 SDLoc dl(N);
9395 EVT VT = N->getValueType(0);
9396 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9397
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009398 // Optimize concat_vectors of truncated vectors, where the intermediate
9399 // type is illegal, to avoid said illegality, e.g.,
9400 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9401 // (v2i16 (truncate (v2i64)))))
9402 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009403 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9404 // (v4i32 (bitcast (v2i64))),
9405 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009406 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9407 // on both input and result type, so we might generate worse code.
9408 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9409 if (N->getNumOperands() == 2 &&
9410 N0->getOpcode() == ISD::TRUNCATE &&
9411 N1->getOpcode() == ISD::TRUNCATE) {
9412 SDValue N00 = N0->getOperand(0);
9413 SDValue N10 = N1->getOperand(0);
9414 EVT N00VT = N00.getValueType();
9415
9416 if (N00VT == N10.getValueType() &&
9417 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9418 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009419 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9420 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9421 for (size_t i = 0; i < Mask.size(); ++i)
9422 Mask[i] = i * 2;
9423 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9424 DAG.getVectorShuffle(
9425 MidVT, dl,
9426 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9427 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009428 }
9429 }
9430
Tim Northover3b0846e2014-05-24 12:50:23 +00009431 // Wait 'til after everything is legalized to try this. That way we have
9432 // legal vector types and such.
9433 if (DCI.isBeforeLegalizeOps())
9434 return SDValue();
9435
Tim Northover3b0846e2014-05-24 12:50:23 +00009436 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9437 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9438 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009439 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009440 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009441 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009442 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009443 }
9444
9445 // Canonicalise concat_vectors so that the right-hand vector has as few
9446 // bit-casts as possible before its real operation. The primary matching
9447 // destination for these operations will be the narrowing "2" instructions,
9448 // which depend on the operation being performed on this right-hand vector.
9449 // For example,
9450 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9451 // becomes
9452 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9453
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009454 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009455 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009456 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009457 MVT RHSTy = RHS.getValueType().getSimpleVT();
9458 // If the RHS is not a vector, this is not the pattern we're looking for.
9459 if (!RHSTy.isVector())
9460 return SDValue();
9461
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009462 LLVM_DEBUG(
9463 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009464
9465 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9466 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009467 return DAG.getNode(ISD::BITCAST, dl, VT,
9468 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9469 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9470 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009471}
9472
9473static SDValue tryCombineFixedPointConvert(SDNode *N,
9474 TargetLowering::DAGCombinerInfo &DCI,
9475 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009476 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009477 // legal vector types and such.
9478 if (DCI.isBeforeLegalizeOps())
9479 return SDValue();
9480 // Transform a scalar conversion of a value from a lane extract into a
9481 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9482 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9483 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9484 //
9485 // The second form interacts better with instruction selection and the
9486 // register allocator to avoid cross-class register copies that aren't
9487 // coalescable due to a lane reference.
9488
9489 // Check the operand and see if it originates from a lane extract.
9490 SDValue Op1 = N->getOperand(1);
9491 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9492 // Yep, no additional predication needed. Perform the transform.
9493 SDValue IID = N->getOperand(0);
9494 SDValue Shift = N->getOperand(2);
9495 SDValue Vec = Op1.getOperand(0);
9496 SDValue Lane = Op1.getOperand(1);
9497 EVT ResTy = N->getValueType(0);
9498 EVT VecResTy;
9499 SDLoc DL(N);
9500
9501 // The vector width should be 128 bits by the time we get here, even
9502 // if it started as 64 bits (the extract_vector handling will have
9503 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009504 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009505 "unexpected vector size on extract_vector_elt!");
9506 if (Vec.getValueType() == MVT::v4i32)
9507 VecResTy = MVT::v4f32;
9508 else if (Vec.getValueType() == MVT::v2i64)
9509 VecResTy = MVT::v2f64;
9510 else
Craig Topper2a30d782014-06-18 05:05:13 +00009511 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009512
9513 SDValue Convert =
9514 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9515 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9516 }
9517 return SDValue();
9518}
9519
9520// AArch64 high-vector "long" operations are formed by performing the non-high
9521// version on an extract_subvector of each operand which gets the high half:
9522//
9523// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9524//
9525// However, there are cases which don't have an extract_high explicitly, but
9526// have another operation that can be made compatible with one for free. For
9527// example:
9528//
9529// (dupv64 scalar) --> (extract_high (dup128 scalar))
9530//
9531// This routine does the actual conversion of such DUPs, once outer routines
9532// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009533// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9534// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009535static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009536 switch (N.getOpcode()) {
9537 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009538 case AArch64ISD::DUPLANE8:
9539 case AArch64ISD::DUPLANE16:
9540 case AArch64ISD::DUPLANE32:
9541 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009542 case AArch64ISD::MOVI:
9543 case AArch64ISD::MOVIshift:
9544 case AArch64ISD::MOVIedit:
9545 case AArch64ISD::MOVImsl:
9546 case AArch64ISD::MVNIshift:
9547 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009548 break;
9549 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009550 // FMOV could be supported, but isn't very useful, as it would only occur
9551 // if you passed a bitcast' floating point immediate to an eligible long
9552 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009553 return SDValue();
9554 }
9555
9556 MVT NarrowTy = N.getSimpleValueType();
9557 if (!NarrowTy.is64BitVector())
9558 return SDValue();
9559
9560 MVT ElementTy = NarrowTy.getVectorElementType();
9561 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009562 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009563
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009564 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009565 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9566 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009567 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009568}
9569
9570static bool isEssentiallyExtractSubvector(SDValue N) {
9571 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9572 return true;
9573
9574 return N.getOpcode() == ISD::BITCAST &&
9575 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9576}
9577
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009578/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009579struct GenericSetCCInfo {
9580 const SDValue *Opnd0;
9581 const SDValue *Opnd1;
9582 ISD::CondCode CC;
9583};
9584
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009585/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009586struct AArch64SetCCInfo {
9587 const SDValue *Cmp;
9588 AArch64CC::CondCode CC;
9589};
9590
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009591/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009592union SetCCInfo {
9593 GenericSetCCInfo Generic;
9594 AArch64SetCCInfo AArch64;
9595};
9596
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009597/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009598/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9599/// GenericSetCCInfo.
9600struct SetCCInfoAndKind {
9601 SetCCInfo Info;
9602 bool IsAArch64;
9603};
9604
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009605/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009606/// an
9607/// AArch64 lowered one.
9608/// \p SetCCInfo is filled accordingly.
9609/// \post SetCCInfo is meanginfull only when this function returns true.
9610/// \return True when Op is a kind of SET_CC operation.
9611static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9612 // If this is a setcc, this is straight forward.
9613 if (Op.getOpcode() == ISD::SETCC) {
9614 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9615 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9616 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9617 SetCCInfo.IsAArch64 = false;
9618 return true;
9619 }
9620 // Otherwise, check if this is a matching csel instruction.
9621 // In other words:
9622 // - csel 1, 0, cc
9623 // - csel 0, 1, !cc
9624 if (Op.getOpcode() != AArch64ISD::CSEL)
9625 return false;
9626 // Set the information about the operands.
9627 // TODO: we want the operands of the Cmp not the csel
9628 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9629 SetCCInfo.IsAArch64 = true;
9630 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9631 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9632
9633 // Check that the operands matches the constraints:
9634 // (1) Both operands must be constants.
9635 // (2) One must be 1 and the other must be 0.
9636 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9637 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9638
9639 // Check (1).
9640 if (!TValue || !FValue)
9641 return false;
9642
9643 // Check (2).
9644 if (!TValue->isOne()) {
9645 // Update the comparison when we are interested in !cc.
9646 std::swap(TValue, FValue);
9647 SetCCInfo.Info.AArch64.CC =
9648 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9649 }
9650 return TValue->isOne() && FValue->isNullValue();
9651}
9652
9653// Returns true if Op is setcc or zext of setcc.
9654static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9655 if (isSetCC(Op, Info))
9656 return true;
9657 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9658 isSetCC(Op->getOperand(0), Info));
9659}
9660
9661// The folding we want to perform is:
9662// (add x, [zext] (setcc cc ...) )
9663// -->
9664// (csel x, (add x, 1), !cc ...)
9665//
9666// The latter will get matched to a CSINC instruction.
9667static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9668 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9669 SDValue LHS = Op->getOperand(0);
9670 SDValue RHS = Op->getOperand(1);
9671 SetCCInfoAndKind InfoAndKind;
9672
9673 // If neither operand is a SET_CC, give up.
9674 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9675 std::swap(LHS, RHS);
9676 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9677 return SDValue();
9678 }
9679
9680 // FIXME: This could be generatized to work for FP comparisons.
9681 EVT CmpVT = InfoAndKind.IsAArch64
9682 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9683 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9684 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9685 return SDValue();
9686
9687 SDValue CCVal;
9688 SDValue Cmp;
9689 SDLoc dl(Op);
9690 if (InfoAndKind.IsAArch64) {
9691 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009692 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9693 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009694 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9695 } else
9696 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9697 *InfoAndKind.Info.Generic.Opnd1,
9698 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9699 CCVal, DAG, dl);
9700
9701 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009702 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009703 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9704}
9705
9706// The basic add/sub long vector instructions have variants with "2" on the end
9707// which act on the high-half of their inputs. They are normally matched by
9708// patterns like:
9709//
9710// (add (zeroext (extract_high LHS)),
9711// (zeroext (extract_high RHS)))
9712// -> uaddl2 vD, vN, vM
9713//
9714// However, if one of the extracts is something like a duplicate, this
9715// instruction can still be used profitably. This function puts the DAG into a
9716// more appropriate form for those patterns to trigger.
9717static SDValue performAddSubLongCombine(SDNode *N,
9718 TargetLowering::DAGCombinerInfo &DCI,
9719 SelectionDAG &DAG) {
9720 if (DCI.isBeforeLegalizeOps())
9721 return SDValue();
9722
9723 MVT VT = N->getSimpleValueType(0);
9724 if (!VT.is128BitVector()) {
9725 if (N->getOpcode() == ISD::ADD)
9726 return performSetccAddFolding(N, DAG);
9727 return SDValue();
9728 }
9729
9730 // Make sure both branches are extended in the same way.
9731 SDValue LHS = N->getOperand(0);
9732 SDValue RHS = N->getOperand(1);
9733 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9734 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9735 LHS.getOpcode() != RHS.getOpcode())
9736 return SDValue();
9737
9738 unsigned ExtType = LHS.getOpcode();
9739
9740 // It's not worth doing if at least one of the inputs isn't already an
9741 // extract, but we don't know which it'll be so we have to try both.
9742 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9743 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9744 if (!RHS.getNode())
9745 return SDValue();
9746
9747 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9748 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9749 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9750 if (!LHS.getNode())
9751 return SDValue();
9752
9753 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9754 }
9755
9756 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9757}
9758
9759// Massage DAGs which we can use the high-half "long" operations on into
9760// something isel will recognize better. E.g.
9761//
9762// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9763// (aarch64_neon_umull (extract_high (v2i64 vec)))
9764// (extract_high (v2i64 (dup128 scalar)))))
9765//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009766static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009767 TargetLowering::DAGCombinerInfo &DCI,
9768 SelectionDAG &DAG) {
9769 if (DCI.isBeforeLegalizeOps())
9770 return SDValue();
9771
Hal Finkelcd8664c2015-12-11 23:11:52 +00009772 SDValue LHS = N->getOperand(1);
9773 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009774 assert(LHS.getValueType().is64BitVector() &&
9775 RHS.getValueType().is64BitVector() &&
9776 "unexpected shape for long operation");
9777
9778 // Either node could be a DUP, but it's not worth doing both of them (you'd
9779 // just as well use the non-high version) so look for a corresponding extract
9780 // operation on the other "wing".
9781 if (isEssentiallyExtractSubvector(LHS)) {
9782 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9783 if (!RHS.getNode())
9784 return SDValue();
9785 } else if (isEssentiallyExtractSubvector(RHS)) {
9786 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9787 if (!LHS.getNode())
9788 return SDValue();
9789 }
9790
Hal Finkelcd8664c2015-12-11 23:11:52 +00009791 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9792 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009793}
9794
9795static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9796 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9797 unsigned ElemBits = ElemTy.getSizeInBits();
9798
9799 int64_t ShiftAmount;
9800 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9801 APInt SplatValue, SplatUndef;
9802 unsigned SplatBitSize;
9803 bool HasAnyUndefs;
9804 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9805 HasAnyUndefs, ElemBits) ||
9806 SplatBitSize != ElemBits)
9807 return SDValue();
9808
9809 ShiftAmount = SplatValue.getSExtValue();
9810 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9811 ShiftAmount = CVN->getSExtValue();
9812 } else
9813 return SDValue();
9814
9815 unsigned Opcode;
9816 bool IsRightShift;
9817 switch (IID) {
9818 default:
9819 llvm_unreachable("Unknown shift intrinsic");
9820 case Intrinsic::aarch64_neon_sqshl:
9821 Opcode = AArch64ISD::SQSHL_I;
9822 IsRightShift = false;
9823 break;
9824 case Intrinsic::aarch64_neon_uqshl:
9825 Opcode = AArch64ISD::UQSHL_I;
9826 IsRightShift = false;
9827 break;
9828 case Intrinsic::aarch64_neon_srshl:
9829 Opcode = AArch64ISD::SRSHR_I;
9830 IsRightShift = true;
9831 break;
9832 case Intrinsic::aarch64_neon_urshl:
9833 Opcode = AArch64ISD::URSHR_I;
9834 IsRightShift = true;
9835 break;
9836 case Intrinsic::aarch64_neon_sqshlu:
9837 Opcode = AArch64ISD::SQSHLU_I;
9838 IsRightShift = false;
9839 break;
9840 }
9841
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009842 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9843 SDLoc dl(N);
9844 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9845 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9846 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9847 SDLoc dl(N);
9848 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9849 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9850 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009851
9852 return SDValue();
9853}
9854
9855// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9856// the intrinsics must be legal and take an i32, this means there's almost
9857// certainly going to be a zext in the DAG which we can eliminate.
9858static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9859 SDValue AndN = N->getOperand(2);
9860 if (AndN.getOpcode() != ISD::AND)
9861 return SDValue();
9862
9863 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9864 if (!CMask || CMask->getZExtValue() != Mask)
9865 return SDValue();
9866
9867 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9868 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9869}
9870
Ahmed Bougachafab58922015-03-10 20:45:38 +00009871static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9872 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009873 SDLoc dl(N);
9874 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9875 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009876 N->getOperand(1).getSimpleValueType(),
9877 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009878 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009879}
9880
Tim Northover3b0846e2014-05-24 12:50:23 +00009881static SDValue performIntrinsicCombine(SDNode *N,
9882 TargetLowering::DAGCombinerInfo &DCI,
9883 const AArch64Subtarget *Subtarget) {
9884 SelectionDAG &DAG = DCI.DAG;
9885 unsigned IID = getIntrinsicID(N);
9886 switch (IID) {
9887 default:
9888 break;
9889 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9890 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9891 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00009892 case Intrinsic::aarch64_neon_saddv:
9893 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9894 case Intrinsic::aarch64_neon_uaddv:
9895 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9896 case Intrinsic::aarch64_neon_sminv:
9897 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9898 case Intrinsic::aarch64_neon_uminv:
9899 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9900 case Intrinsic::aarch64_neon_smaxv:
9901 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9902 case Intrinsic::aarch64_neon_umaxv:
9903 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009904 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +00009905 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009906 N->getOperand(1), N->getOperand(2));
9907 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +00009908 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009909 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00009910 case Intrinsic::aarch64_neon_fmaxnm:
9911 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9912 N->getOperand(1), N->getOperand(2));
9913 case Intrinsic::aarch64_neon_fminnm:
9914 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9915 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009916 case Intrinsic::aarch64_neon_smull:
9917 case Intrinsic::aarch64_neon_umull:
9918 case Intrinsic::aarch64_neon_pmull:
9919 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00009920 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009921 case Intrinsic::aarch64_neon_sqshl:
9922 case Intrinsic::aarch64_neon_uqshl:
9923 case Intrinsic::aarch64_neon_sqshlu:
9924 case Intrinsic::aarch64_neon_srshl:
9925 case Intrinsic::aarch64_neon_urshl:
9926 return tryCombineShiftImm(IID, N, DAG);
9927 case Intrinsic::aarch64_crc32b:
9928 case Intrinsic::aarch64_crc32cb:
9929 return tryCombineCRC32(0xff, N, DAG);
9930 case Intrinsic::aarch64_crc32h:
9931 case Intrinsic::aarch64_crc32ch:
9932 return tryCombineCRC32(0xffff, N, DAG);
9933 }
9934 return SDValue();
9935}
9936
9937static SDValue performExtendCombine(SDNode *N,
9938 TargetLowering::DAGCombinerInfo &DCI,
9939 SelectionDAG &DAG) {
9940 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9941 // we can convert that DUP into another extract_high (of a bigger DUP), which
9942 // helps the backend to decide that an sabdl2 would be useful, saving a real
9943 // extract_high operation.
9944 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00009945 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009946 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00009947 unsigned IID = getIntrinsicID(ABDNode);
9948 if (IID == Intrinsic::aarch64_neon_sabd ||
9949 IID == Intrinsic::aarch64_neon_uabd) {
9950 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9951 if (!NewABD.getNode())
9952 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009953
Hal Finkelcd8664c2015-12-11 23:11:52 +00009954 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9955 NewABD);
9956 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009957 }
9958
9959 // This is effectively a custom type legalization for AArch64.
9960 //
9961 // Type legalization will split an extend of a small, legal, type to a larger
9962 // illegal type by first splitting the destination type, often creating
9963 // illegal source types, which then get legalized in isel-confusing ways,
9964 // leading to really terrible codegen. E.g.,
9965 // %result = v8i32 sext v8i8 %value
9966 // becomes
9967 // %losrc = extract_subreg %value, ...
9968 // %hisrc = extract_subreg %value, ...
9969 // %lo = v4i32 sext v4i8 %losrc
9970 // %hi = v4i32 sext v4i8 %hisrc
9971 // Things go rapidly downhill from there.
9972 //
9973 // For AArch64, the [sz]ext vector instructions can only go up one element
9974 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9975 // take two instructions.
9976 //
9977 // This implies that the most efficient way to do the extend from v8i8
9978 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9979 // the normal splitting to happen for the v8i16->v8i32.
9980
9981 // This is pre-legalization to catch some cases where the default
9982 // type legalization will create ill-tempered code.
9983 if (!DCI.isBeforeLegalizeOps())
9984 return SDValue();
9985
9986 // We're only interested in cleaning things up for non-legal vector types
9987 // here. If both the source and destination are legal, things will just
9988 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00009989 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00009990 EVT ResVT = N->getValueType(0);
9991 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9992 return SDValue();
9993 // If the vector type isn't a simple VT, it's beyond the scope of what
9994 // we're worried about here. Let legalization do its thing and hope for
9995 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00009996 SDValue Src = N->getOperand(0);
9997 EVT SrcVT = Src->getValueType(0);
9998 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00009999 return SDValue();
10000
Tim Northover3b0846e2014-05-24 12:50:23 +000010001 // If the source VT is a 64-bit vector, we can play games and get the
10002 // better results we want.
10003 if (SrcVT.getSizeInBits() != 64)
10004 return SDValue();
10005
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010006 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010007 unsigned ElementCount = SrcVT.getVectorNumElements();
10008 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10009 SDLoc DL(N);
10010 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10011
10012 // Now split the rest of the operation into two halves, each with a 64
10013 // bit source.
10014 EVT LoVT, HiVT;
10015 SDValue Lo, Hi;
10016 unsigned NumElements = ResVT.getVectorNumElements();
10017 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10018 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10019 ResVT.getVectorElementType(), NumElements / 2);
10020
10021 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10022 LoVT.getVectorNumElements());
10023 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010024 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010025 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010026 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010027 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10028 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10029
10030 // Now combine the parts back together so we still have a single result
10031 // like the combiner expects.
10032 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10033}
10034
Geoff Berry8301c642016-11-16 19:35:19 +000010035static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10036 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010037 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010038 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010039
10040 // Create scalar stores. This is at least as good as the code sequence for a
10041 // split unaligned store which is a dup.s, ext.b, and two stores.
10042 // Most of the time the three stores should be replaced by store pair
10043 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010044 SDLoc DL(&St);
10045 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010046 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010047
John Brawn3a9c8422017-02-06 18:07:20 +000010048 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010049 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010050 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010051 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010052
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010053 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010054 if (BasePtr->getOpcode() == ISD::ADD &&
10055 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10056 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10057 BasePtr = BasePtr->getOperand(0);
10058 }
10059
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010060 unsigned Offset = EltOffset;
10061 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010062 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010063 SDValue OffsetPtr =
10064 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10065 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010066 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010067 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010068 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010069 Offset += EltOffset;
10070 }
10071 return NewST1;
10072}
10073
Geoff Berry526c5052016-11-14 19:39:04 +000010074/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10075/// load store optimizer pass will merge them to store pair stores. This should
10076/// be better than a movi to create the vector zero followed by a vector store
10077/// if the zero constant is not re-used, since one instructions and one register
10078/// live range will be removed.
10079///
10080/// For example, the final generated code should be:
10081///
10082/// stp xzr, xzr, [x0]
10083///
10084/// instead of:
10085///
10086/// movi v0.2d, #0
10087/// str q0, [x0]
10088///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010089static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10090 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010091 EVT VT = StVal.getValueType();
10092
Geoff Berry8301c642016-11-16 19:35:19 +000010093 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10094 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010095 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010096 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10097 VT.getVectorElementType().getSizeInBits() == 64) ||
10098 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10099 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010100 return SDValue();
10101
10102 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10103 return SDValue();
10104
10105 // If the zero constant has more than one use then the vector store could be
10106 // better since the constant mov will be amortized and stp q instructions
10107 // should be able to be formed.
10108 if (!StVal.hasOneUse())
10109 return SDValue();
10110
10111 // If the immediate offset of the address operand is too large for the stp
10112 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010113 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10114 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010115 if (Offset < -512 || Offset > 504)
10116 return SDValue();
10117 }
10118
10119 for (int I = 0; I < NumVecElts; ++I) {
10120 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010121 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010122 return SDValue();
10123 }
Geoff Berry8301c642016-11-16 19:35:19 +000010124
Geoff Berrybb23df92017-09-21 21:10:06 +000010125 // Use a CopyFromReg WZR/XZR here to prevent
10126 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10127 SDLoc DL(&St);
10128 unsigned ZeroReg;
10129 EVT ZeroVT;
10130 if (VT.getVectorElementType().getSizeInBits() == 32) {
10131 ZeroReg = AArch64::WZR;
10132 ZeroVT = MVT::i32;
10133 } else {
10134 ZeroReg = AArch64::XZR;
10135 ZeroVT = MVT::i64;
10136 }
10137 SDValue SplatVal =
10138 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010139 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010140}
10141
Tim Northover3b0846e2014-05-24 12:50:23 +000010142/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10143/// value. The load store optimizer pass will merge them to store pair stores.
10144/// This has better performance than a splat of the scalar followed by a split
10145/// vector store. Even if the stores are not merged it is four stores vs a dup,
10146/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010147static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10148 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010149 EVT VT = StVal.getValueType();
10150
10151 // Don't replace floating point stores, they possibly won't be transformed to
10152 // stp because of the store pair suppress pass.
10153 if (VT.isFloatingPoint())
10154 return SDValue();
10155
Tim Northover3b0846e2014-05-24 12:50:23 +000010156 // We can express a splat as store pair(s) for 2 or 4 elements.
10157 unsigned NumVecElts = VT.getVectorNumElements();
10158 if (NumVecElts != 4 && NumVecElts != 2)
10159 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010160
10161 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010162 // Make sure that each of the relevant vector element locations are inserted
10163 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10164 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10165 SDValue SplatVal;
10166 for (unsigned I = 0; I < NumVecElts; ++I) {
10167 // Check for insert vector elements.
10168 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010169 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010170
10171 // Check that same value is inserted at each vector element.
10172 if (I == 0)
10173 SplatVal = StVal.getOperand(1);
10174 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010175 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010176
10177 // Check insert element index.
10178 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10179 if (!CIndex)
10180 return SDValue();
10181 uint64_t IndexVal = CIndex->getZExtValue();
10182 if (IndexVal >= NumVecElts)
10183 return SDValue();
10184 IndexNotInserted.reset(IndexVal);
10185
10186 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010187 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010188 // Check that all vector element locations were inserted to.
10189 if (IndexNotInserted.any())
10190 return SDValue();
10191
Geoff Berry8301c642016-11-16 19:35:19 +000010192 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010193}
10194
Geoff Berry8301c642016-11-16 19:35:19 +000010195static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10196 SelectionDAG &DAG,
10197 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010198
10199 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010200 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010201 return SDValue();
10202
Geoff Berry526c5052016-11-14 19:39:04 +000010203 SDValue StVal = S->getValue();
10204 EVT VT = StVal.getValueType();
10205 if (!VT.isVector())
10206 return SDValue();
10207
10208 // If we get a splat of zeros, convert this vector store to a store of
10209 // scalars. They will be merged into store pairs of xzr thereby removing one
10210 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010211 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010212 return ReplacedZeroSplat;
10213
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010214 // FIXME: The logic for deciding if an unaligned store should be split should
10215 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10216 // a call to that function here.
10217
Matthias Braun651cff42016-06-02 18:03:53 +000010218 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010219 return SDValue();
10220
Sanjay Patel924879a2015-08-04 15:49:57 +000010221 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +000010222 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010223 return SDValue();
10224
Tim Northover3b0846e2014-05-24 12:50:23 +000010225 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10226 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010227 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010228 return SDValue();
10229
10230 // Split unaligned 16B stores. They are terrible for performance.
10231 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10232 // extensions can use this to mark that it does not want splitting to happen
10233 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10234 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10235 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10236 S->getAlignment() <= 2)
10237 return SDValue();
10238
10239 // If we get a splat of a scalar convert this vector store to a store of
10240 // scalars. They will be merged into store pairs thereby removing two
10241 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010242 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010243 return ReplacedSplat;
10244
10245 SDLoc DL(S);
10246 unsigned NumElts = VT.getVectorNumElements() / 2;
10247 // Split VT into two.
10248 EVT HalfVT =
10249 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10250 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010251 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010252 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010253 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010254 SDValue BasePtr = S->getBasePtr();
10255 SDValue NewST1 =
10256 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010257 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010258 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010259 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010260 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010261 S->getPointerInfo(), S->getAlignment(),
10262 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010263}
10264
10265/// Target-specific DAG combine function for post-increment LD1 (lane) and
10266/// post-increment LD1R.
10267static SDValue performPostLD1Combine(SDNode *N,
10268 TargetLowering::DAGCombinerInfo &DCI,
10269 bool IsLaneOp) {
10270 if (DCI.isBeforeLegalizeOps())
10271 return SDValue();
10272
10273 SelectionDAG &DAG = DCI.DAG;
10274 EVT VT = N->getValueType(0);
10275
10276 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10277 SDNode *LD = N->getOperand(LoadIdx).getNode();
10278 // If it is not LOAD, can not do such combine.
10279 if (LD->getOpcode() != ISD::LOAD)
10280 return SDValue();
10281
Geoff Berry60460262018-05-11 16:25:06 +000010282 // The vector lane must be a constant in the LD1LANE opcode.
10283 SDValue Lane;
10284 if (IsLaneOp) {
10285 Lane = N->getOperand(2);
10286 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10287 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10288 return SDValue();
10289 }
10290
Tim Northover3b0846e2014-05-24 12:50:23 +000010291 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10292 EVT MemVT = LoadSDN->getMemoryVT();
10293 // Check if memory operand is the same type as the vector element.
10294 if (MemVT != VT.getVectorElementType())
10295 return SDValue();
10296
10297 // Check if there are other uses. If so, do not combine as it will introduce
10298 // an extra load.
10299 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10300 ++UI) {
10301 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10302 continue;
10303 if (*UI != N)
10304 return SDValue();
10305 }
10306
10307 SDValue Addr = LD->getOperand(1);
10308 SDValue Vector = N->getOperand(0);
10309 // Search for a use of the address operand that is an increment.
10310 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10311 Addr.getNode()->use_end(); UI != UE; ++UI) {
10312 SDNode *User = *UI;
10313 if (User->getOpcode() != ISD::ADD
10314 || UI.getUse().getResNo() != Addr.getResNo())
10315 continue;
10316
Tim Northover3b0846e2014-05-24 12:50:23 +000010317 // If the increment is a constant, it must match the memory ref size.
10318 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10319 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10320 uint32_t IncVal = CInc->getZExtValue();
10321 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10322 if (IncVal != NumBytes)
10323 continue;
10324 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10325 }
10326
Nirav Davee40e2bb2018-09-25 15:30:22 +000010327 // To avoid cycle construction make sure that neither the load nor the add
10328 // are predecessors to each other or the Vector.
10329 SmallPtrSet<const SDNode *, 32> Visited;
10330 SmallVector<const SDNode *, 16> Worklist;
10331 Visited.insert(N);
10332 Worklist.push_back(User);
10333 Worklist.push_back(LD);
10334 Worklist.push_back(Vector.getNode());
10335 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10336 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010337 continue;
10338
Tim Northover3b0846e2014-05-24 12:50:23 +000010339 SmallVector<SDValue, 8> Ops;
10340 Ops.push_back(LD->getOperand(0)); // Chain
10341 if (IsLaneOp) {
10342 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010343 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010344 }
10345 Ops.push_back(Addr);
10346 Ops.push_back(Inc);
10347
10348 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010349 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010350 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10351 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10352 MemVT,
10353 LoadSDN->getMemOperand());
10354
10355 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010356 SDValue NewResults[] = {
10357 SDValue(LD, 0), // The result of load
10358 SDValue(UpdN.getNode(), 2) // Chain
10359 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010360 DCI.CombineTo(LD, NewResults);
10361 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10362 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10363
10364 break;
10365 }
10366 return SDValue();
10367}
10368
Joel Jones7466ccf2017-07-10 22:11:50 +000010369/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010370/// address translation.
10371static bool performTBISimplification(SDValue Addr,
10372 TargetLowering::DAGCombinerInfo &DCI,
10373 SelectionDAG &DAG) {
10374 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010375 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010376 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10377 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010379 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010380 DCI.CommitTargetLoweringOpt(TLO);
10381 return true;
10382 }
10383 return false;
10384}
10385
10386static SDValue performSTORECombine(SDNode *N,
10387 TargetLowering::DAGCombinerInfo &DCI,
10388 SelectionDAG &DAG,
10389 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010390 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010391 return Split;
10392
10393 if (Subtarget->supportsAddressTopByteIgnored() &&
10394 performTBISimplification(N->getOperand(2), DCI, DAG))
10395 return SDValue(N, 0);
10396
10397 return SDValue();
10398}
10399
Chad Rosier6c36eff2015-09-03 18:13:57 +000010400
Tim Northover3b0846e2014-05-24 12:50:23 +000010401/// Target-specific DAG combine function for NEON load/store intrinsics
10402/// to merge base address updates.
10403static SDValue performNEONPostLDSTCombine(SDNode *N,
10404 TargetLowering::DAGCombinerInfo &DCI,
10405 SelectionDAG &DAG) {
10406 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10407 return SDValue();
10408
10409 unsigned AddrOpIdx = N->getNumOperands() - 1;
10410 SDValue Addr = N->getOperand(AddrOpIdx);
10411
10412 // Search for a use of the address operand that is an increment.
10413 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10414 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10415 SDNode *User = *UI;
10416 if (User->getOpcode() != ISD::ADD ||
10417 UI.getUse().getResNo() != Addr.getResNo())
10418 continue;
10419
10420 // Check that the add is independent of the load/store. Otherwise, folding
10421 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010422 SmallPtrSet<const SDNode *, 32> Visited;
10423 SmallVector<const SDNode *, 16> Worklist;
10424 Visited.insert(Addr.getNode());
10425 Worklist.push_back(N);
10426 Worklist.push_back(User);
10427 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10428 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010429 continue;
10430
10431 // Find the new opcode for the updating load/store.
10432 bool IsStore = false;
10433 bool IsLaneOp = false;
10434 bool IsDupOp = false;
10435 unsigned NewOpc = 0;
10436 unsigned NumVecs = 0;
10437 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10438 switch (IntNo) {
10439 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10440 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10441 NumVecs = 2; break;
10442 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10443 NumVecs = 3; break;
10444 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10445 NumVecs = 4; break;
10446 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10447 NumVecs = 2; IsStore = true; break;
10448 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10449 NumVecs = 3; IsStore = true; break;
10450 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10451 NumVecs = 4; IsStore = true; break;
10452 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10453 NumVecs = 2; break;
10454 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10455 NumVecs = 3; break;
10456 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10457 NumVecs = 4; break;
10458 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10459 NumVecs = 2; IsStore = true; break;
10460 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10461 NumVecs = 3; IsStore = true; break;
10462 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10463 NumVecs = 4; IsStore = true; break;
10464 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10465 NumVecs = 2; IsDupOp = true; break;
10466 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10467 NumVecs = 3; IsDupOp = true; break;
10468 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10469 NumVecs = 4; IsDupOp = true; break;
10470 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10471 NumVecs = 2; IsLaneOp = true; break;
10472 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10473 NumVecs = 3; IsLaneOp = true; break;
10474 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10475 NumVecs = 4; IsLaneOp = true; break;
10476 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10477 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10478 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10479 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10480 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10481 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10482 }
10483
10484 EVT VecTy;
10485 if (IsStore)
10486 VecTy = N->getOperand(2).getValueType();
10487 else
10488 VecTy = N->getValueType(0);
10489
10490 // If the increment is a constant, it must match the memory ref size.
10491 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10492 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10493 uint32_t IncVal = CInc->getZExtValue();
10494 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10495 if (IsLaneOp || IsDupOp)
10496 NumBytes /= VecTy.getVectorNumElements();
10497 if (IncVal != NumBytes)
10498 continue;
10499 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10500 }
10501 SmallVector<SDValue, 8> Ops;
10502 Ops.push_back(N->getOperand(0)); // Incoming chain
10503 // Load lane and store have vector list as input.
10504 if (IsLaneOp || IsStore)
10505 for (unsigned i = 2; i < AddrOpIdx; ++i)
10506 Ops.push_back(N->getOperand(i));
10507 Ops.push_back(Addr); // Base register
10508 Ops.push_back(Inc);
10509
10510 // Return Types.
10511 EVT Tys[6];
10512 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10513 unsigned n;
10514 for (n = 0; n < NumResultVecs; ++n)
10515 Tys[n] = VecTy;
10516 Tys[n++] = MVT::i64; // Type of write back register
10517 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010518 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010519
10520 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10521 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10522 MemInt->getMemoryVT(),
10523 MemInt->getMemOperand());
10524
10525 // Update the uses.
10526 std::vector<SDValue> NewResults;
10527 for (unsigned i = 0; i < NumResultVecs; ++i) {
10528 NewResults.push_back(SDValue(UpdN.getNode(), i));
10529 }
10530 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10531 DCI.CombineTo(N, NewResults);
10532 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10533
10534 break;
10535 }
10536 return SDValue();
10537}
10538
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010539// Checks to see if the value is the prescribed width and returns information
10540// about its extension mode.
10541static
10542bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10543 ExtType = ISD::NON_EXTLOAD;
10544 switch(V.getNode()->getOpcode()) {
10545 default:
10546 return false;
10547 case ISD::LOAD: {
10548 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10549 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10550 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10551 ExtType = LoadNode->getExtensionType();
10552 return true;
10553 }
10554 return false;
10555 }
10556 case ISD::AssertSext: {
10557 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10558 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10559 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10560 ExtType = ISD::SEXTLOAD;
10561 return true;
10562 }
10563 return false;
10564 }
10565 case ISD::AssertZext: {
10566 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10567 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10568 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10569 ExtType = ISD::ZEXTLOAD;
10570 return true;
10571 }
10572 return false;
10573 }
10574 case ISD::Constant:
10575 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010576 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10577 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010578 }
10579 }
10580
10581 return true;
10582}
10583
10584// This function does a whole lot of voodoo to determine if the tests are
10585// equivalent without and with a mask. Essentially what happens is that given a
10586// DAG resembling:
10587//
10588// +-------------+ +-------------+ +-------------+ +-------------+
10589// | Input | | AddConstant | | CompConstant| | CC |
10590// +-------------+ +-------------+ +-------------+ +-------------+
10591// | | | |
10592// V V | +----------+
10593// +-------------+ +----+ | |
10594// | ADD | |0xff| | |
10595// +-------------+ +----+ | |
10596// | | | |
10597// V V | |
10598// +-------------+ | |
10599// | AND | | |
10600// +-------------+ | |
10601// | | |
10602// +-----+ | |
10603// | | |
10604// V V V
10605// +-------------+
10606// | CMP |
10607// +-------------+
10608//
10609// The AND node may be safely removed for some combinations of inputs. In
10610// particular we need to take into account the extension type of the Input,
10611// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10612// width of the input (this can work for any width inputs, the above graph is
10613// specific to 8 bits.
10614//
10615// The specific equations were worked out by generating output tables for each
10616// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10617// problem was simplified by working with 4 bit inputs, which means we only
10618// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10619// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10620// patterns present in both extensions (0,7). For every distinct set of
10621// AddConstant and CompConstants bit patterns we can consider the masked and
10622// unmasked versions to be equivalent if the result of this function is true for
10623// all 16 distinct bit patterns of for the current extension type of Input (w0).
10624//
10625// sub w8, w0, w1
10626// and w10, w8, #0x0f
10627// cmp w8, w2
10628// cset w9, AArch64CC
10629// cmp w10, w2
10630// cset w11, AArch64CC
10631// cmp w9, w11
10632// cset w0, eq
10633// ret
10634//
10635// Since the above function shows when the outputs are equivalent it defines
10636// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10637// would be expensive to run during compiles. The equations below were written
10638// in a test harness that confirmed they gave equivalent outputs to the above
10639// for all inputs function, so they can be used determine if the removal is
10640// legal instead.
10641//
10642// isEquivalentMaskless() is the code for testing if the AND can be removed
10643// factored out of the DAG recognition as the DAG can take several forms.
10644
David Majnemere61e4bf2016-06-21 05:10:24 +000010645static bool isEquivalentMaskless(unsigned CC, unsigned width,
10646 ISD::LoadExtType ExtType, int AddConstant,
10647 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010648 // By being careful about our equations and only writing the in term
10649 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10650 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010651 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010652
10653 // For the purposes of these comparisons sign extending the type is
10654 // equivalent to zero extending the add and displacing it by half the integer
10655 // width. Provided we are careful and make sure our equations are valid over
10656 // the whole range we can just adjust the input and avoid writing equations
10657 // for sign extended inputs.
10658 if (ExtType == ISD::SEXTLOAD)
10659 AddConstant -= (1 << (width-1));
10660
10661 switch(CC) {
10662 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010663 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010664 if ((AddConstant == 0) ||
10665 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10666 (AddConstant >= 0 && CompConstant < 0) ||
10667 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10668 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010669 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010670 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010671 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010672 if ((AddConstant == 0) ||
10673 (AddConstant >= 0 && CompConstant <= 0) ||
10674 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10675 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010676 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010677 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010678 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010679 if ((AddConstant >= 0 && CompConstant < 0) ||
10680 (AddConstant <= 0 && CompConstant >= -1 &&
10681 CompConstant < AddConstant + MaxUInt))
10682 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010683 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010684 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010685 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010686 if ((AddConstant == 0) ||
10687 (AddConstant > 0 && CompConstant <= 0) ||
10688 (AddConstant < 0 && CompConstant <= AddConstant))
10689 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010690 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010691 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010692 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010693 if ((AddConstant >= 0 && CompConstant <= 0) ||
10694 (AddConstant <= 0 && CompConstant >= 0 &&
10695 CompConstant <= AddConstant + MaxUInt))
10696 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010697 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010698 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010699 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010700 if ((AddConstant > 0 && CompConstant < 0) ||
10701 (AddConstant < 0 && CompConstant >= 0 &&
10702 CompConstant < AddConstant + MaxUInt) ||
10703 (AddConstant >= 0 && CompConstant >= 0 &&
10704 CompConstant >= AddConstant) ||
10705 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010706 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010707 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010708 case AArch64CC::VS:
10709 case AArch64CC::VC:
10710 case AArch64CC::AL:
10711 case AArch64CC::NV:
10712 return true;
10713 case AArch64CC::Invalid:
10714 break;
10715 }
10716
10717 return false;
10718}
10719
10720static
10721SDValue performCONDCombine(SDNode *N,
10722 TargetLowering::DAGCombinerInfo &DCI,
10723 SelectionDAG &DAG, unsigned CCIndex,
10724 unsigned CmpIndex) {
10725 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10726 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10727 unsigned CondOpcode = SubsNode->getOpcode();
10728
10729 if (CondOpcode != AArch64ISD::SUBS)
10730 return SDValue();
10731
10732 // There is a SUBS feeding this condition. Is it fed by a mask we can
10733 // use?
10734
10735 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10736 unsigned MaskBits = 0;
10737
10738 if (AndNode->getOpcode() != ISD::AND)
10739 return SDValue();
10740
10741 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10742 uint32_t CNV = CN->getZExtValue();
10743 if (CNV == 255)
10744 MaskBits = 8;
10745 else if (CNV == 65535)
10746 MaskBits = 16;
10747 }
10748
10749 if (!MaskBits)
10750 return SDValue();
10751
10752 SDValue AddValue = AndNode->getOperand(0);
10753
10754 if (AddValue.getOpcode() != ISD::ADD)
10755 return SDValue();
10756
10757 // The basic dag structure is correct, grab the inputs and validate them.
10758
10759 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10760 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10761 SDValue SubsInputValue = SubsNode->getOperand(1);
10762
10763 // The mask is present and the provenance of all the values is a smaller type,
10764 // lets see if the mask is superfluous.
10765
10766 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10767 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10768 return SDValue();
10769
10770 ISD::LoadExtType ExtType;
10771
10772 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10773 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10774 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10775 return SDValue();
10776
10777 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10778 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10779 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10780 return SDValue();
10781
10782 // The AND is not necessary, remove it.
10783
10784 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10785 SubsNode->getValueType(1));
10786 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10787
10788 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10789 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10790
10791 return SDValue(N, 0);
10792}
10793
Tim Northover3b0846e2014-05-24 12:50:23 +000010794// Optimize compare with zero and branch.
10795static SDValue performBRCONDCombine(SDNode *N,
10796 TargetLowering::DAGCombinerInfo &DCI,
10797 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010798 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010799 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010800 SDValue Chain = N->getOperand(0);
10801 SDValue Dest = N->getOperand(1);
10802 SDValue CCVal = N->getOperand(2);
10803 SDValue Cmp = N->getOperand(3);
10804
10805 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10806 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10807 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10808 return SDValue();
10809
10810 unsigned CmpOpc = Cmp.getOpcode();
10811 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10812 return SDValue();
10813
10814 // Only attempt folding if there is only one use of the flag and no use of the
10815 // value.
10816 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10817 return SDValue();
10818
10819 SDValue LHS = Cmp.getOperand(0);
10820 SDValue RHS = Cmp.getOperand(1);
10821
10822 assert(LHS.getValueType() == RHS.getValueType() &&
10823 "Expected the value type to be the same for both operands!");
10824 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10825 return SDValue();
10826
Artyom Skrobov314ee042015-11-25 19:41:11 +000010827 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010828 std::swap(LHS, RHS);
10829
Artyom Skrobov314ee042015-11-25 19:41:11 +000010830 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010831 return SDValue();
10832
10833 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10834 LHS.getOpcode() == ISD::SRL)
10835 return SDValue();
10836
10837 // Fold the compare into the branch instruction.
10838 SDValue BR;
10839 if (CC == AArch64CC::EQ)
10840 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10841 else
10842 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10843
10844 // Do not add new nodes to DAG combiner worklist.
10845 DCI.CombineTo(N, BR, false);
10846
10847 return SDValue();
10848}
10849
Geoff Berry9e934b02016-01-04 18:55:47 +000010850// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10851// as well as whether the test should be inverted. This code is required to
10852// catch these cases (as opposed to standard dag combines) because
10853// AArch64ISD::TBZ is matched during legalization.
10854static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10855 SelectionDAG &DAG) {
10856
10857 if (!Op->hasOneUse())
10858 return Op;
10859
10860 // We don't handle undef/constant-fold cases below, as they should have
10861 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10862 // etc.)
10863
10864 // (tbz (trunc x), b) -> (tbz x, b)
10865 // This case is just here to enable more of the below cases to be caught.
10866 if (Op->getOpcode() == ISD::TRUNCATE &&
10867 Bit < Op->getValueType(0).getSizeInBits()) {
10868 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10869 }
10870
10871 if (Op->getNumOperands() != 2)
10872 return Op;
10873
10874 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10875 if (!C)
10876 return Op;
10877
10878 switch (Op->getOpcode()) {
10879 default:
10880 return Op;
10881
10882 // (tbz (and x, m), b) -> (tbz x, b)
10883 case ISD::AND:
10884 if ((C->getZExtValue() >> Bit) & 1)
10885 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10886 return Op;
10887
10888 // (tbz (shl x, c), b) -> (tbz x, b-c)
10889 case ISD::SHL:
10890 if (C->getZExtValue() <= Bit &&
10891 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10892 Bit = Bit - C->getZExtValue();
10893 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10894 }
10895 return Op;
10896
10897 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10898 case ISD::SRA:
10899 Bit = Bit + C->getZExtValue();
10900 if (Bit >= Op->getValueType(0).getSizeInBits())
10901 Bit = Op->getValueType(0).getSizeInBits() - 1;
10902 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10903
10904 // (tbz (srl x, c), b) -> (tbz x, b+c)
10905 case ISD::SRL:
10906 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10907 Bit = Bit + C->getZExtValue();
10908 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10909 }
10910 return Op;
10911
10912 // (tbz (xor x, -1), b) -> (tbnz x, b)
10913 case ISD::XOR:
10914 if ((C->getZExtValue() >> Bit) & 1)
10915 Invert = !Invert;
10916 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10917 }
10918}
10919
10920// Optimize test single bit zero/non-zero and branch.
10921static SDValue performTBZCombine(SDNode *N,
10922 TargetLowering::DAGCombinerInfo &DCI,
10923 SelectionDAG &DAG) {
10924 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10925 bool Invert = false;
10926 SDValue TestSrc = N->getOperand(1);
10927 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10928
10929 if (TestSrc == NewTestSrc)
10930 return SDValue();
10931
10932 unsigned NewOpc = N->getOpcode();
10933 if (Invert) {
10934 if (NewOpc == AArch64ISD::TBZ)
10935 NewOpc = AArch64ISD::TBNZ;
10936 else {
10937 assert(NewOpc == AArch64ISD::TBNZ);
10938 NewOpc = AArch64ISD::TBZ;
10939 }
10940 }
10941
10942 SDLoc DL(N);
10943 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10944 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10945}
10946
Tim Northover3b0846e2014-05-24 12:50:23 +000010947// vselect (v1i1 setcc) ->
10948// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10949// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10950// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10951// such VSELECT.
10952static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10953 SDValue N0 = N->getOperand(0);
10954 EVT CCVT = N0.getValueType();
10955
10956 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10957 CCVT.getVectorElementType() != MVT::i1)
10958 return SDValue();
10959
10960 EVT ResVT = N->getValueType(0);
10961 EVT CmpVT = N0.getOperand(0).getValueType();
10962 // Only combine when the result type is of the same size as the compared
10963 // operands.
10964 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10965 return SDValue();
10966
10967 SDValue IfTrue = N->getOperand(1);
10968 SDValue IfFalse = N->getOperand(2);
10969 SDValue SetCC =
10970 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10971 N0.getOperand(0), N0.getOperand(1),
10972 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10973 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10974 IfTrue, IfFalse);
10975}
10976
10977/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10978/// the compare-mask instructions rather than going via NZCV, even if LHS and
10979/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10980/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010981static SDValue performSelectCombine(SDNode *N,
10982 TargetLowering::DAGCombinerInfo &DCI) {
10983 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010984 SDValue N0 = N->getOperand(0);
10985 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010986
Ahmed Bougachac004c602015-04-27 21:43:12 +000010987 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010988 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010989
Ahmed Bougachac004c602015-04-27 21:43:12 +000010990 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10991 // scalar SetCCResultType. We also don't expect vectors, because we assume
10992 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10993 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10994 "Scalar-SETCC feeding SELECT has unexpected result type!");
10995
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010996 // If NumMaskElts == 0, the comparison is larger than select result. The
10997 // largest real NEON comparison is 64-bits per lane, which means the result is
10998 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010999 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011000
11001 // Don't try to do this optimization when the setcc itself has i1 operands.
11002 // There are no legal vectors of i1, so this would be pointless.
11003 if (SrcVT == MVT::i1)
11004 return SDValue();
11005
Tim Northover3c0915e2014-08-29 15:34:58 +000011006 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011007 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011008 return SDValue();
11009
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011010 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011011 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11012
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011013 // Also bail out if the vector CCVT isn't the same size as ResVT.
11014 // This can happen if the SETCC operand size doesn't divide the ResVT size
11015 // (e.g., f64 vs v3f32).
11016 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11017 return SDValue();
11018
Ahmed Bougachac004c602015-04-27 21:43:12 +000011019 // Make sure we didn't create illegal types, if we're not supposed to.
11020 assert(DCI.isBeforeLegalize() ||
11021 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11022
Tim Northover3b0846e2014-05-24 12:50:23 +000011023 // First perform a vector comparison, where lane 0 is the one we're interested
11024 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011025 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011026 SDValue LHS =
11027 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11028 SDValue RHS =
11029 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11030 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11031
11032 // Now duplicate the comparison mask we want across all other lanes.
11033 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011034 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011035 Mask = DAG.getNode(ISD::BITCAST, DL,
11036 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011037
11038 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11039}
11040
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011041/// Get rid of unnecessary NVCASTs (that don't change the type).
11042static SDValue performNVCASTCombine(SDNode *N) {
11043 if (N->getValueType(0) == N->getOperand(0).getValueType())
11044 return N->getOperand(0);
11045
11046 return SDValue();
11047}
11048
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011049// If all users of the globaladdr are of the form (globaladdr + constant), find
11050// the smallest constant, fold it into the globaladdr's offset and rewrite the
11051// globaladdr as (globaladdr + constant) - constant.
11052static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11053 const AArch64Subtarget *Subtarget,
11054 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011055 auto *GN = cast<GlobalAddressSDNode>(N);
11056 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11057 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011058 return SDValue();
11059
11060 uint64_t MinOffset = -1ull;
11061 for (SDNode *N : GN->uses()) {
11062 if (N->getOpcode() != ISD::ADD)
11063 return SDValue();
11064 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11065 if (!C)
11066 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11067 if (!C)
11068 return SDValue();
11069 MinOffset = std::min(MinOffset, C->getZExtValue());
11070 }
11071 uint64_t Offset = MinOffset + GN->getOffset();
11072
11073 // Require that the new offset is larger than the existing one. Otherwise, we
11074 // can end up oscillating between two possible DAGs, for example,
11075 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11076 if (Offset <= uint64_t(GN->getOffset()))
11077 return SDValue();
11078
11079 // Check whether folding this offset is legal. It must not go out of bounds of
11080 // the referenced object to avoid violating the code model, and must be
11081 // smaller than 2^21 because this is the largest offset expressible in all
11082 // object formats.
11083 //
11084 // This check also prevents us from folding negative offsets, which will end
11085 // up being treated in the same way as large positive ones. They could also
11086 // cause code model violations, and aren't really common enough to matter.
11087 if (Offset >= (1 << 21))
11088 return SDValue();
11089
11090 const GlobalValue *GV = GN->getGlobal();
11091 Type *T = GV->getValueType();
11092 if (!T->isSized() ||
11093 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11094 return SDValue();
11095
11096 SDLoc DL(GN);
11097 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11098 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11099 DAG.getConstant(MinOffset, DL, MVT::i64));
11100}
11101
Tim Northover3b0846e2014-05-24 12:50:23 +000011102SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11103 DAGCombinerInfo &DCI) const {
11104 SelectionDAG &DAG = DCI.DAG;
11105 switch (N->getOpcode()) {
11106 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011107 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011108 break;
11109 case ISD::ADD:
11110 case ISD::SUB:
11111 return performAddSubLongCombine(N, DCI, DAG);
11112 case ISD::XOR:
11113 return performXorCombine(N, DAG, DCI, Subtarget);
11114 case ISD::MUL:
11115 return performMulCombine(N, DAG, DCI, Subtarget);
11116 case ISD::SINT_TO_FP:
11117 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011118 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011119 case ISD::FP_TO_SINT:
11120 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011121 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011122 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011123 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011124 case ISD::OR:
11125 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011126 case ISD::SRL:
11127 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011128 case ISD::INTRINSIC_WO_CHAIN:
11129 return performIntrinsicCombine(N, DCI, Subtarget);
11130 case ISD::ANY_EXTEND:
11131 case ISD::ZERO_EXTEND:
11132 case ISD::SIGN_EXTEND:
11133 return performExtendCombine(N, DCI, DAG);
11134 case ISD::BITCAST:
11135 return performBitcastCombine(N, DCI, DAG);
11136 case ISD::CONCAT_VECTORS:
11137 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011138 case ISD::SELECT:
11139 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011140 case ISD::VSELECT:
11141 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011142 case ISD::LOAD:
11143 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11144 return SDValue(N, 0);
11145 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011146 case ISD::STORE:
11147 return performSTORECombine(N, DCI, DAG, Subtarget);
11148 case AArch64ISD::BRCOND:
11149 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011150 case AArch64ISD::TBNZ:
11151 case AArch64ISD::TBZ:
11152 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011153 case AArch64ISD::CSEL:
11154 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011155 case AArch64ISD::DUP:
11156 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011157 case AArch64ISD::NVCAST:
11158 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011159 case ISD::INSERT_VECTOR_ELT:
11160 return performPostLD1Combine(N, DCI, true);
11161 case ISD::INTRINSIC_VOID:
11162 case ISD::INTRINSIC_W_CHAIN:
11163 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11164 case Intrinsic::aarch64_neon_ld2:
11165 case Intrinsic::aarch64_neon_ld3:
11166 case Intrinsic::aarch64_neon_ld4:
11167 case Intrinsic::aarch64_neon_ld1x2:
11168 case Intrinsic::aarch64_neon_ld1x3:
11169 case Intrinsic::aarch64_neon_ld1x4:
11170 case Intrinsic::aarch64_neon_ld2lane:
11171 case Intrinsic::aarch64_neon_ld3lane:
11172 case Intrinsic::aarch64_neon_ld4lane:
11173 case Intrinsic::aarch64_neon_ld2r:
11174 case Intrinsic::aarch64_neon_ld3r:
11175 case Intrinsic::aarch64_neon_ld4r:
11176 case Intrinsic::aarch64_neon_st2:
11177 case Intrinsic::aarch64_neon_st3:
11178 case Intrinsic::aarch64_neon_st4:
11179 case Intrinsic::aarch64_neon_st1x2:
11180 case Intrinsic::aarch64_neon_st1x3:
11181 case Intrinsic::aarch64_neon_st1x4:
11182 case Intrinsic::aarch64_neon_st2lane:
11183 case Intrinsic::aarch64_neon_st3lane:
11184 case Intrinsic::aarch64_neon_st4lane:
11185 return performNEONPostLDSTCombine(N, DCI, DAG);
11186 default:
11187 break;
11188 }
Reid Klecknereb568942018-11-01 18:02:27 +000011189 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011190 case ISD::GlobalAddress:
11191 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011192 }
11193 return SDValue();
11194}
11195
11196// Check if the return value is used as only a return value, as otherwise
11197// we can't perform a tail-call. In particular, we need to check for
11198// target ISD nodes that are returns and any other "odd" constructs
11199// that the generic analysis code won't necessarily catch.
11200bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11201 SDValue &Chain) const {
11202 if (N->getNumValues() != 1)
11203 return false;
11204 if (!N->hasNUsesOfValue(1, 0))
11205 return false;
11206
11207 SDValue TCChain = Chain;
11208 SDNode *Copy = *N->use_begin();
11209 if (Copy->getOpcode() == ISD::CopyToReg) {
11210 // If the copy has a glue operand, we conservatively assume it isn't safe to
11211 // perform a tail call.
11212 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11213 MVT::Glue)
11214 return false;
11215 TCChain = Copy->getOperand(0);
11216 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11217 return false;
11218
11219 bool HasRet = false;
11220 for (SDNode *Node : Copy->uses()) {
11221 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11222 return false;
11223 HasRet = true;
11224 }
11225
11226 if (!HasRet)
11227 return false;
11228
11229 Chain = TCChain;
11230 return true;
11231}
11232
11233// Return whether the an instruction can potentially be optimized to a tail
11234// call. This will cause the optimizers to attempt to move, or duplicate,
11235// return instructions to help enable tail call optimizations for this
11236// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011237bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011238 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011239}
11240
11241bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11242 SDValue &Offset,
11243 ISD::MemIndexedMode &AM,
11244 bool &IsInc,
11245 SelectionDAG &DAG) const {
11246 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11247 return false;
11248
11249 Base = Op->getOperand(0);
11250 // All of the indexed addressing mode instructions take a signed
11251 // 9 bit immediate offset.
11252 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011253 int64_t RHSC = RHS->getSExtValue();
11254 if (Op->getOpcode() == ISD::SUB)
11255 RHSC = -(uint64_t)RHSC;
11256 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011257 return false;
11258 IsInc = (Op->getOpcode() == ISD::ADD);
11259 Offset = Op->getOperand(1);
11260 return true;
11261 }
11262 return false;
11263}
11264
11265bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11266 SDValue &Offset,
11267 ISD::MemIndexedMode &AM,
11268 SelectionDAG &DAG) const {
11269 EVT VT;
11270 SDValue Ptr;
11271 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11272 VT = LD->getMemoryVT();
11273 Ptr = LD->getBasePtr();
11274 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11275 VT = ST->getMemoryVT();
11276 Ptr = ST->getBasePtr();
11277 } else
11278 return false;
11279
11280 bool IsInc;
11281 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11282 return false;
11283 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11284 return true;
11285}
11286
11287bool AArch64TargetLowering::getPostIndexedAddressParts(
11288 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11289 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11290 EVT VT;
11291 SDValue Ptr;
11292 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11293 VT = LD->getMemoryVT();
11294 Ptr = LD->getBasePtr();
11295 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11296 VT = ST->getMemoryVT();
11297 Ptr = ST->getBasePtr();
11298 } else
11299 return false;
11300
11301 bool IsInc;
11302 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11303 return false;
11304 // Post-indexing updates the base, so it's not a valid transform
11305 // if that's not the same as the load's pointer.
11306 if (Ptr != Base)
11307 return false;
11308 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11309 return true;
11310}
11311
Tim Northoverf8bfe212014-07-18 13:07:05 +000011312static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11313 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011314 SDLoc DL(N);
11315 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011316
11317 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11318 return;
11319
Tim Northoverf8bfe212014-07-18 13:07:05 +000011320 Op = SDValue(
11321 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11322 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011323 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011324 0);
11325 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11326 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11327}
11328
Charlie Turner434d4592015-10-16 15:38:25 +000011329static void ReplaceReductionResults(SDNode *N,
11330 SmallVectorImpl<SDValue> &Results,
11331 SelectionDAG &DAG, unsigned InterOp,
11332 unsigned AcrossOp) {
11333 EVT LoVT, HiVT;
11334 SDValue Lo, Hi;
11335 SDLoc dl(N);
11336 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11337 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11338 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11339 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11340 Results.push_back(SplitVal);
11341}
11342
Tim Northover2f32e7f2016-08-04 19:32:28 +000011343static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11344 SDLoc DL(N);
11345 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11346 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11347 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11348 DAG.getConstant(64, DL, MVT::i64)));
11349 return std::make_pair(Lo, Hi);
11350}
11351
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011352// Create an even/odd pair of X registers holding integer value V.
11353static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11354 SDLoc dl(V.getNode());
11355 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11356 SDValue VHi = DAG.getAnyExtOrTrunc(
11357 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11358 dl, MVT::i64);
11359 if (DAG.getDataLayout().isBigEndian())
11360 std::swap (VLo, VHi);
11361 SDValue RegClass =
11362 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11363 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11364 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11365 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11366 return SDValue(
11367 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11368}
11369
Tim Northovercdf15292016-04-14 17:03:29 +000011370static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011371 SmallVectorImpl<SDValue> &Results,
11372 SelectionDAG &DAG,
11373 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011374 assert(N->getValueType(0) == MVT::i128 &&
11375 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011376
11377 if (Subtarget->hasLSE()) {
11378 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11379 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11380 SDValue Ops[] = {
11381 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11382 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11383 N->getOperand(1), // Ptr
11384 N->getOperand(0), // Chain in
11385 };
11386
Chandler Carruth66654b72018-08-14 23:30:32 +000011387 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011388
11389 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011390 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011391 case AtomicOrdering::Monotonic:
11392 Opcode = AArch64::CASPX;
11393 break;
11394 case AtomicOrdering::Acquire:
11395 Opcode = AArch64::CASPAX;
11396 break;
11397 case AtomicOrdering::Release:
11398 Opcode = AArch64::CASPLX;
11399 break;
11400 case AtomicOrdering::AcquireRelease:
11401 case AtomicOrdering::SequentiallyConsistent:
11402 Opcode = AArch64::CASPALX;
11403 break;
11404 default:
11405 llvm_unreachable("Unexpected ordering!");
11406 }
11407
11408 MachineSDNode *CmpSwap = DAG.getMachineNode(
11409 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011410 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011411
11412 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11413 if (DAG.getDataLayout().isBigEndian())
11414 std::swap(SubReg1, SubReg2);
11415 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11416 SDValue(CmpSwap, 0)));
11417 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11418 SDValue(CmpSwap, 0)));
11419 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11420 return;
11421 }
11422
Tim Northover2f32e7f2016-08-04 19:32:28 +000011423 auto Desired = splitInt128(N->getOperand(2), DAG);
11424 auto New = splitInt128(N->getOperand(3), DAG);
11425 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11426 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011427 SDNode *CmpSwap = DAG.getMachineNode(
11428 AArch64::CMP_SWAP_128, SDLoc(N),
11429 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11430
Chandler Carruth66654b72018-08-14 23:30:32 +000011431 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11432 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011433
11434 Results.push_back(SDValue(CmpSwap, 0));
11435 Results.push_back(SDValue(CmpSwap, 1));
11436 Results.push_back(SDValue(CmpSwap, 3));
11437}
11438
Tim Northover3b0846e2014-05-24 12:50:23 +000011439void AArch64TargetLowering::ReplaceNodeResults(
11440 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11441 switch (N->getOpcode()) {
11442 default:
11443 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011444 case ISD::BITCAST:
11445 ReplaceBITCASTResults(N, Results, DAG);
11446 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011447 case ISD::VECREDUCE_ADD:
11448 case ISD::VECREDUCE_SMAX:
11449 case ISD::VECREDUCE_SMIN:
11450 case ISD::VECREDUCE_UMAX:
11451 case ISD::VECREDUCE_UMIN:
11452 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11453 return;
11454
Charlie Turner434d4592015-10-16 15:38:25 +000011455 case AArch64ISD::SADDV:
11456 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11457 return;
11458 case AArch64ISD::UADDV:
11459 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11460 return;
11461 case AArch64ISD::SMINV:
11462 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11463 return;
11464 case AArch64ISD::UMINV:
11465 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11466 return;
11467 case AArch64ISD::SMAXV:
11468 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11469 return;
11470 case AArch64ISD::UMAXV:
11471 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11472 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011473 case ISD::FP_TO_UINT:
11474 case ISD::FP_TO_SINT:
11475 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11476 // Let normal code take care of it by not adding anything to Results.
11477 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011478 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011479 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011480 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011481 }
11482}
11483
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011484bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011485 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11486 return TargetLowering::useLoadStackGuardNode();
11487 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011488}
11489
Sanjay Patel1dd15592015-07-28 23:05:48 +000011490unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011491 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11492 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011493 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011494}
11495
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011496TargetLoweringBase::LegalizeTypeAction
11497AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
11498 MVT SVT = VT.getSimpleVT();
11499 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11500 // v4i16, v2i32 instead of to promote.
11501 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
11502 || SVT == MVT::v1f32)
11503 return TypeWidenVector;
11504
11505 return TargetLoweringBase::getPreferredVectorAction(VT);
11506}
11507
Robin Morisseted3d48f2014-09-03 21:29:59 +000011508// Loads and stores less than 128-bits are already atomic; ones above that
11509// are doomed anyway, so defer to the default libcall and blame the OS when
11510// things go wrong.
11511bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11512 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11513 return Size == 128;
11514}
11515
11516// Loads and stores less than 128-bits are already atomic; ones above that
11517// are doomed anyway, so defer to the default libcall and blame the OS when
11518// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011519TargetLowering::AtomicExpansionKind
11520AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011521 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011522 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011523}
11524
11525// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011526TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011527AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011528 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011529 if (Size > 128) return AtomicExpansionKind::None;
11530 // Nand not supported in LSE.
11531 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011532 // Leave 128 bits to LLSC.
11533 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011534}
11535
Alex Bradbury79518b02018-09-19 14:51:42 +000011536TargetLowering::AtomicExpansionKind
11537AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011538 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011539 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011540 if (Subtarget->hasLSE())
11541 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011542 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11543 // implement cmpxchg without spilling. If the address being exchanged is also
11544 // on the stack and close enough to the spill slot, this can lead to a
11545 // situation where the monitor always gets cleared and the atomic operation
11546 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011547 if (getTargetMachine().getOptLevel() == 0)
11548 return AtomicExpansionKind::None;
11549 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011550}
11551
Tim Northover3b0846e2014-05-24 12:50:23 +000011552Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11553 AtomicOrdering Ord) const {
11554 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11555 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011556 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011557
11558 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11559 // intrinsic must return {i64, i64} and we have to recombine them into a
11560 // single i128 here.
11561 if (ValTy->getPrimitiveSizeInBits() == 128) {
11562 Intrinsic::ID Int =
11563 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011564 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011565
11566 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11567 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11568
11569 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11570 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11571 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11572 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11573 return Builder.CreateOr(
11574 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11575 }
11576
11577 Type *Tys[] = { Addr->getType() };
11578 Intrinsic::ID Int =
11579 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011580 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011581
11582 return Builder.CreateTruncOrBitCast(
11583 Builder.CreateCall(Ldxr, Addr),
11584 cast<PointerType>(Addr->getType())->getElementType());
11585}
11586
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011587void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11588 IRBuilder<> &Builder) const {
11589 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011590 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011591}
11592
Tim Northover3b0846e2014-05-24 12:50:23 +000011593Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11594 Value *Val, Value *Addr,
11595 AtomicOrdering Ord) const {
11596 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011597 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011598
11599 // Since the intrinsics must have legal type, the i128 intrinsics take two
11600 // parameters: "i64, i64". We must marshal Val into the appropriate form
11601 // before the call.
11602 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11603 Intrinsic::ID Int =
11604 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11605 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11606 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11607
11608 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11609 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11610 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011611 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011612 }
11613
11614 Intrinsic::ID Int =
11615 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11616 Type *Tys[] = { Addr->getType() };
11617 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11618
David Blaikieff6409d2015-05-18 22:13:54 +000011619 return Builder.CreateCall(Stxr,
11620 {Builder.CreateZExtOrBitCast(
11621 Val, Stxr->getFunctionType()->getParamType(0)),
11622 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011623}
Tim Northover3c55cca2014-11-27 21:02:42 +000011624
11625bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11626 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11627 return Ty->isArrayTy();
11628}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011629
11630bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11631 EVT) const {
11632 return false;
11633}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011634
Petr Hoseka7d59162017-02-24 03:10:10 +000011635static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011636 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11637 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011638 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011639 return IRB.CreatePointerCast(
Petr Hoseka7d59162017-02-24 03:10:10 +000011640 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011641 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
11642}
11643
Petr Hoseka7d59162017-02-24 03:10:10 +000011644Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11645 // Android provides a fixed TLS slot for the stack cookie. See the definition
11646 // of TLS_SLOT_STACK_GUARD in
11647 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11648 if (Subtarget->isTargetAndroid())
11649 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011650
Petr Hoseka7d59162017-02-24 03:10:10 +000011651 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011652 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011653 if (Subtarget->isTargetFuchsia())
11654 return UseTlsOffset(IRB, -0x10);
11655
11656 return TargetLowering::getIRStackGuard(IRB);
11657}
11658
11659Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011660 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11661 // definition of TLS_SLOT_SAFESTACK in
11662 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011663 if (Subtarget->isTargetAndroid())
11664 return UseTlsOffset(IRB, 0x48);
11665
11666 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011667 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011668 if (Subtarget->isTargetFuchsia())
11669 return UseTlsOffset(IRB, -0x8);
11670
11671 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011672}
Manman Rencbe4f942015-12-16 21:04:19 +000011673
Geoff Berry5d534b62017-02-21 18:53:14 +000011674bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11675 const Instruction &AndI) const {
11676 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11677 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11678 // may be beneficial to sink in other cases, but we would have to check that
11679 // the cmp would not get folded into the br to form a cbz for these to be
11680 // beneficial.
11681 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11682 if (!Mask)
11683 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011684 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011685}
11686
Manman Rencbe4f942015-12-16 21:04:19 +000011687void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11688 // Update IsSplitCSR in AArch64unctionInfo.
11689 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11690 AFI->setIsSplitCSR(true);
11691}
11692
11693void AArch64TargetLowering::insertCopiesSplitCSR(
11694 MachineBasicBlock *Entry,
11695 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11696 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11697 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11698 if (!IStart)
11699 return;
11700
11701 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11702 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011703 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011704 for (const MCPhysReg *I = IStart; *I; ++I) {
11705 const TargetRegisterClass *RC = nullptr;
11706 if (AArch64::GPR64RegClass.contains(*I))
11707 RC = &AArch64::GPR64RegClass;
11708 else if (AArch64::FPR64RegClass.contains(*I))
11709 RC = &AArch64::FPR64RegClass;
11710 else
11711 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11712
11713 unsigned NewVR = MRI->createVirtualRegister(RC);
11714 // Create copy from CSR to a virtual register.
11715 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11716 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11717 // nounwind. If we want to generalize this later, we may need to emit
11718 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011719 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011720 Attribute::NoUnwind) &&
11721 "Function should be nounwind in insertCopiesSplitCSR!");
11722 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011723 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011724 .addReg(*I);
11725
Manman Ren4632e8e2016-01-15 20:13:28 +000011726 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011727 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011728 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11729 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011730 .addReg(NewVR);
11731 }
11732}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011733
Reid Klecknerb5180542017-03-21 16:57:19 +000011734bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011735 // Integer division on AArch64 is expensive. However, when aggressively
11736 // optimizing for code size, we prefer to use a div instruction, as it is
11737 // usually smaller than the alternative sequence.
11738 // The exception to this is vector division. Since AArch64 doesn't have vector
11739 // integer division, leaving the division as-is is a loss even in terms of
11740 // size, because it will have to be scalarized, while the alternative code
11741 // sequence can be performed in vector form.
11742 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011743 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011744 return OptSize && !VT.isVector();
11745}
Tim Northoverf19d4672017-02-08 17:57:20 +000011746
Joel Jones07150922018-01-25 21:55:39 +000011747bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11748 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11749}
11750
Tim Northoverf19d4672017-02-08 17:57:20 +000011751unsigned
11752AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011753 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011754 return getPointerTy(DL).getSizeInBits();
11755
11756 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11757}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011758
11759void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11760 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11761 TargetLoweringBase::finalizeLowering(MF);
11762}