blob: e394a4d90e05814d0112999b5b09f3e4a7d5ce60 [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);
190 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
191 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);
388 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
389 setOperationAction(ISD::FMAXNAN, 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);
James Molloy88edc822015-08-17 07:13:20 +0000453 setOperationAction(ISD::FMINNAN, Ty, Legal);
454 setOperationAction(ISD::FMAXNAN, 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);
466 setOperationAction(ISD::FMINNAN, MVT::f16, Legal);
467 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal);
468 }
469
Tim Northover3b0846e2014-05-24 12:50:23 +0000470 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
471
Tim Northovercdf15292016-04-14 17:03:29 +0000472 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000473 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
474 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000475 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000477
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000478 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
479 // This requires the Performance Monitors extension.
480 if (Subtarget->hasPerfMon())
481 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
482
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000483 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
484 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
485 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000486 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
487 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
488 } else {
489 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
490 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
491 }
492
Juergen Ributzka23266502014-12-10 19:43:32 +0000493 // Make floating-point constants legal for the large code model, so they don't
494 // become loads from the constant pool.
495 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
496 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
497 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
498 }
499
Tim Northover3b0846e2014-05-24 12:50:23 +0000500 // AArch64 does not have floating-point extending loads, i1 sign-extending
501 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000502 for (MVT VT : MVT::fp_valuetypes()) {
503 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
504 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
505 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
506 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
507 }
508 for (MVT VT : MVT::integer_valuetypes())
509 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
510
Tim Northover3b0846e2014-05-24 12:50:23 +0000511 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
512 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
513 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
514 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
515 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
516 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
517 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000518
519 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
520 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
521
Tim Northover3b0846e2014-05-24 12:50:23 +0000522 // Indexed loads and stores are supported.
523 for (unsigned im = (unsigned)ISD::PRE_INC;
524 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
525 setIndexedLoadAction(im, MVT::i8, Legal);
526 setIndexedLoadAction(im, MVT::i16, Legal);
527 setIndexedLoadAction(im, MVT::i32, Legal);
528 setIndexedLoadAction(im, MVT::i64, Legal);
529 setIndexedLoadAction(im, MVT::f64, Legal);
530 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000531 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000532 setIndexedStoreAction(im, MVT::i8, Legal);
533 setIndexedStoreAction(im, MVT::i16, Legal);
534 setIndexedStoreAction(im, MVT::i32, Legal);
535 setIndexedStoreAction(im, MVT::i64, Legal);
536 setIndexedStoreAction(im, MVT::f64, Legal);
537 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000538 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000539 }
540
541 // Trap.
542 setOperationAction(ISD::TRAP, MVT::Other, Legal);
543
544 // We combine OR nodes for bitfield operations.
545 setTargetDAGCombine(ISD::OR);
546
547 // Vector add and sub nodes may conceal a high-half opportunity.
548 // Also, try to fold ADD into CSINC/CSINV..
549 setTargetDAGCombine(ISD::ADD);
550 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000551 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000552 setTargetDAGCombine(ISD::XOR);
553 setTargetDAGCombine(ISD::SINT_TO_FP);
554 setTargetDAGCombine(ISD::UINT_TO_FP);
555
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000556 setTargetDAGCombine(ISD::FP_TO_SINT);
557 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000558 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000559
Tim Northover3b0846e2014-05-24 12:50:23 +0000560 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
561
562 setTargetDAGCombine(ISD::ANY_EXTEND);
563 setTargetDAGCombine(ISD::ZERO_EXTEND);
564 setTargetDAGCombine(ISD::SIGN_EXTEND);
565 setTargetDAGCombine(ISD::BITCAST);
566 setTargetDAGCombine(ISD::CONCAT_VECTORS);
567 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000568 if (Subtarget->supportsAddressTopByteIgnored())
569 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000570
571 setTargetDAGCombine(ISD::MUL);
572
573 setTargetDAGCombine(ISD::SELECT);
574 setTargetDAGCombine(ISD::VSELECT);
575
576 setTargetDAGCombine(ISD::INTRINSIC_VOID);
577 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
578 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
579
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000580 setTargetDAGCombine(ISD::GlobalAddress);
581
Tim Northover3b0846e2014-05-24 12:50:23 +0000582 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
583 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
584 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
585
586 setStackPointerRegisterToSaveRestore(AArch64::SP);
587
588 setSchedulingPreference(Sched::Hybrid);
589
Quentin Colombet6843ac42015-03-31 20:52:32 +0000590 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000591
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000592 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000593 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000594 // Set preferred alignments.
595 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
596 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000597
Evandro Menezese45de8a2016-09-26 15:32:33 +0000598 // Only change the limit for entries in a jump table if specified by
599 // the subtarget, but not at the command line.
600 unsigned MaxJT = STI.getMaximumJumpTableSize();
601 if (MaxJT && getMaximumJumpTableSize() == 0)
602 setMaximumJumpTableSize(MaxJT);
603
Tim Northover3b0846e2014-05-24 12:50:23 +0000604 setHasExtractBitsInsn(true);
605
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000606 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
607
Tim Northover3b0846e2014-05-24 12:50:23 +0000608 if (Subtarget->hasNEON()) {
609 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
610 // silliness like this:
611 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
612 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
613 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
614 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
615 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
616 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
617 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
618 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
619 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
620 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
621 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
622 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
623 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
624 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
625 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
626 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
627 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
628 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
629 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
630 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
631 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
632 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
633 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
634 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
635 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
636
637 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
638 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
639 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
640 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
641 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
642
643 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
644
645 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
646 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000647 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
648 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
649 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
650 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000651 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
652 // -> v8f16 conversions.
Craig Toppera4f99972018-01-01 19:21:35 +0000653 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
654 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
655 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
656 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
658 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
659 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
660 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
661 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000662 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
663 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
664 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
665 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000666
Craig Topperc5551bf2016-04-26 05:26:51 +0000667 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
668 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
669
Craig Topper3b4842b2016-04-28 01:58:21 +0000670 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
671 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
672 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
673 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
674 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
675 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
676 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
677 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
678
Tim Northover3b0846e2014-05-24 12:50:23 +0000679 // AArch64 doesn't have MUL.2d:
680 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000681 // Custom handling for some quad-vector types to detect MULL.
682 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
683 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
684 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
685
Amara Emersonc9916d72017-05-16 21:29:22 +0000686 // Vector reductions
687 for (MVT VT : MVT::integer_valuetypes()) {
688 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
689 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
690 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
691 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
692 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
693 }
694 for (MVT VT : MVT::fp_valuetypes()) {
695 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
696 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
697 }
698
Tim Northover3b0846e2014-05-24 12:50:23 +0000699 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
700 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
701 // Likewise, narrowing and extending vector loads/stores aren't handled
702 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000703 for (MVT VT : MVT::vector_valuetypes()) {
704 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000705
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000706 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
707 setOperationAction(ISD::MULHS, VT, Custom);
708 setOperationAction(ISD::MULHU, VT, Custom);
709 } else {
710 setOperationAction(ISD::MULHS, VT, Expand);
711 setOperationAction(ISD::MULHU, VT, Expand);
712 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000713 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000714 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000715
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000716 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000717
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000718 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000719 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000720 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
721 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
722 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
723 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000724 }
725
726 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000727 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000728 setOperationAction(ISD::FFLOOR, Ty, Legal);
729 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
730 setOperationAction(ISD::FCEIL, Ty, Legal);
731 setOperationAction(ISD::FRINT, Ty, Legal);
732 setOperationAction(ISD::FTRUNC, Ty, Legal);
733 setOperationAction(ISD::FROUND, Ty, Legal);
734 }
735 }
James Molloyf089ab72014-08-06 10:42:18 +0000736
Matthias Braun651cff42016-06-02 18:03:53 +0000737 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000738}
739
Craig Topper18e69f42016-04-15 06:20:21 +0000740void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000741 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000742
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000743 if (VT.isFloatingPoint()) {
744 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
745 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
746 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000747 }
748
749 // Mark vector float intrinsics as expand.
750 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000751 setOperationAction(ISD::FSIN, VT, Expand);
752 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000753 setOperationAction(ISD::FPOW, VT, Expand);
754 setOperationAction(ISD::FLOG, VT, Expand);
755 setOperationAction(ISD::FLOG2, VT, Expand);
756 setOperationAction(ISD::FLOG10, VT, Expand);
757 setOperationAction(ISD::FEXP, VT, Expand);
758 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000759
760 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000761 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000762 }
763
Craig Topper18e69f42016-04-15 06:20:21 +0000764 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
765 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
766 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
767 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
768 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
769 setOperationAction(ISD::SRA, VT, Custom);
770 setOperationAction(ISD::SRL, VT, Custom);
771 setOperationAction(ISD::SHL, VT, Custom);
772 setOperationAction(ISD::AND, VT, Custom);
773 setOperationAction(ISD::OR, VT, Custom);
774 setOperationAction(ISD::SETCC, VT, Custom);
775 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000776
Craig Topper18e69f42016-04-15 06:20:21 +0000777 setOperationAction(ISD::SELECT, VT, Expand);
778 setOperationAction(ISD::SELECT_CC, VT, Expand);
779 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000780 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000781 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000782
783 // CNT supports only B element sizes.
784 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000785 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000786
Craig Topper18e69f42016-04-15 06:20:21 +0000787 setOperationAction(ISD::UDIV, VT, Expand);
788 setOperationAction(ISD::SDIV, VT, Expand);
789 setOperationAction(ISD::UREM, VT, Expand);
790 setOperationAction(ISD::SREM, VT, Expand);
791 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000792
Craig Topper18e69f42016-04-15 06:20:21 +0000793 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
794 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000795
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000796 if (!VT.isFloatingPoint())
797 setOperationAction(ISD::ABS, VT, Legal);
798
Hal Finkelcd8664c2015-12-11 23:11:52 +0000799 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000800 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000801 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000802 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000803
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000804 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
805 if (VT.isFloatingPoint() &&
806 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
James Molloyb7b2a1e2015-08-11 12:06:37 +0000807 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
808 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000809 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000810
Tim Northover3b0846e2014-05-24 12:50:23 +0000811 if (Subtarget->isLittleEndian()) {
812 for (unsigned im = (unsigned)ISD::PRE_INC;
813 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000814 setIndexedLoadAction(im, VT, Legal);
815 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000816 }
817 }
818}
819
820void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
821 addRegisterClass(VT, &AArch64::FPR64RegClass);
822 addTypeForNEON(VT, MVT::v2i32);
823}
824
825void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
826 addRegisterClass(VT, &AArch64::FPR128RegClass);
827 addTypeForNEON(VT, MVT::v4i32);
828}
829
Mehdi Amini44ede332015-07-09 02:09:04 +0000830EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
831 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000832 if (!VT.isVector())
833 return MVT::i32;
834 return VT.changeVectorElementTypeToInteger();
835}
836
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000837static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
838 const APInt &Demanded,
839 TargetLowering::TargetLoweringOpt &TLO,
840 unsigned NewOpc) {
841 uint64_t OldImm = Imm, NewImm, Enc;
842 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
843
844 // Return if the immediate is already all zeros, all ones, a bimm32 or a
845 // bimm64.
846 if (Imm == 0 || Imm == Mask ||
847 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
848 return false;
849
850 unsigned EltSize = Size;
851 uint64_t DemandedBits = Demanded.getZExtValue();
852
853 // Clear bits that are not demanded.
854 Imm &= DemandedBits;
855
856 while (true) {
857 // The goal here is to set the non-demanded bits in a way that minimizes
858 // the number of switching between 0 and 1. In order to achieve this goal,
859 // we set the non-demanded bits to the value of the preceding demanded bits.
860 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
861 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
862 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
863 // The final result is 0b11000011.
864 uint64_t NonDemandedBits = ~DemandedBits;
865 uint64_t InvertedImm = ~Imm & DemandedBits;
866 uint64_t RotatedImm =
867 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
868 NonDemandedBits;
869 uint64_t Sum = RotatedImm + NonDemandedBits;
870 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
871 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
872 NewImm = (Imm | Ones) & Mask;
873
874 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
875 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
876 // we halve the element size and continue the search.
877 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
878 break;
879
880 // We cannot shrink the element size any further if it is 2-bits.
881 if (EltSize == 2)
882 return false;
883
884 EltSize /= 2;
885 Mask >>= EltSize;
886 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
887
888 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
889 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
890 return false;
891
892 // Merge the upper and lower halves of Imm and DemandedBits.
893 Imm |= Hi;
894 DemandedBits |= DemandedBitsHi;
895 }
896
897 ++NumOptimizedImms;
898
899 // Replicate the element across the register width.
900 while (EltSize < Size) {
901 NewImm |= NewImm << EltSize;
902 EltSize *= 2;
903 }
904
905 (void)OldImm;
906 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
907 "demanded bits should never be altered");
908 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
909
910 // Create the new constant immediate node.
911 EVT VT = Op.getValueType();
912 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000913 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000914
915 // If the new constant immediate is all-zeros or all-ones, let the target
916 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000917 if (NewImm == 0 || NewImm == OrigMask) {
918 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
919 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000920 // Otherwise, create a machine node so that target independent DAG combine
921 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000922 } else {
923 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
924 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
925 New = SDValue(
926 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
927 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000928
929 return TLO.CombineTo(Op, New);
930}
931
932bool AArch64TargetLowering::targetShrinkDemandedConstant(
933 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
934 // Delay this optimization to as late as possible.
935 if (!TLO.LegalOps)
936 return false;
937
938 if (!EnableOptimizeLogicalImm)
939 return false;
940
941 EVT VT = Op.getValueType();
942 if (VT.isVector())
943 return false;
944
945 unsigned Size = VT.getSizeInBits();
946 assert((Size == 32 || Size == 64) &&
947 "i32 or i64 is expected after legalization.");
948
949 // Exit early if we demand all bits.
950 if (Demanded.countPopulation() == Size)
951 return false;
952
953 unsigned NewOpc;
954 switch (Op.getOpcode()) {
955 default:
956 return false;
957 case ISD::AND:
958 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
959 break;
960 case ISD::OR:
961 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
962 break;
963 case ISD::XOR:
964 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
965 break;
966 }
967 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
968 if (!C)
969 return false;
970 uint64_t Imm = C->getZExtValue();
971 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
972}
973
Tim Northover3b0846e2014-05-24 12:50:23 +0000974/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000975/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000976void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000977 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000978 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000979 switch (Op.getOpcode()) {
980 default:
981 break;
982 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000983 KnownBits Known2;
984 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
985 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
986 Known.Zero &= Known2.Zero;
987 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +0000988 break;
989 }
990 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000991 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000992 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
993 switch (IntID) {
994 default: return;
995 case Intrinsic::aarch64_ldaxr:
996 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000997 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +0000998 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +0000999 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001000 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001001 return;
1002 }
1003 }
1004 break;
1005 }
1006 case ISD::INTRINSIC_WO_CHAIN:
1007 case ISD::INTRINSIC_VOID: {
1008 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1009 switch (IntNo) {
1010 default:
1011 break;
1012 case Intrinsic::aarch64_neon_umaxv:
1013 case Intrinsic::aarch64_neon_uminv: {
1014 // Figure out the datatype of the vector operand. The UMINV instruction
1015 // will zero extend the result, so we can mark as known zero all the
1016 // bits larger than the element datatype. 32-bit or larget doesn't need
1017 // this as those are legal types and will be handled by isel directly.
1018 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001019 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001020 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1021 assert(BitWidth >= 8 && "Unexpected width!");
1022 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001023 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001024 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1025 assert(BitWidth >= 16 && "Unexpected width!");
1026 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001027 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001028 }
1029 break;
1030 } break;
1031 }
1032 }
1033 }
1034}
1035
Mehdi Aminieaabc512015-07-09 15:12:23 +00001036MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1037 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001038 return MVT::i64;
1039}
1040
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001041bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1042 unsigned AddrSpace,
1043 unsigned Align,
1044 bool *Fast) const {
1045 if (Subtarget->requiresStrictAlign())
1046 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001047
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001048 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001049 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1050 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001051 // See comments in performSTORECombine() for more details about
1052 // these conditions.
1053
1054 // Code that uses clang vector extensions can mark that it
1055 // wants unaligned accesses to be treated as fast by
1056 // underspecifying alignment to be 1 or 2.
1057 Align <= 2 ||
1058
1059 // Disregard v2i64. Memcpy lowering produces those and splitting
1060 // them regresses performance on micro-benchmarks and olden/bh.
1061 VT == MVT::v2i64;
1062 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001063 return true;
1064}
1065
Tim Northover3b0846e2014-05-24 12:50:23 +00001066FastISel *
1067AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1068 const TargetLibraryInfo *libInfo) const {
1069 return AArch64::createFastISel(funcInfo, libInfo);
1070}
1071
1072const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001073 switch ((AArch64ISD::NodeType)Opcode) {
1074 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001075 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1076 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1077 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1078 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1079 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1080 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1081 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1082 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1083 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1084 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1085 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1086 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001087 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001088 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1089 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1090 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1091 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1092 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1093 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1094 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001095 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1096 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1097 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001098 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001099 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1100 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1101 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1102 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1103 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1104 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1105 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1106 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1107 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1108 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1109 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1110 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1111 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1112 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1113 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1114 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1115 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1116 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1117 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1118 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1119 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1120 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1121 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1122 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1123 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1124 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1125 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1126 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1127 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1128 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1129 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1130 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1131 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1132 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1133 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1134 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1135 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1136 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1137 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1138 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1139 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1140 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1141 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1142 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1143 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1144 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1145 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1146 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001147 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1148 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1149 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1150 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1151 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1152 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001153 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1154 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1155 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1156 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1157 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1158 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1159 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001160 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001161 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1162 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001163 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001164 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1165 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1166 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1167 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1168 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1169 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1170 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1171 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1172 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1173 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1174 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1175 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1176 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1177 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1178 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1179 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1180 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1181 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1182 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1183 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1184 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1185 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1186 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1187 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1188 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1189 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1190 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1191 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1192 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001193 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1194 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001195 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001196 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1197 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1198 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001199 }
Matthias Braund04893f2015-05-07 21:33:59 +00001200 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001201}
1202
1203MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001204AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001205 MachineBasicBlock *MBB) const {
1206 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1207 // phi node:
1208
1209 // OrigBB:
1210 // [... previous instrs leading to comparison ...]
1211 // b.ne TrueBB
1212 // b EndBB
1213 // TrueBB:
1214 // ; Fallthrough
1215 // EndBB:
1216 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1217
Tim Northover3b0846e2014-05-24 12:50:23 +00001218 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001219 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001220 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001221 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001222 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001223
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001224 unsigned DestReg = MI.getOperand(0).getReg();
1225 unsigned IfTrueReg = MI.getOperand(1).getReg();
1226 unsigned IfFalseReg = MI.getOperand(2).getReg();
1227 unsigned CondCode = MI.getOperand(3).getImm();
1228 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001229
1230 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1231 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1232 MF->insert(It, TrueBB);
1233 MF->insert(It, EndBB);
1234
1235 // Transfer rest of current basic-block to EndBB
1236 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1237 MBB->end());
1238 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1239
1240 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1241 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1242 MBB->addSuccessor(TrueBB);
1243 MBB->addSuccessor(EndBB);
1244
1245 // TrueBB falls through to the end.
1246 TrueBB->addSuccessor(EndBB);
1247
1248 if (!NZCVKilled) {
1249 TrueBB->addLiveIn(AArch64::NZCV);
1250 EndBB->addLiveIn(AArch64::NZCV);
1251 }
1252
1253 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1254 .addReg(IfTrueReg)
1255 .addMBB(TrueBB)
1256 .addReg(IfFalseReg)
1257 .addMBB(MBB);
1258
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001259 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001260 return EndBB;
1261}
1262
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001263MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1264 MachineInstr &MI, MachineBasicBlock *BB) const {
1265 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001266 default:
1267#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001268 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001269#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001270 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001271
1272 case AArch64::F128CSEL:
1273 return EmitF128CSEL(MI, BB);
1274
1275 case TargetOpcode::STACKMAP:
1276 case TargetOpcode::PATCHPOINT:
1277 return emitPatchPoint(MI, BB);
1278 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001279}
1280
1281//===----------------------------------------------------------------------===//
1282// AArch64 Lowering private implementation.
1283//===----------------------------------------------------------------------===//
1284
1285//===----------------------------------------------------------------------===//
1286// Lowering Code
1287//===----------------------------------------------------------------------===//
1288
1289/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1290/// CC
1291static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1292 switch (CC) {
1293 default:
1294 llvm_unreachable("Unknown condition code!");
1295 case ISD::SETNE:
1296 return AArch64CC::NE;
1297 case ISD::SETEQ:
1298 return AArch64CC::EQ;
1299 case ISD::SETGT:
1300 return AArch64CC::GT;
1301 case ISD::SETGE:
1302 return AArch64CC::GE;
1303 case ISD::SETLT:
1304 return AArch64CC::LT;
1305 case ISD::SETLE:
1306 return AArch64CC::LE;
1307 case ISD::SETUGT:
1308 return AArch64CC::HI;
1309 case ISD::SETUGE:
1310 return AArch64CC::HS;
1311 case ISD::SETULT:
1312 return AArch64CC::LO;
1313 case ISD::SETULE:
1314 return AArch64CC::LS;
1315 }
1316}
1317
1318/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1319static void changeFPCCToAArch64CC(ISD::CondCode CC,
1320 AArch64CC::CondCode &CondCode,
1321 AArch64CC::CondCode &CondCode2) {
1322 CondCode2 = AArch64CC::AL;
1323 switch (CC) {
1324 default:
1325 llvm_unreachable("Unknown FP condition!");
1326 case ISD::SETEQ:
1327 case ISD::SETOEQ:
1328 CondCode = AArch64CC::EQ;
1329 break;
1330 case ISD::SETGT:
1331 case ISD::SETOGT:
1332 CondCode = AArch64CC::GT;
1333 break;
1334 case ISD::SETGE:
1335 case ISD::SETOGE:
1336 CondCode = AArch64CC::GE;
1337 break;
1338 case ISD::SETOLT:
1339 CondCode = AArch64CC::MI;
1340 break;
1341 case ISD::SETOLE:
1342 CondCode = AArch64CC::LS;
1343 break;
1344 case ISD::SETONE:
1345 CondCode = AArch64CC::MI;
1346 CondCode2 = AArch64CC::GT;
1347 break;
1348 case ISD::SETO:
1349 CondCode = AArch64CC::VC;
1350 break;
1351 case ISD::SETUO:
1352 CondCode = AArch64CC::VS;
1353 break;
1354 case ISD::SETUEQ:
1355 CondCode = AArch64CC::EQ;
1356 CondCode2 = AArch64CC::VS;
1357 break;
1358 case ISD::SETUGT:
1359 CondCode = AArch64CC::HI;
1360 break;
1361 case ISD::SETUGE:
1362 CondCode = AArch64CC::PL;
1363 break;
1364 case ISD::SETLT:
1365 case ISD::SETULT:
1366 CondCode = AArch64CC::LT;
1367 break;
1368 case ISD::SETLE:
1369 case ISD::SETULE:
1370 CondCode = AArch64CC::LE;
1371 break;
1372 case ISD::SETNE:
1373 case ISD::SETUNE:
1374 CondCode = AArch64CC::NE;
1375 break;
1376 }
1377}
1378
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001379/// Convert a DAG fp condition code to an AArch64 CC.
1380/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1381/// should be AND'ed instead of OR'ed.
1382static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1383 AArch64CC::CondCode &CondCode,
1384 AArch64CC::CondCode &CondCode2) {
1385 CondCode2 = AArch64CC::AL;
1386 switch (CC) {
1387 default:
1388 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1389 assert(CondCode2 == AArch64CC::AL);
1390 break;
1391 case ISD::SETONE:
1392 // (a one b)
1393 // == ((a olt b) || (a ogt b))
1394 // == ((a ord b) && (a une b))
1395 CondCode = AArch64CC::VC;
1396 CondCode2 = AArch64CC::NE;
1397 break;
1398 case ISD::SETUEQ:
1399 // (a ueq b)
1400 // == ((a uno b) || (a oeq b))
1401 // == ((a ule b) && (a uge b))
1402 CondCode = AArch64CC::PL;
1403 CondCode2 = AArch64CC::LE;
1404 break;
1405 }
1406}
1407
Tim Northover3b0846e2014-05-24 12:50:23 +00001408/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1409/// CC usable with the vector instructions. Fewer operations are available
1410/// without a real NZCV register, so we have to use less efficient combinations
1411/// to get the same effect.
1412static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1413 AArch64CC::CondCode &CondCode,
1414 AArch64CC::CondCode &CondCode2,
1415 bool &Invert) {
1416 Invert = false;
1417 switch (CC) {
1418 default:
1419 // Mostly the scalar mappings work fine.
1420 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1421 break;
1422 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001423 Invert = true;
1424 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001425 case ISD::SETO:
1426 CondCode = AArch64CC::MI;
1427 CondCode2 = AArch64CC::GE;
1428 break;
1429 case ISD::SETUEQ:
1430 case ISD::SETULT:
1431 case ISD::SETULE:
1432 case ISD::SETUGT:
1433 case ISD::SETUGE:
1434 // All of the compare-mask comparisons are ordered, but we can switch
1435 // between the two by a double inversion. E.g. ULE == !OGT.
1436 Invert = true;
1437 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1438 break;
1439 }
1440}
1441
1442static bool isLegalArithImmed(uint64_t C) {
1443 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001444 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1445 DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1446 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001447}
1448
1449static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001450 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001451 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001452 const bool FullFP16 =
1453 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001454
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001455 if (VT.isFloatingPoint()) {
1456 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001457 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001458 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1459 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001460 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001461 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001462 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001463 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001464
1465 // The CMP instruction is just an alias for SUBS, and representing it as
1466 // SUBS means that it's possible to get CSE with subtract operations.
1467 // A later phase can perform the optimization of setting the destination
1468 // register to WZR/XZR if it ends up being unused.
1469 unsigned Opcode = AArch64ISD::SUBS;
1470
Artyom Skrobov314ee042015-11-25 19:41:11 +00001471 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001472 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1473 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1474 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1475 // can be set differently by this operation. It comes down to whether
1476 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1477 // everything is fine. If not then the optimization is wrong. Thus general
1478 // comparisons are only valid if op2 != 0.
1479
1480 // So, finally, the only LLVM-native comparisons that don't mention C and V
1481 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1482 // the absence of information about op2.
1483 Opcode = AArch64ISD::ADDS;
1484 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001485 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001486 !isUnsignedIntSetCC(CC)) {
1487 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1488 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1489 // of the signed comparisons.
1490 Opcode = AArch64ISD::ANDS;
1491 RHS = LHS.getOperand(1);
1492 LHS = LHS.getOperand(0);
1493 }
1494
Matthias Braunaf7d7702015-07-16 20:02:37 +00001495 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001496 .getValue(1);
1497}
1498
Matthias Braunaf7d7702015-07-16 20:02:37 +00001499/// \defgroup AArch64CCMP CMP;CCMP matching
1500///
1501/// These functions deal with the formation of CMP;CCMP;... sequences.
1502/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1503/// a comparison. They set the NZCV flags to a predefined value if their
1504/// predicate is false. This allows to express arbitrary conjunctions, for
1505/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1506/// expressed as:
1507/// cmp A
1508/// ccmp B, inv(CB), CA
1509/// check for CB flags
1510///
1511/// In general we can create code for arbitrary "... (and (and A B) C)"
1512/// sequences. We can also implement some "or" expressions, because "(or A B)"
1513/// is equivalent to "not (and (not A) (not B))" and we can implement some
1514/// negation operations:
1515/// We can negate the results of a single comparison by inverting the flags
1516/// used when the predicate fails and inverting the flags tested in the next
1517/// instruction; We can also negate the results of the whole previous
1518/// conditional compare sequence by inverting the flags tested in the next
1519/// instruction. However there is no way to negate the result of a partial
1520/// sequence.
1521///
1522/// Therefore on encountering an "or" expression we can negate the subtree on
1523/// one side and have to be able to push the negate to the leafs of the subtree
1524/// on the other side (see also the comments in code). As complete example:
1525/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1526/// (and (setCC (cmp C)) (setCD (cmp D)))"
1527/// is transformed to
1528/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1529/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1530/// and implemented as:
1531/// cmp C
1532/// ccmp D, inv(CD), CC
1533/// ccmp A, CA, inv(CD)
1534/// ccmp B, CB, inv(CA)
1535/// check for CB flags
1536/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1537/// by conditional compare sequences.
1538/// @{
1539
Geoff Berrye41c2df2015-07-20 22:03:52 +00001540/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001541static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1542 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001543 AArch64CC::CondCode Predicate,
1544 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001545 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001546 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001547 const bool FullFP16 =
1548 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1549
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001550 if (LHS.getValueType().isFloatingPoint()) {
1551 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001552 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001553 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1554 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1555 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001556 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001557 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001558 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001559 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001560 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1561 Opcode = AArch64ISD::CCMN;
1562 RHS = RHS.getOperand(1);
1563 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001564 }
1565 if (Opcode == 0)
1566 Opcode = AArch64ISD::CCMP;
1567
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001568 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1569 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1570 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001571 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1572 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1573}
1574
1575/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1576/// CanPushNegate is set to true if we can push a negate operation through
1577/// the tree in a was that we are left with AND operations and negate operations
1578/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1579/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1580/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001581static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001582 unsigned Depth = 0) {
1583 if (!Val.hasOneUse())
1584 return false;
1585 unsigned Opcode = Val->getOpcode();
1586 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001587 if (Val->getOperand(0).getValueType() == MVT::f128)
1588 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001589 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001590 return true;
1591 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001592 // Protect against exponential runtime and stack overflow.
1593 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001594 return false;
1595 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1596 SDValue O0 = Val->getOperand(0);
1597 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001598 bool CanNegateL;
1599 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001600 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001601 bool CanNegateR;
1602 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001603 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001604
1605 if (Opcode == ISD::OR) {
1606 // For an OR expression we need to be able to negate at least one side or
1607 // we cannot do the transformation at all.
1608 if (!CanNegateL && !CanNegateR)
1609 return false;
1610 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1611 // can negate the x and y subtrees.
1612 CanNegate = CanNegateL && CanNegateR;
1613 } else {
1614 // If the operands are OR expressions then we finally need to negate their
1615 // outputs, we can only do that for the operand with emitted last by
1616 // negating OutCC, not for both operands.
1617 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1618 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1619 if (NeedsNegOutL && NeedsNegOutR)
1620 return false;
1621 // We cannot negate an AND operation (it would become an OR),
1622 CanNegate = false;
1623 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001624 return true;
1625 }
1626 return false;
1627}
1628
1629/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1630/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1631/// Tries to transform the given i1 producing node @p Val to a series compare
1632/// and conditional compare operations. @returns an NZCV flags producing node
1633/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1634/// transformation was not possible.
1635/// On recursive invocations @p PushNegate may be set to true to have negation
1636/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1637/// for the comparisons in the current subtree; @p Depth limits the search
1638/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001639static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1640 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001641 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001642 // We're at a tree leaf, produce a conditional comparison operation.
1643 unsigned Opcode = Val->getOpcode();
1644 if (Opcode == ISD::SETCC) {
1645 SDValue LHS = Val->getOperand(0);
1646 SDValue RHS = Val->getOperand(1);
1647 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1648 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001649 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001650 CC = getSetCCInverse(CC, isInteger);
1651 SDLoc DL(Val);
1652 // Determine OutCC and handle FP special case.
1653 if (isInteger) {
1654 OutCC = changeIntCCToAArch64CC(CC);
1655 } else {
1656 assert(LHS.getValueType().isFloatingPoint());
1657 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001658 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1659 // Some floating point conditions can't be tested with a single condition
1660 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001661 if (ExtraCC != AArch64CC::AL) {
1662 SDValue ExtraCmp;
1663 if (!CCOp.getNode())
1664 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001665 else
1666 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001667 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001668 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001669 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001670 }
1671 }
1672
1673 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001674 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001675 return emitComparison(LHS, RHS, CC, DL, DAG);
1676 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001677 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001678 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001679 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001680 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1681 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001682
1683 // Check if both sides can be transformed.
1684 SDValue LHS = Val->getOperand(0);
1685 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001686
Matthias Braunfdef49b2016-01-23 04:05:22 +00001687 // In case of an OR we need to negate our operands and the result.
1688 // (A v B) <=> not(not(A) ^ not(B))
1689 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001690 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001691 // predicate flags giving us a free negation for one side. The other side
1692 // must be negatable by itself.
1693 if (NegateOpsAndResult) {
1694 // See which side we can negate.
1695 bool CanNegateL;
1696 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1697 assert(isValidL && "Valid conjunction/disjunction tree");
1698 (void)isValidL;
1699
1700#ifndef NDEBUG
1701 bool CanNegateR;
1702 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1703 assert(isValidR && "Valid conjunction/disjunction tree");
1704 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1705#endif
1706
1707 // Order the side which we cannot negate to RHS so we can emit it first.
1708 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001709 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001710 } else {
1711 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001712 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001713 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001714 // Order the side where we need to negate the output flags to RHS so it
1715 // gets emitted first.
1716 if (NeedsNegOutL)
1717 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001718 }
1719
1720 // Emit RHS. If we want to negate the tree we only need to push a negate
1721 // through if we are already in a PushNegate case, otherwise we can negate
1722 // the "flags to test" afterwards.
1723 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001724 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001725 CCOp, Predicate);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001726 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001727 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001728 // Emit LHS. We may need to negate it.
1729 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1730 NegateOpsAndResult, CmpR,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001731 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001732 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001733 // (or absorb the Negate parameter).
1734 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001735 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1736 return CmpL;
1737}
1738
Matthias Braunfdef49b2016-01-23 04:05:22 +00001739/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1740/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1741/// \see emitConjunctionDisjunctionTreeRec().
1742static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001743 AArch64CC::CondCode &OutCC) {
Matthias Braunfdef49b2016-01-23 04:05:22 +00001744 bool CanNegate;
1745 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1746 return SDValue();
1747
1748 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001749 AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001750}
1751
Matthias Braunaf7d7702015-07-16 20:02:37 +00001752/// @}
1753
Tim Northover3b0846e2014-05-24 12:50:23 +00001754static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001755 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001756 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001757 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1758 EVT VT = RHS.getValueType();
1759 uint64_t C = RHSC->getZExtValue();
1760 if (!isLegalArithImmed(C)) {
1761 // Constant does not fit, try adjusting it by one?
1762 switch (CC) {
1763 default:
1764 break;
1765 case ISD::SETLT:
1766 case ISD::SETGE:
1767 if ((VT == MVT::i32 && C != 0x80000000 &&
1768 isLegalArithImmed((uint32_t)(C - 1))) ||
1769 (VT == MVT::i64 && C != 0x80000000ULL &&
1770 isLegalArithImmed(C - 1ULL))) {
1771 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1772 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001773 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001774 }
1775 break;
1776 case ISD::SETULT:
1777 case ISD::SETUGE:
1778 if ((VT == MVT::i32 && C != 0 &&
1779 isLegalArithImmed((uint32_t)(C - 1))) ||
1780 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1781 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1782 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001783 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001784 }
1785 break;
1786 case ISD::SETLE:
1787 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001788 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001789 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001790 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001791 isLegalArithImmed(C + 1ULL))) {
1792 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1793 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001794 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001795 }
1796 break;
1797 case ISD::SETULE:
1798 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001799 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001800 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001801 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001802 isLegalArithImmed(C + 1ULL))) {
1803 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1804 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001805 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001806 }
1807 break;
1808 }
1809 }
1810 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001811 SDValue Cmp;
1812 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001813 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001814 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1815
1816 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1817 // For the i8 operand, the largest immediate is 255, so this can be easily
1818 // encoded in the compare instruction. For the i16 operand, however, the
1819 // largest immediate cannot be encoded in the compare.
1820 // Therefore, use a sign extending load and cmn to avoid materializing the
1821 // -1 constant. For example,
1822 // movz w1, #65535
1823 // ldrh w0, [x0, #0]
1824 // cmp w0, w1
1825 // >
1826 // ldrsh w0, [x0, #0]
1827 // cmn w0, #1
1828 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1829 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001830 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001831 // transformation is profitable.
1832 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1833 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1834 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1835 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1836 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1837 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1838 SDValue SExt =
1839 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1840 DAG.getValueType(MVT::i16));
1841 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1842 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001843 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001844 AArch64CC = changeIntCCToAArch64CC(CC);
1845 }
1846 }
1847
1848 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001849 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001850 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1851 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001852 }
1853 }
1854 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001855
1856 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001857 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001858 AArch64CC = changeIntCCToAArch64CC(CC);
1859 }
1860 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001861 return Cmp;
1862}
1863
1864static std::pair<SDValue, SDValue>
1865getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1866 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1867 "Unsupported value type");
1868 SDValue Value, Overflow;
1869 SDLoc DL(Op);
1870 SDValue LHS = Op.getOperand(0);
1871 SDValue RHS = Op.getOperand(1);
1872 unsigned Opc = 0;
1873 switch (Op.getOpcode()) {
1874 default:
1875 llvm_unreachable("Unknown overflow instruction!");
1876 case ISD::SADDO:
1877 Opc = AArch64ISD::ADDS;
1878 CC = AArch64CC::VS;
1879 break;
1880 case ISD::UADDO:
1881 Opc = AArch64ISD::ADDS;
1882 CC = AArch64CC::HS;
1883 break;
1884 case ISD::SSUBO:
1885 Opc = AArch64ISD::SUBS;
1886 CC = AArch64CC::VS;
1887 break;
1888 case ISD::USUBO:
1889 Opc = AArch64ISD::SUBS;
1890 CC = AArch64CC::LO;
1891 break;
1892 // Multiply needs a little bit extra work.
1893 case ISD::SMULO:
1894 case ISD::UMULO: {
1895 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001896 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001897 if (Op.getValueType() == MVT::i32) {
1898 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1899 // For a 32 bit multiply with overflow check we want the instruction
1900 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1901 // need to generate the following pattern:
1902 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1903 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1904 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1905 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1906 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001907 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001908 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1909 // operation. We need to clear out the upper 32 bits, because we used a
1910 // widening multiply that wrote all 64 bits. In the end this should be a
1911 // noop.
1912 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1913 if (IsSigned) {
1914 // The signed overflow check requires more than just a simple check for
1915 // any bit set in the upper 32 bits of the result. These bits could be
1916 // just the sign bits of a negative number. To perform the overflow
1917 // check we have to arithmetic shift right the 32nd bit of the result by
1918 // 31 bits. Then we compare the result to the upper 32 bits.
1919 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001920 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001921 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1922 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001923 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001924 // It is important that LowerBits is last, otherwise the arithmetic
1925 // shift will not be folded into the compare (SUBS).
1926 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1927 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1928 .getValue(1);
1929 } else {
1930 // The overflow check for unsigned multiply is easy. We only need to
1931 // check if any of the upper 32 bits are set. This can be done with a
1932 // CMP (shifted register). For that we need to generate the following
1933 // pattern:
1934 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1935 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001936 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001937 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1938 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001939 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1940 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001941 UpperBits).getValue(1);
1942 }
1943 break;
1944 }
1945 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1946 // For the 64 bit multiply
1947 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1948 if (IsSigned) {
1949 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1950 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001951 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001952 // It is important that LowerBits is last, otherwise the arithmetic
1953 // shift will not be folded into the compare (SUBS).
1954 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1955 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1956 .getValue(1);
1957 } else {
1958 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1959 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1960 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001961 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1962 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001963 UpperBits).getValue(1);
1964 }
1965 break;
1966 }
1967 } // switch (...)
1968
1969 if (Opc) {
1970 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1971
1972 // Emit the AArch64 operation with overflow check.
1973 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1974 Overflow = Value.getValue(1);
1975 }
1976 return std::make_pair(Value, Overflow);
1977}
1978
1979SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1980 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001981 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001982 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001983}
1984
Amara Emerson24ca39c2017-10-09 15:15:09 +00001985// Returns true if the given Op is the overflow flag result of an overflow
1986// intrinsic operation.
1987static bool isOverflowIntrOpRes(SDValue Op) {
1988 unsigned Opc = Op.getOpcode();
1989 return (Op.getResNo() == 1 &&
1990 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
1991 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
1992}
1993
Tim Northover3b0846e2014-05-24 12:50:23 +00001994static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1995 SDValue Sel = Op.getOperand(0);
1996 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00001997 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00001998
Amara Emerson24ca39c2017-10-09 15:15:09 +00001999 // If the operand is an overflow checking operation, invert the condition
2000 // code and kill the Not operation. I.e., transform:
2001 // (xor (overflow_op_bool, 1))
2002 // -->
2003 // (csel 1, 0, invert(cc), overflow_op_bool)
2004 // ... which later gets transformed to just a cset instruction with an
2005 // inverted condition code, rather than a cset + eor sequence.
2006 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2007 // Only lower legal XALUO ops.
2008 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2009 return SDValue();
2010
2011 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2012 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2013 AArch64CC::CondCode CC;
2014 SDValue Value, Overflow;
2015 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2016 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2017 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2018 CCVal, Overflow);
2019 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002020 // If neither operand is a SELECT_CC, give up.
2021 if (Sel.getOpcode() != ISD::SELECT_CC)
2022 std::swap(Sel, Other);
2023 if (Sel.getOpcode() != ISD::SELECT_CC)
2024 return Op;
2025
2026 // The folding we want to perform is:
2027 // (xor x, (select_cc a, b, cc, 0, -1) )
2028 // -->
2029 // (csel x, (xor x, -1), cc ...)
2030 //
2031 // The latter will get matched to a CSINV instruction.
2032
2033 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2034 SDValue LHS = Sel.getOperand(0);
2035 SDValue RHS = Sel.getOperand(1);
2036 SDValue TVal = Sel.getOperand(2);
2037 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002038
2039 // FIXME: This could be generalized to non-integer comparisons.
2040 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2041 return Op;
2042
2043 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2044 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2045
Eric Christopher572e03a2015-06-19 01:53:21 +00002046 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002047 if (!CFVal || !CTVal)
2048 return Op;
2049
2050 // We can commute the SELECT_CC by inverting the condition. This
2051 // might be needed to make this fit into a CSINV pattern.
2052 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2053 std::swap(TVal, FVal);
2054 std::swap(CTVal, CFVal);
2055 CC = ISD::getSetCCInverse(CC, true);
2056 }
2057
2058 // If the constants line up, perform the transform!
2059 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2060 SDValue CCVal;
2061 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2062
2063 FVal = Other;
2064 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002065 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002066
2067 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2068 CCVal, Cmp);
2069 }
2070
2071 return Op;
2072}
2073
2074static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2075 EVT VT = Op.getValueType();
2076
2077 // Let legalize expand this if it isn't a legal type yet.
2078 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2079 return SDValue();
2080
2081 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2082
2083 unsigned Opc;
2084 bool ExtraOp = false;
2085 switch (Op.getOpcode()) {
2086 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002087 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002088 case ISD::ADDC:
2089 Opc = AArch64ISD::ADDS;
2090 break;
2091 case ISD::SUBC:
2092 Opc = AArch64ISD::SUBS;
2093 break;
2094 case ISD::ADDE:
2095 Opc = AArch64ISD::ADCS;
2096 ExtraOp = true;
2097 break;
2098 case ISD::SUBE:
2099 Opc = AArch64ISD::SBCS;
2100 ExtraOp = true;
2101 break;
2102 }
2103
2104 if (!ExtraOp)
2105 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2106 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2107 Op.getOperand(2));
2108}
2109
2110static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2111 // Let legalize expand this if it isn't a legal type yet.
2112 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2113 return SDValue();
2114
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002115 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002116 AArch64CC::CondCode CC;
2117 // The actual operation that sets the overflow or carry flag.
2118 SDValue Value, Overflow;
2119 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2120
2121 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002122 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2123 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002124
2125 // We use an inverted condition, because the conditional select is inverted
2126 // too. This will allow it to be selected to a single instruction:
2127 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002128 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2129 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002130 CCVal, Overflow);
2131
2132 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002133 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002134}
2135
2136// Prefetch operands are:
2137// 1: Address to prefetch
2138// 2: bool isWrite
2139// 3: int locality (0 = no locality ... 3 = extreme locality)
2140// 4: bool isDataCache
2141static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2142 SDLoc DL(Op);
2143 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2144 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002145 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002146
2147 bool IsStream = !Locality;
2148 // When the locality number is set
2149 if (Locality) {
2150 // The front-end should have filtered out the out-of-range values
2151 assert(Locality <= 3 && "Prefetch locality out-of-range");
2152 // The locality degree is the opposite of the cache speed.
2153 // Put the number the other way around.
2154 // The encoding starts at 0 for level 1
2155 Locality = 3 - Locality;
2156 }
2157
2158 // built the mask value encoding the expected behavior.
2159 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002160 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002161 (Locality << 1) | // Cache level bits
2162 (unsigned)IsStream; // Stream bit
2163 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002164 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002165}
2166
2167SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2168 SelectionDAG &DAG) const {
2169 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2170
2171 RTLIB::Libcall LC;
2172 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2173
2174 return LowerF128Call(Op, DAG, LC);
2175}
2176
2177SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2178 SelectionDAG &DAG) const {
2179 if (Op.getOperand(0).getValueType() != MVT::f128) {
2180 // It's legal except when f128 is involved
2181 return Op;
2182 }
2183
2184 RTLIB::Libcall LC;
2185 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2186
2187 // FP_ROUND node has a second operand indicating whether it is known to be
2188 // precise. That doesn't take part in the LibCall so we can't directly use
2189 // LowerF128Call.
2190 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002191 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2192 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002193}
2194
2195static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2196 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2197 // Any additional optimization in this function should be recorded
2198 // in the cost tables.
2199 EVT InVT = Op.getOperand(0).getValueType();
2200 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002201 unsigned NumElts = InVT.getVectorNumElements();
2202
2203 // f16 vectors are promoted to f32 before a conversion.
2204 if (InVT.getVectorElementType() == MVT::f16) {
2205 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2206 SDLoc dl(Op);
2207 return DAG.getNode(
2208 Op.getOpcode(), dl, Op.getValueType(),
2209 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2210 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002211
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002212 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002213 SDLoc dl(Op);
2214 SDValue Cv =
2215 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2216 Op.getOperand(0));
2217 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002218 }
2219
2220 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002221 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002222 MVT ExtVT =
2223 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2224 VT.getVectorNumElements());
2225 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002226 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2227 }
2228
2229 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002230 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002231}
2232
2233SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2234 SelectionDAG &DAG) const {
2235 if (Op.getOperand(0).getValueType().isVector())
2236 return LowerVectorFP_TO_INT(Op, DAG);
2237
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002238 // f16 conversions are promoted to f32 when full fp16 is not supported.
2239 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2240 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002241 SDLoc dl(Op);
2242 return DAG.getNode(
2243 Op.getOpcode(), dl, Op.getValueType(),
2244 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2245 }
2246
Tim Northover3b0846e2014-05-24 12:50:23 +00002247 if (Op.getOperand(0).getValueType() != MVT::f128) {
2248 // It's legal except when f128 is involved
2249 return Op;
2250 }
2251
2252 RTLIB::Libcall LC;
2253 if (Op.getOpcode() == ISD::FP_TO_SINT)
2254 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2255 else
2256 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2257
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002258 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002259 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002260}
2261
2262static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2263 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2264 // Any additional optimization in this function should be recorded
2265 // in the cost tables.
2266 EVT VT = Op.getValueType();
2267 SDLoc dl(Op);
2268 SDValue In = Op.getOperand(0);
2269 EVT InVT = In.getValueType();
2270
Tim Northoveref0d7602014-06-15 09:27:06 +00002271 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2272 MVT CastVT =
2273 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2274 InVT.getVectorNumElements());
2275 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002276 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002277 }
2278
Tim Northoveref0d7602014-06-15 09:27:06 +00002279 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2280 unsigned CastOpc =
2281 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2282 EVT CastVT = VT.changeVectorElementTypeToInteger();
2283 In = DAG.getNode(CastOpc, dl, CastVT, In);
2284 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002285 }
2286
Tim Northoveref0d7602014-06-15 09:27:06 +00002287 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002288}
2289
2290SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2291 SelectionDAG &DAG) const {
2292 if (Op.getValueType().isVector())
2293 return LowerVectorINT_TO_FP(Op, DAG);
2294
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002295 // f16 conversions are promoted to f32 when full fp16 is not supported.
2296 if (Op.getValueType() == MVT::f16 &&
2297 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002298 SDLoc dl(Op);
2299 return DAG.getNode(
2300 ISD::FP_ROUND, dl, MVT::f16,
2301 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002302 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002303 }
2304
Tim Northover3b0846e2014-05-24 12:50:23 +00002305 // i128 conversions are libcalls.
2306 if (Op.getOperand(0).getValueType() == MVT::i128)
2307 return SDValue();
2308
2309 // Other conversions are legal, unless it's to the completely software-based
2310 // fp128.
2311 if (Op.getValueType() != MVT::f128)
2312 return Op;
2313
2314 RTLIB::Libcall LC;
2315 if (Op.getOpcode() == ISD::SINT_TO_FP)
2316 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2317 else
2318 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2319
2320 return LowerF128Call(Op, DAG, LC);
2321}
2322
2323SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2324 SelectionDAG &DAG) const {
2325 // For iOS, we want to call an alternative entry point: __sincos_stret,
2326 // which returns the values in two S / D registers.
2327 SDLoc dl(Op);
2328 SDValue Arg = Op.getOperand(0);
2329 EVT ArgVT = Arg.getValueType();
2330 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2331
2332 ArgListTy Args;
2333 ArgListEntry Entry;
2334
2335 Entry.Node = Arg;
2336 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002337 Entry.IsSExt = false;
2338 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002339 Args.push_back(Entry);
2340
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002341 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2342 : RTLIB::SINCOS_STRET_F32;
2343 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002344 SDValue Callee =
2345 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002346
Serge Gueltone38003f2017-05-09 19:31:13 +00002347 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002348 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002349 CLI.setDebugLoc(dl)
2350 .setChain(DAG.getEntryNode())
2351 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002352
2353 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2354 return CallResult.first;
2355}
2356
Tim Northoverf8bfe212014-07-18 13:07:05 +00002357static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2358 if (Op.getValueType() != MVT::f16)
2359 return SDValue();
2360
2361 assert(Op.getOperand(0).getValueType() == MVT::i16);
2362 SDLoc DL(Op);
2363
2364 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2365 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2366 return SDValue(
2367 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002368 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002369 0);
2370}
2371
Chad Rosierd9d0f862014-10-08 02:31:24 +00002372static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2373 if (OrigVT.getSizeInBits() >= 64)
2374 return OrigVT;
2375
2376 assert(OrigVT.isSimple() && "Expecting a simple value type");
2377
2378 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2379 switch (OrigSimpleTy) {
2380 default: llvm_unreachable("Unexpected Vector Type");
2381 case MVT::v2i8:
2382 case MVT::v2i16:
2383 return MVT::v2i32;
2384 case MVT::v4i8:
2385 return MVT::v4i16;
2386 }
2387}
2388
2389static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2390 const EVT &OrigTy,
2391 const EVT &ExtTy,
2392 unsigned ExtOpcode) {
2393 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2394 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2395 // 64-bits we need to insert a new extension so that it will be 64-bits.
2396 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2397 if (OrigTy.getSizeInBits() >= 64)
2398 return N;
2399
2400 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2401 EVT NewVT = getExtensionTo64Bits(OrigTy);
2402
2403 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2404}
2405
2406static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2407 bool isSigned) {
2408 EVT VT = N->getValueType(0);
2409
2410 if (N->getOpcode() != ISD::BUILD_VECTOR)
2411 return false;
2412
Pete Cooper3af9a252015-06-26 18:17:36 +00002413 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002415 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002416 unsigned HalfSize = EltSize / 2;
2417 if (isSigned) {
2418 if (!isIntN(HalfSize, C->getSExtValue()))
2419 return false;
2420 } else {
2421 if (!isUIntN(HalfSize, C->getZExtValue()))
2422 return false;
2423 }
2424 continue;
2425 }
2426 return false;
2427 }
2428
2429 return true;
2430}
2431
2432static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2433 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2434 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2435 N->getOperand(0)->getValueType(0),
2436 N->getValueType(0),
2437 N->getOpcode());
2438
2439 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2440 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002441 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002442 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002443 unsigned NumElts = VT.getVectorNumElements();
2444 MVT TruncVT = MVT::getIntegerVT(EltSize);
2445 SmallVector<SDValue, 8> Ops;
2446 for (unsigned i = 0; i != NumElts; ++i) {
2447 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2448 const APInt &CInt = C->getAPIntValue();
2449 // Element types smaller than 32 bits are not legal, so use i32 elements.
2450 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002451 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002452 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002453 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002454}
2455
2456static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002457 return N->getOpcode() == ISD::SIGN_EXTEND ||
2458 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002459}
2460
2461static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002462 return N->getOpcode() == ISD::ZERO_EXTEND ||
2463 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002464}
2465
2466static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2467 unsigned Opcode = N->getOpcode();
2468 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2469 SDNode *N0 = N->getOperand(0).getNode();
2470 SDNode *N1 = N->getOperand(1).getNode();
2471 return N0->hasOneUse() && N1->hasOneUse() &&
2472 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2473 }
2474 return false;
2475}
2476
2477static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2478 unsigned Opcode = N->getOpcode();
2479 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2480 SDNode *N0 = N->getOperand(0).getNode();
2481 SDNode *N1 = N->getOperand(1).getNode();
2482 return N0->hasOneUse() && N1->hasOneUse() &&
2483 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2484 }
2485 return false;
2486}
2487
2488static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2489 // Multiplications are only custom-lowered for 128-bit vectors so that
2490 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2491 EVT VT = Op.getValueType();
2492 assert(VT.is128BitVector() && VT.isInteger() &&
2493 "unexpected type for custom-lowering ISD::MUL");
2494 SDNode *N0 = Op.getOperand(0).getNode();
2495 SDNode *N1 = Op.getOperand(1).getNode();
2496 unsigned NewOpc = 0;
2497 bool isMLA = false;
2498 bool isN0SExt = isSignExtended(N0, DAG);
2499 bool isN1SExt = isSignExtended(N1, DAG);
2500 if (isN0SExt && isN1SExt)
2501 NewOpc = AArch64ISD::SMULL;
2502 else {
2503 bool isN0ZExt = isZeroExtended(N0, DAG);
2504 bool isN1ZExt = isZeroExtended(N1, DAG);
2505 if (isN0ZExt && isN1ZExt)
2506 NewOpc = AArch64ISD::UMULL;
2507 else if (isN1SExt || isN1ZExt) {
2508 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2509 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2510 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2511 NewOpc = AArch64ISD::SMULL;
2512 isMLA = true;
2513 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2514 NewOpc = AArch64ISD::UMULL;
2515 isMLA = true;
2516 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2517 std::swap(N0, N1);
2518 NewOpc = AArch64ISD::UMULL;
2519 isMLA = true;
2520 }
2521 }
2522
2523 if (!NewOpc) {
2524 if (VT == MVT::v2i64)
2525 // Fall through to expand this. It is not legal.
2526 return SDValue();
2527 else
2528 // Other vector multiplications are legal.
2529 return Op;
2530 }
2531 }
2532
2533 // Legalize to a S/UMULL instruction
2534 SDLoc DL(Op);
2535 SDValue Op0;
2536 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2537 if (!isMLA) {
2538 Op0 = skipExtensionForVectorMULL(N0, DAG);
2539 assert(Op0.getValueType().is64BitVector() &&
2540 Op1.getValueType().is64BitVector() &&
2541 "unexpected types for extended operands to VMULL");
2542 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2543 }
2544 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2545 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2546 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2547 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2548 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2549 EVT Op1VT = Op1.getValueType();
2550 return DAG.getNode(N0->getOpcode(), DL, VT,
2551 DAG.getNode(NewOpc, DL, VT,
2552 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2553 DAG.getNode(NewOpc, DL, VT,
2554 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2555}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002556
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +00002557// Lower vector multiply high (ISD::MULHS and ISD::MULHU).
2558static SDValue LowerMULH(SDValue Op, SelectionDAG &DAG) {
2559 // Multiplications are only custom-lowered for 128-bit vectors so that
2560 // {S,U}MULL{2} can be detected. Otherwise v2i64 multiplications are not
2561 // legal.
2562 EVT VT = Op.getValueType();
2563 assert(VT.is128BitVector() && VT.isInteger() &&
2564 "unexpected type for custom-lowering ISD::MULH{U,S}");
2565
2566 SDValue V0 = Op.getOperand(0);
2567 SDValue V1 = Op.getOperand(1);
2568
2569 SDLoc DL(Op);
2570
2571 EVT ExtractVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
2572
2573 // We turn (V0 mulhs/mulhu V1) to:
2574 //
2575 // (uzp2 (smull (extract_subvector (ExtractVT V128:V0, (i64 0)),
2576 // (extract_subvector (ExtractVT V128:V1, (i64 0))))),
2577 // (smull (extract_subvector (ExtractVT V128:V0, (i64 VMull2Idx)),
2578 // (extract_subvector (ExtractVT V128:V2, (i64 VMull2Idx))))))
2579 //
2580 // Where ExtractVT is a subvector with half number of elements, and
2581 // VMullIdx2 is the index of the middle element (the high part).
2582 //
2583 // The vector hight part extract and multiply will be matched against
2584 // {S,U}MULL{v16i8_v8i16,v8i16_v4i32,v4i32_v2i64} which in turn will
2585 // issue a {s}mull2 instruction.
2586 //
2587 // This basically multiply the lower subvector with '{s,u}mull', the high
2588 // subvector with '{s,u}mull2', and shuffle both results high part in
2589 // resulting vector.
2590 unsigned Mull2VectorIdx = VT.getVectorNumElements () / 2;
2591 SDValue VMullIdx = DAG.getConstant(0, DL, MVT::i64);
2592 SDValue VMull2Idx = DAG.getConstant(Mull2VectorIdx, DL, MVT::i64);
2593
2594 SDValue VMullV0 =
2595 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMullIdx);
2596 SDValue VMullV1 =
2597 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMullIdx);
2598
2599 SDValue VMull2V0 =
2600 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMull2Idx);
2601 SDValue VMull2V1 =
2602 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMull2Idx);
2603
2604 unsigned MullOpc = Op.getOpcode() == ISD::MULHS ? AArch64ISD::SMULL
2605 : AArch64ISD::UMULL;
2606
2607 EVT MullVT = ExtractVT.widenIntegerVectorElementType(*DAG.getContext());
2608 SDValue Mull = DAG.getNode(MullOpc, DL, MullVT, VMullV0, VMullV1);
2609 SDValue Mull2 = DAG.getNode(MullOpc, DL, MullVT, VMull2V0, VMull2V1);
2610
2611 Mull = DAG.getNode(ISD::BITCAST, DL, VT, Mull);
2612 Mull2 = DAG.getNode(ISD::BITCAST, DL, VT, Mull2);
2613
2614 return DAG.getNode(AArch64ISD::UZP2, DL, VT, Mull, Mull2);
2615}
2616
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002617SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2618 SelectionDAG &DAG) const {
2619 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2620 SDLoc dl(Op);
2621 switch (IntNo) {
2622 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002623 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002624 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2625 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2626 }
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +00002627 case Intrinsic::aarch64_neon_abs:
2628 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2629 Op.getOperand(1));
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002630 case Intrinsic::aarch64_neon_smax:
2631 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2632 Op.getOperand(1), Op.getOperand(2));
2633 case Intrinsic::aarch64_neon_umax:
2634 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2635 Op.getOperand(1), Op.getOperand(2));
2636 case Intrinsic::aarch64_neon_smin:
2637 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2638 Op.getOperand(1), Op.getOperand(2));
2639 case Intrinsic::aarch64_neon_umin:
2640 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2641 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002642 }
2643}
2644
Tim Northover3b0846e2014-05-24 12:50:23 +00002645SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2646 SelectionDAG &DAG) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002647 DEBUG(dbgs() << "Custom lowering: ");
2648 DEBUG(Op.dump());
2649
Tim Northover3b0846e2014-05-24 12:50:23 +00002650 switch (Op.getOpcode()) {
2651 default:
2652 llvm_unreachable("unimplemented operand");
2653 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002654 case ISD::BITCAST:
2655 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002656 case ISD::GlobalAddress:
2657 return LowerGlobalAddress(Op, DAG);
2658 case ISD::GlobalTLSAddress:
2659 return LowerGlobalTLSAddress(Op, DAG);
2660 case ISD::SETCC:
2661 return LowerSETCC(Op, DAG);
2662 case ISD::BR_CC:
2663 return LowerBR_CC(Op, DAG);
2664 case ISD::SELECT:
2665 return LowerSELECT(Op, DAG);
2666 case ISD::SELECT_CC:
2667 return LowerSELECT_CC(Op, DAG);
2668 case ISD::JumpTable:
2669 return LowerJumpTable(Op, DAG);
2670 case ISD::ConstantPool:
2671 return LowerConstantPool(Op, DAG);
2672 case ISD::BlockAddress:
2673 return LowerBlockAddress(Op, DAG);
2674 case ISD::VASTART:
2675 return LowerVASTART(Op, DAG);
2676 case ISD::VACOPY:
2677 return LowerVACOPY(Op, DAG);
2678 case ISD::VAARG:
2679 return LowerVAARG(Op, DAG);
2680 case ISD::ADDC:
2681 case ISD::ADDE:
2682 case ISD::SUBC:
2683 case ISD::SUBE:
2684 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2685 case ISD::SADDO:
2686 case ISD::UADDO:
2687 case ISD::SSUBO:
2688 case ISD::USUBO:
2689 case ISD::SMULO:
2690 case ISD::UMULO:
2691 return LowerXALUO(Op, DAG);
2692 case ISD::FADD:
2693 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2694 case ISD::FSUB:
2695 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2696 case ISD::FMUL:
2697 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2698 case ISD::FDIV:
2699 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2700 case ISD::FP_ROUND:
2701 return LowerFP_ROUND(Op, DAG);
2702 case ISD::FP_EXTEND:
2703 return LowerFP_EXTEND(Op, DAG);
2704 case ISD::FRAMEADDR:
2705 return LowerFRAMEADDR(Op, DAG);
2706 case ISD::RETURNADDR:
2707 return LowerRETURNADDR(Op, DAG);
2708 case ISD::INSERT_VECTOR_ELT:
2709 return LowerINSERT_VECTOR_ELT(Op, DAG);
2710 case ISD::EXTRACT_VECTOR_ELT:
2711 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2712 case ISD::BUILD_VECTOR:
2713 return LowerBUILD_VECTOR(Op, DAG);
2714 case ISD::VECTOR_SHUFFLE:
2715 return LowerVECTOR_SHUFFLE(Op, DAG);
2716 case ISD::EXTRACT_SUBVECTOR:
2717 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2718 case ISD::SRA:
2719 case ISD::SRL:
2720 case ISD::SHL:
2721 return LowerVectorSRA_SRL_SHL(Op, DAG);
2722 case ISD::SHL_PARTS:
2723 return LowerShiftLeftParts(Op, DAG);
2724 case ISD::SRL_PARTS:
2725 case ISD::SRA_PARTS:
2726 return LowerShiftRightParts(Op, DAG);
2727 case ISD::CTPOP:
2728 return LowerCTPOP(Op, DAG);
2729 case ISD::FCOPYSIGN:
2730 return LowerFCOPYSIGN(Op, DAG);
2731 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002732 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002733 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002734 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002735 case ISD::XOR:
2736 return LowerXOR(Op, DAG);
2737 case ISD::PREFETCH:
2738 return LowerPREFETCH(Op, DAG);
2739 case ISD::SINT_TO_FP:
2740 case ISD::UINT_TO_FP:
2741 return LowerINT_TO_FP(Op, DAG);
2742 case ISD::FP_TO_SINT:
2743 case ISD::FP_TO_UINT:
2744 return LowerFP_TO_INT(Op, DAG);
2745 case ISD::FSINCOS:
2746 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002747 case ISD::MUL:
2748 return LowerMUL(Op, DAG);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +00002749 case ISD::MULHS:
2750 case ISD::MULHU:
2751 return LowerMULH(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002752 case ISD::INTRINSIC_WO_CHAIN:
2753 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002754 case ISD::VECREDUCE_ADD:
2755 case ISD::VECREDUCE_SMAX:
2756 case ISD::VECREDUCE_SMIN:
2757 case ISD::VECREDUCE_UMAX:
2758 case ISD::VECREDUCE_UMIN:
2759 case ISD::VECREDUCE_FMAX:
2760 case ISD::VECREDUCE_FMIN:
2761 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002762 case ISD::ATOMIC_LOAD_SUB:
2763 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002764 case ISD::ATOMIC_LOAD_AND:
2765 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002766 case ISD::DYNAMIC_STACKALLOC:
2767 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002768 }
2769}
2770
Tim Northover3b0846e2014-05-24 12:50:23 +00002771//===----------------------------------------------------------------------===//
2772// Calling Convention Implementation
2773//===----------------------------------------------------------------------===//
2774
2775#include "AArch64GenCallingConv.inc"
2776
Robin Morisset039781e2014-08-29 21:53:01 +00002777/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002778CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2779 bool IsVarArg) const {
2780 switch (CC) {
2781 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002782 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002783 case CallingConv::WebKit_JS:
2784 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002785 case CallingConv::GHC:
2786 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002787 case CallingConv::C:
2788 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002789 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002790 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002791 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002792 if (Subtarget->isTargetWindows() && IsVarArg)
2793 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002794 if (!Subtarget->isTargetDarwin())
2795 return CC_AArch64_AAPCS;
2796 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002797 case CallingConv::Win64:
2798 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002799 }
2800}
2801
Tim Northover406024a2016-08-10 21:44:01 +00002802CCAssignFn *
2803AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2804 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2805 : RetCC_AArch64_AAPCS;
2806}
2807
Tim Northover3b0846e2014-05-24 12:50:23 +00002808SDValue AArch64TargetLowering::LowerFormalArguments(
2809 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002810 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2811 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002812 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002813 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00002814 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002815
2816 // Assign locations to all of the incoming arguments.
2817 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002818 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2819 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002820
2821 // At this point, Ins[].VT may already be promoted to i32. To correctly
2822 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2823 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2824 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2825 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2826 // LocVT.
2827 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00002828 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00002829 unsigned CurArgIdx = 0;
2830 for (unsigned i = 0; i != NumArgs; ++i) {
2831 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002832 if (Ins[i].isOrigArg()) {
2833 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2834 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002835
Andrew Trick05938a52015-02-16 18:10:47 +00002836 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002837 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2838 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002839 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2840 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2841 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2842 ValVT = MVT::i8;
2843 else if (ActualMVT == MVT::i16)
2844 ValVT = MVT::i16;
2845 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002846 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2847 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002848 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002849 assert(!Res && "Call operand has unhandled type");
2850 (void)Res;
2851 }
2852 assert(ArgLocs.size() == Ins.size());
2853 SmallVector<SDValue, 16> ArgValues;
2854 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855 CCValAssign &VA = ArgLocs[i];
2856
2857 if (Ins[i].Flags.isByVal()) {
2858 // Byval is used for HFAs in the PCS, but the system should work in a
2859 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002860 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002861 int Size = Ins[i].Flags.getByValSize();
2862 unsigned NumRegs = (Size + 7) / 8;
2863
2864 // FIXME: This works on big-endian for composite byvals, which are the common
2865 // case. It should also work for fundamental types too.
2866 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002867 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002868 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002869 InVals.push_back(FrameIdxN);
2870
2871 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002872 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002873
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002874 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002875 // Arguments stored in registers.
2876 EVT RegVT = VA.getLocVT();
2877
2878 SDValue ArgValue;
2879 const TargetRegisterClass *RC;
2880
2881 if (RegVT == MVT::i32)
2882 RC = &AArch64::GPR32RegClass;
2883 else if (RegVT == MVT::i64)
2884 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002885 else if (RegVT == MVT::f16)
2886 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002887 else if (RegVT == MVT::f32)
2888 RC = &AArch64::FPR32RegClass;
2889 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2890 RC = &AArch64::FPR64RegClass;
2891 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2892 RC = &AArch64::FPR128RegClass;
2893 else
2894 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2895
2896 // Transform the arguments in physical registers into virtual ones.
2897 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2898 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2899
2900 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2901 // to 64 bits. Insert an assert[sz]ext to capture this, then
2902 // truncate to the right size.
2903 switch (VA.getLocInfo()) {
2904 default:
2905 llvm_unreachable("Unknown loc info!");
2906 case CCValAssign::Full:
2907 break;
2908 case CCValAssign::BCvt:
2909 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2910 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002911 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002912 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002913 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002914 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2915 // nodes after our lowering.
2916 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002917 break;
2918 }
2919
2920 InVals.push_back(ArgValue);
2921
2922 } else { // VA.isRegLoc()
2923 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2924 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002925 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002926
2927 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002928 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2929 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002930 BEAlign = 8 - ArgSize;
2931
Matthias Braun941a7052016-07-28 18:40:00 +00002932 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002933
2934 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002935 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002936 SDValue ArgValue;
2937
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002938 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002939 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002940 MVT MemVT = VA.getValVT();
2941
Tim Northover47e003c2014-05-26 17:21:53 +00002942 switch (VA.getLocInfo()) {
2943 default:
2944 break;
Tim Northover6890add2014-06-03 13:54:53 +00002945 case CCValAssign::BCvt:
2946 MemVT = VA.getLocVT();
2947 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002948 case CCValAssign::SExt:
2949 ExtType = ISD::SEXTLOAD;
2950 break;
2951 case CCValAssign::ZExt:
2952 ExtType = ISD::ZEXTLOAD;
2953 break;
2954 case CCValAssign::AExt:
2955 ExtType = ISD::EXTLOAD;
2956 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002957 }
2958
Alex Lorenze40c8a22015-08-11 23:09:45 +00002959 ArgValue = DAG.getExtLoad(
2960 ExtType, DL, VA.getLocVT(), Chain, FIN,
2961 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002962 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002963
Tim Northover3b0846e2014-05-24 12:50:23 +00002964 InVals.push_back(ArgValue);
2965 }
2966 }
2967
2968 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002969 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002970 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00002971 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002972 // The AAPCS variadic function ABI is identical to the non-variadic
2973 // one. As a result there may be more arguments in registers and we should
2974 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00002975 // Win64 variadic functions also pass arguments in registers, but all float
2976 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00002977 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2978 }
2979
Tim Northover3b0846e2014-05-24 12:50:23 +00002980 // This will point to the next argument passed via stack.
2981 unsigned StackOffset = CCInfo.getNextStackOffset();
2982 // We currently pass all varargs at 8-byte alignment.
2983 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002984 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002985 }
2986
Tim Northover3b0846e2014-05-24 12:50:23 +00002987 unsigned StackArgSize = CCInfo.getNextStackOffset();
2988 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2989 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2990 // This is a non-standard ABI so by fiat I say we're allowed to make full
2991 // use of the stack area to be popped, which must be aligned to 16 bytes in
2992 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002993 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002994
2995 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2996 // a multiple of 16.
2997 FuncInfo->setArgumentStackToRestore(StackArgSize);
2998
2999 // This realignment carries over to the available bytes below. Our own
3000 // callers will guarantee the space is free by giving an aligned value to
3001 // CALLSEQ_START.
3002 }
3003 // Even if we're not expected to free up the space, it's useful to know how
3004 // much is there while considering tail calls (because we can reuse it).
3005 FuncInfo->setBytesInStackArgArea(StackArgSize);
3006
3007 return Chain;
3008}
3009
3010void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003011 SelectionDAG &DAG,
3012 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003013 SDValue &Chain) const {
3014 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003015 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003016 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003017 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003018 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003019
3020 SmallVector<SDValue, 8> MemOps;
3021
3022 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3023 AArch64::X3, AArch64::X4, AArch64::X5,
3024 AArch64::X6, AArch64::X7 };
3025 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003026 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003027
3028 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3029 int GPRIdx = 0;
3030 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003031 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003032 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003033 if (GPRSaveSize & 15)
3034 // The extra size here, if triggered, will always be 8.
3035 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3036 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003037 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003038
Mehdi Amini44ede332015-07-09 02:09:04 +00003039 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003040
3041 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3042 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3043 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003044 SDValue Store = DAG.getStore(
3045 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003046 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003047 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3048 GPRIdx,
3049 (i - FirstVariadicGPR) * 8)
3050 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003051 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003052 FIN =
3053 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003054 }
3055 }
3056 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3057 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3058
Martin Storsjo2f24e932017-07-17 20:05:19 +00003059 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003060 static const MCPhysReg FPRArgRegs[] = {
3061 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3062 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3063 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003064 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003065
3066 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3067 int FPRIdx = 0;
3068 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003069 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003070
Mehdi Amini44ede332015-07-09 02:09:04 +00003071 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003072
3073 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3074 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3075 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3076
Alex Lorenze40c8a22015-08-11 23:09:45 +00003077 SDValue Store = DAG.getStore(
3078 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003079 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003080 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003081 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3082 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003083 }
3084 }
3085 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3086 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3087 }
3088
3089 if (!MemOps.empty()) {
3090 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3091 }
3092}
3093
3094/// LowerCallResult - Lower the result values of a call into the
3095/// appropriate copies out of appropriate physical registers.
3096SDValue AArch64TargetLowering::LowerCallResult(
3097 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003098 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3099 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003100 SDValue ThisVal) const {
3101 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3102 ? RetCC_AArch64_WebKit_JS
3103 : RetCC_AArch64_AAPCS;
3104 // Assign locations to each value returned by this call.
3105 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003106 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3107 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003108 CCInfo.AnalyzeCallResult(Ins, RetCC);
3109
3110 // Copy all of the result registers out of their specified physreg.
3111 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3112 CCValAssign VA = RVLocs[i];
3113
3114 // Pass 'this' value directly from the argument to return value, to avoid
3115 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003116 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003117 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3118 "unexpected return calling convention register assignment");
3119 InVals.push_back(ThisVal);
3120 continue;
3121 }
3122
3123 SDValue Val =
3124 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3125 Chain = Val.getValue(1);
3126 InFlag = Val.getValue(2);
3127
3128 switch (VA.getLocInfo()) {
3129 default:
3130 llvm_unreachable("Unknown loc info!");
3131 case CCValAssign::Full:
3132 break;
3133 case CCValAssign::BCvt:
3134 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3135 break;
3136 }
3137
3138 InVals.push_back(Val);
3139 }
3140
3141 return Chain;
3142}
3143
Matthias Braun1af14142016-09-13 19:27:38 +00003144/// Return true if the calling convention is one that we can guarantee TCO for.
3145static bool canGuaranteeTCO(CallingConv::ID CC) {
3146 return CC == CallingConv::Fast;
3147}
3148
3149/// Return true if we might ever do TCO for calls with this calling convention.
3150static bool mayTailCallThisCC(CallingConv::ID CC) {
3151 switch (CC) {
3152 case CallingConv::C:
3153 case CallingConv::PreserveMost:
3154 case CallingConv::Swift:
3155 return true;
3156 default:
3157 return canGuaranteeTCO(CC);
3158 }
3159}
3160
Tim Northover3b0846e2014-05-24 12:50:23 +00003161bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3162 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003163 const SmallVectorImpl<ISD::OutputArg> &Outs,
3164 const SmallVectorImpl<SDValue> &OutVals,
3165 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003166 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003167 return false;
3168
Matthias Braun8d414362016-03-30 22:46:04 +00003169 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003170 const Function &CallerF = MF.getFunction();
3171 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003172 bool CCMatch = CallerCC == CalleeCC;
3173
3174 // Byval parameters hand the function a pointer directly into the stack area
3175 // we want to reuse during a tail call. Working around this *is* possible (see
3176 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003177 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3178 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003179 i != e; ++i)
3180 if (i->hasByValAttr())
3181 return false;
3182
Matthias Braun1af14142016-09-13 19:27:38 +00003183 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3184 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003185
Oliver Stannard12993dd2014-08-18 12:42:15 +00003186 // Externally-defined functions with weak linkage should not be
3187 // tail-called on AArch64 when the OS does not support dynamic
3188 // pre-emption of symbols, as the AAELF spec requires normal calls
3189 // to undefined weak functions to be replaced with a NOP or jump to the
3190 // next instruction. The behaviour of branch instructions in this
3191 // situation (as used for tail calls) is implementation-defined, so we
3192 // cannot rely on the linker replacing the tail call with a return.
3193 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3194 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003195 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003196 if (GV->hasExternalWeakLinkage() &&
3197 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003198 return false;
3199 }
3200
Tim Northover3b0846e2014-05-24 12:50:23 +00003201 // Now we search for cases where we can use a tail call without changing the
3202 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3203 // concept.
3204
3205 // I want anyone implementing a new calling convention to think long and hard
3206 // about this assert.
3207 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3208 "Unexpected variadic calling convention");
3209
Matthias Braun8d414362016-03-30 22:46:04 +00003210 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003211 if (isVarArg && !Outs.empty()) {
3212 // At least two cases here: if caller is fastcc then we can't have any
3213 // memory arguments (we'd be expected to clean up the stack afterwards). If
3214 // caller is C then we could potentially use its argument area.
3215
3216 // FIXME: for now we take the most conservative of these in both cases:
3217 // disallow all variadic memory operands.
3218 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003219 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003220
3221 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003222 for (const CCValAssign &ArgLoc : ArgLocs)
3223 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003224 return false;
3225 }
3226
Matthias Braun8d414362016-03-30 22:46:04 +00003227 // Check that the call results are passed in the same way.
3228 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3229 CCAssignFnForCall(CalleeCC, isVarArg),
3230 CCAssignFnForCall(CallerCC, isVarArg)))
3231 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003232 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003233 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3234 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003235 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003236 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3237 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003238 return false;
3239 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003240
3241 // Nothing more to check if the callee is taking no arguments
3242 if (Outs.empty())
3243 return true;
3244
3245 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003246 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003247
3248 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3249
3250 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3251
Matthias Braun74a0bd32016-04-13 21:43:16 +00003252 // If the stack arguments for this call do not fit into our own save area then
3253 // the call cannot be made tail.
3254 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3255 return false;
3256
Matthias Braun46b0f032016-04-14 01:10:42 +00003257 const MachineRegisterInfo &MRI = MF.getRegInfo();
3258 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3259 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003260
3261 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003262}
3263
3264SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3265 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003266 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003267 int ClobberedFI) const {
3268 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003269 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3270 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003271
3272 // Include the original chain at the beginning of the list. When this is
3273 // used by target LowerCall hooks, this helps legalize find the
3274 // CALLSEQ_BEGIN node.
3275 ArgChains.push_back(Chain);
3276
3277 // Add a chain value for each stack argument corresponding
3278 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3279 UE = DAG.getEntryNode().getNode()->use_end();
3280 U != UE; ++U)
3281 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3282 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3283 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003284 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003285 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003286 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003287
3288 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3289 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3290 ArgChains.push_back(SDValue(L, 1));
3291 }
3292
3293 // Build a tokenfactor for all the chains.
3294 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3295}
3296
3297bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3298 bool TailCallOpt) const {
3299 return CallCC == CallingConv::Fast && TailCallOpt;
3300}
3301
Tim Northover3b0846e2014-05-24 12:50:23 +00003302/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3303/// and add input and output parameter nodes.
3304SDValue
3305AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3306 SmallVectorImpl<SDValue> &InVals) const {
3307 SelectionDAG &DAG = CLI.DAG;
3308 SDLoc &DL = CLI.DL;
3309 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3310 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3311 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3312 SDValue Chain = CLI.Chain;
3313 SDValue Callee = CLI.Callee;
3314 bool &IsTailCall = CLI.IsTailCall;
3315 CallingConv::ID CallConv = CLI.CallConv;
3316 bool IsVarArg = CLI.IsVarArg;
3317
3318 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003319 bool IsThisReturn = false;
3320
3321 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3322 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3323 bool IsSibCall = false;
3324
3325 if (IsTailCall) {
3326 // Check if it's really possible to do a tail call.
3327 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003328 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003329 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003330 report_fatal_error("failed to perform tail call elimination on a call "
3331 "site marked musttail");
3332
3333 // A sibling call is one where we're under the usual C ABI and not planning
3334 // to change that but can still do a tail call:
3335 if (!TailCallOpt && IsTailCall)
3336 IsSibCall = true;
3337
3338 if (IsTailCall)
3339 ++NumTailCalls;
3340 }
3341
3342 // Analyze operands of the call, assigning locations to each operand.
3343 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003344 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3345 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003346
3347 if (IsVarArg) {
3348 // Handle fixed and variable vector arguments differently.
3349 // Variable vector arguments always go into memory.
3350 unsigned NumArgs = Outs.size();
3351
3352 for (unsigned i = 0; i != NumArgs; ++i) {
3353 MVT ArgVT = Outs[i].VT;
3354 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3355 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3356 /*IsVarArg=*/ !Outs[i].IsFixed);
3357 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3358 assert(!Res && "Call operand has unhandled type");
3359 (void)Res;
3360 }
3361 } else {
3362 // At this point, Outs[].VT may already be promoted to i32. To correctly
3363 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3364 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3365 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3366 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3367 // LocVT.
3368 unsigned NumArgs = Outs.size();
3369 for (unsigned i = 0; i != NumArgs; ++i) {
3370 MVT ValVT = Outs[i].VT;
3371 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003372 EVT ActualVT = getValueType(DAG.getDataLayout(),
3373 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003374 /*AllowUnknown*/ true);
3375 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3376 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3377 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003378 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003379 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003380 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003381 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003382
3383 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003384 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003385 assert(!Res && "Call operand has unhandled type");
3386 (void)Res;
3387 }
3388 }
3389
3390 // Get a count of how many bytes are to be pushed on the stack.
3391 unsigned NumBytes = CCInfo.getNextStackOffset();
3392
3393 if (IsSibCall) {
3394 // Since we're not changing the ABI to make this a tail call, the memory
3395 // operands are already available in the caller's incoming argument space.
3396 NumBytes = 0;
3397 }
3398
3399 // FPDiff is the byte offset of the call's argument area from the callee's.
3400 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3401 // by this amount for a tail call. In a sibling call it must be 0 because the
3402 // caller will deallocate the entire stack and the callee still expects its
3403 // arguments to begin at SP+0. Completely unused for non-tail calls.
3404 int FPDiff = 0;
3405
3406 if (IsTailCall && !IsSibCall) {
3407 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3408
3409 // Since callee will pop argument stack as a tail call, we must keep the
3410 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003411 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003412
3413 // FPDiff will be negative if this tail call requires more space than we
3414 // would automatically have in our incoming argument space. Positive if we
3415 // can actually shrink the stack.
3416 FPDiff = NumReusableBytes - NumBytes;
3417
3418 // The stack pointer must be 16-byte aligned at all times it's used for a
3419 // memory operation, which in practice means at *all* times and in
3420 // particular across call boundaries. Therefore our own arguments started at
3421 // a 16-byte aligned SP and the delta applied for the tail call should
3422 // satisfy the same constraint.
3423 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3424 }
3425
3426 // Adjust the stack pointer for the new arguments...
3427 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003428 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003429 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003430
Mehdi Amini44ede332015-07-09 02:09:04 +00003431 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3432 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003433
3434 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3435 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003436 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003437
3438 // Walk the register/memloc assignments, inserting copies/loads.
3439 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3440 ++i, ++realArgIdx) {
3441 CCValAssign &VA = ArgLocs[i];
3442 SDValue Arg = OutVals[realArgIdx];
3443 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3444
3445 // Promote the value if needed.
3446 switch (VA.getLocInfo()) {
3447 default:
3448 llvm_unreachable("Unknown loc info!");
3449 case CCValAssign::Full:
3450 break;
3451 case CCValAssign::SExt:
3452 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3453 break;
3454 case CCValAssign::ZExt:
3455 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3456 break;
3457 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003458 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3459 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3460 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3461 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3462 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003463 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3464 break;
3465 case CCValAssign::BCvt:
3466 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3467 break;
3468 case CCValAssign::FPExt:
3469 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3470 break;
3471 }
3472
3473 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003474 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3475 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003476 assert(VA.getLocVT() == MVT::i64 &&
3477 "unexpected calling convention register assignment");
3478 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3479 "unexpected use of 'returned'");
3480 IsThisReturn = true;
3481 }
3482 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3483 } else {
3484 assert(VA.isMemLoc());
3485
3486 SDValue DstAddr;
3487 MachinePointerInfo DstInfo;
3488
3489 // FIXME: This works on big-endian for composite byvals, which are the
3490 // common case. It should also work for fundamental types too.
3491 uint32_t BEAlign = 0;
3492 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003493 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003494 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003495 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3496 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003497 if (OpSize < 8)
3498 BEAlign = 8 - OpSize;
3499 }
3500 unsigned LocMemOffset = VA.getLocMemOffset();
3501 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003502 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003503 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003504
3505 if (IsTailCall) {
3506 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003507 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003508
Mehdi Amini44ede332015-07-09 02:09:04 +00003509 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003510 DstInfo =
3511 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003512
3513 // Make sure any stack arguments overlapping with where we're storing
3514 // are loaded before this eventual operation. Otherwise they'll be
3515 // clobbered.
3516 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3517 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003518 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003519
Mehdi Amini44ede332015-07-09 02:09:04 +00003520 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003521 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3522 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003523 }
3524
3525 if (Outs[i].Flags.isByVal()) {
3526 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003527 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003528 SDValue Cpy = DAG.getMemcpy(
3529 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003530 /*isVol = */ false, /*AlwaysInline = */ false,
3531 /*isTailCall = */ false,
3532 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003533
3534 MemOpChains.push_back(Cpy);
3535 } else {
3536 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3537 // promoted to a legal register type i32, we should truncate Arg back to
3538 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003539 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3540 VA.getValVT() == MVT::i16)
3541 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003542
Justin Lebar9c375812016-07-15 18:27:10 +00003543 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003544 MemOpChains.push_back(Store);
3545 }
3546 }
3547 }
3548
3549 if (!MemOpChains.empty())
3550 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3551
3552 // Build a sequence of copy-to-reg nodes chained together with token chain
3553 // and flag operands which copy the outgoing args into the appropriate regs.
3554 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003555 for (auto &RegToPass : RegsToPass) {
3556 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3557 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003558 InFlag = Chain.getValue(1);
3559 }
3560
3561 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3562 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3563 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003564 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3565 auto GV = G->getGlobal();
3566 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3567 AArch64II::MO_GOT) {
3568 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3569 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003570 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3571 assert(Subtarget->isTargetWindows() &&
3572 "Windows is the only supported COFF target");
3573 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003574 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003575 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003576 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3577 }
3578 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3579 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3580 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003581 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003582 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3583 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003584 } else {
3585 const char *Sym = S->getSymbol();
3586 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003587 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003588 }
3589
3590 // We don't usually want to end the call-sequence here because we would tidy
3591 // the frame up *after* the call, however in the ABI-changing tail-call case
3592 // we've carefully laid out the parameters so that when sp is reset they'll be
3593 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003594 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003595 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3596 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003597 InFlag = Chain.getValue(1);
3598 }
3599
3600 std::vector<SDValue> Ops;
3601 Ops.push_back(Chain);
3602 Ops.push_back(Callee);
3603
3604 if (IsTailCall) {
3605 // Each tail call may have to adjust the stack by a different amount, so
3606 // this information must travel along with the operation for eventual
3607 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003608 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003609 }
3610
3611 // Add argument registers to the end of the list so that they are known live
3612 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003613 for (auto &RegToPass : RegsToPass)
3614 Ops.push_back(DAG.getRegister(RegToPass.first,
3615 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003616
3617 // Add a register mask operand representing the call-preserved registers.
3618 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003619 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003620 if (IsThisReturn) {
3621 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003622 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003623 if (!Mask) {
3624 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003625 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003626 }
3627 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003628 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003629
3630 assert(Mask && "Missing call preserved mask for calling convention");
3631 Ops.push_back(DAG.getRegisterMask(Mask));
3632
3633 if (InFlag.getNode())
3634 Ops.push_back(InFlag);
3635
3636 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3637
3638 // If we're doing a tall call, use a TC_RETURN here rather than an
3639 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003640 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003641 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003642 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003643 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003644
3645 // Returns a chain and a flag for retval copy to use.
3646 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3647 InFlag = Chain.getValue(1);
3648
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003649 uint64_t CalleePopBytes =
3650 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003651
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003652 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3653 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3654 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003655 if (!Ins.empty())
3656 InFlag = Chain.getValue(1);
3657
3658 // Handle result values, copying them out of physregs into vregs that we
3659 // return.
3660 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3661 InVals, IsThisReturn,
3662 IsThisReturn ? OutVals[0] : SDValue());
3663}
3664
3665bool AArch64TargetLowering::CanLowerReturn(
3666 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3667 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3668 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3669 ? RetCC_AArch64_WebKit_JS
3670 : RetCC_AArch64_AAPCS;
3671 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003672 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003673 return CCInfo.CheckReturn(Outs, RetCC);
3674}
3675
3676SDValue
3677AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3678 bool isVarArg,
3679 const SmallVectorImpl<ISD::OutputArg> &Outs,
3680 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003681 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003682 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3683 ? RetCC_AArch64_WebKit_JS
3684 : RetCC_AArch64_AAPCS;
3685 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003686 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3687 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003688 CCInfo.AnalyzeReturn(Outs, RetCC);
3689
3690 // Copy the result values into the output registers.
3691 SDValue Flag;
3692 SmallVector<SDValue, 4> RetOps(1, Chain);
3693 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3694 ++i, ++realRVLocIdx) {
3695 CCValAssign &VA = RVLocs[i];
3696 assert(VA.isRegLoc() && "Can only return in registers!");
3697 SDValue Arg = OutVals[realRVLocIdx];
3698
3699 switch (VA.getLocInfo()) {
3700 default:
3701 llvm_unreachable("Unknown loc info!");
3702 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003703 if (Outs[i].ArgVT == MVT::i1) {
3704 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3705 // value. This is strictly redundant on Darwin (which uses "zeroext
3706 // i1"), but will be optimised out before ISel.
3707 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3708 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3709 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003710 break;
3711 case CCValAssign::BCvt:
3712 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3713 break;
3714 }
3715
3716 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3717 Flag = Chain.getValue(1);
3718 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3719 }
Manman Rencbe4f942015-12-16 21:04:19 +00003720 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3721 const MCPhysReg *I =
3722 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3723 if (I) {
3724 for (; *I; ++I) {
3725 if (AArch64::GPR64RegClass.contains(*I))
3726 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3727 else if (AArch64::FPR64RegClass.contains(*I))
3728 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3729 else
3730 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3731 }
3732 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003733
3734 RetOps[0] = Chain; // Update chain.
3735
3736 // Add the flag if we have it.
3737 if (Flag.getNode())
3738 RetOps.push_back(Flag);
3739
3740 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3741}
3742
3743//===----------------------------------------------------------------------===//
3744// Other Lowering Code
3745//===----------------------------------------------------------------------===//
3746
Joel Jonesa7c4a522017-04-21 17:31:03 +00003747SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3748 SelectionDAG &DAG,
3749 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003750 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3751 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003752}
3753
3754SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3755 SelectionDAG &DAG,
3756 unsigned Flag) const {
3757 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3758}
3759
3760SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3761 SelectionDAG &DAG,
3762 unsigned Flag) const {
3763 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3764 N->getOffset(), Flag);
3765}
3766
3767SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3768 SelectionDAG &DAG,
3769 unsigned Flag) const {
3770 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3771}
3772
3773// (loadGOT sym)
3774template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003775SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3776 unsigned Flags) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003777 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3778 SDLoc DL(N);
3779 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003780 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003781 // FIXME: Once remat is capable of dealing with instructions with register
3782 // operands, expand this into two nodes instead of using a wrapper node.
3783 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3784}
3785
3786// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3787template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003788SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3789 unsigned Flags) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003790 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3791 SDLoc DL(N);
3792 EVT Ty = getPointerTy(DAG.getDataLayout());
3793 const unsigned char MO_NC = AArch64II::MO_NC;
3794 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003795 AArch64ISD::WrapperLarge, DL, Ty,
3796 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3797 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3798 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3799 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00003800}
3801
3802// (addlow (adrp %hi(sym)) %lo(sym))
3803template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003804SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3805 unsigned Flags) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003806 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3807 SDLoc DL(N);
3808 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003809 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003810 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003811 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003812 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3813 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3814}
3815
Tim Northover3b0846e2014-05-24 12:50:23 +00003816SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3817 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003818 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003819 const GlobalValue *GV = GN->getGlobal();
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003820 const AArch64II::TOF TargetFlags =
3821 (GV->hasDLLImportStorageClass() ? AArch64II::MO_DLLIMPORT
3822 : AArch64II::MO_NO_FLAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003823 unsigned char OpFlags =
3824 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00003825
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003826 if (OpFlags != AArch64II::MO_NO_FLAG)
3827 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3828 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00003829
Joel Jonesa7c4a522017-04-21 17:31:03 +00003830 // This also catches the large code model case for Darwin.
Tim Northover3b0846e2014-05-24 12:50:23 +00003831 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003832 return getGOT(GN, DAG, TargetFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003833 }
3834
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003835 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00003836 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003837 Result = getAddrLarge(GN, DAG, TargetFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003838 } else {
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003839 Result = getAddr(GN, DAG, TargetFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003840 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003841 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3842 SDLoc DL(GN);
3843 if (GV->hasDLLImportStorageClass())
3844 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3845 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3846 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00003847}
3848
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003849/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00003850/// and calls to compute the variable's address (for Darwin, currently) and
3851/// return an SDValue containing the final node.
3852
3853/// Darwin only has one TLS scheme which must be capable of dealing with the
3854/// fully general situation, in the worst case. This means:
3855/// + "extern __thread" declaration.
3856/// + Defined in a possibly unknown dynamic library.
3857///
3858/// The general system is that each __thread variable has a [3 x i64] descriptor
3859/// which contains information used by the runtime to calculate the address. The
3860/// only part of this the compiler needs to know about is the first xword, which
3861/// contains a function pointer that must be called with the address of the
3862/// entire descriptor in "x0".
3863///
3864/// Since this descriptor may be in a different unit, in general even the
3865/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3866/// is:
3867/// adrp x0, _var@TLVPPAGE
3868/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3869/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3870/// ; the function pointer
3871/// blr x1 ; Uses descriptor address in x0
3872/// ; Address of _var is now in x0.
3873///
3874/// If the address of _var's descriptor *is* known to the linker, then it can
3875/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3876/// a slight efficiency gain.
3877SDValue
3878AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3879 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00003880 assert(Subtarget->isTargetDarwin() &&
3881 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00003882
3883 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003884 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003885 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3886
3887 SDValue TLVPAddr =
3888 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3889 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3890
3891 // The first entry in the descriptor is a function pointer that we must call
3892 // to obtain the address of the variable.
3893 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00003894 SDValue FuncTLVGet = DAG.getLoad(
3895 MVT::i64, DL, Chain, DescAddr,
3896 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3897 /* Alignment = */ 8,
3898 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3899 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00003900 Chain = FuncTLVGet.getValue(1);
3901
Matthias Braun941a7052016-07-28 18:40:00 +00003902 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3903 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003904
3905 // TLS calls preserve all registers except those that absolutely must be
3906 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3907 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003908 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003909 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003910
3911 // Finally, we can make the call. This is just a degenerate version of a
3912 // normal AArch64 call node: x0 takes the address of the descriptor, and
3913 // returns the address of the variable in this thread.
3914 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3915 Chain =
3916 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3917 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3918 DAG.getRegisterMask(Mask), Chain.getValue(1));
3919 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3920}
3921
3922/// When accessing thread-local variables under either the general-dynamic or
3923/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3924/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003925/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003926///
Kristof Beylsaea84612015-03-04 09:12:08 +00003927/// The sequence is:
3928/// adrp x0, :tlsdesc:var
3929/// ldr x1, [x0, #:tlsdesc_lo12:var]
3930/// add x0, x0, #:tlsdesc_lo12:var
3931/// .tlsdesccall var
3932/// blr x1
3933/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003934///
Kristof Beylsaea84612015-03-04 09:12:08 +00003935/// The above sequence must be produced unscheduled, to enable the linker to
3936/// optimize/relax this sequence.
3937/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3938/// above sequence, and expanded really late in the compilation flow, to ensure
3939/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003940SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3941 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003942 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003943 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003944
Kristof Beylsaea84612015-03-04 09:12:08 +00003945 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003946 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003947
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003948 Chain =
3949 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003950 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003951
3952 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3953}
3954
3955SDValue
3956AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3957 SelectionDAG &DAG) const {
3958 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
Petr Hosek9eb0a1e2017-04-04 19:51:53 +00003959 assert(Subtarget->useSmallAddressing() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003960 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003961 // Different choices can be made for the maximum size of the TLS area for a
3962 // module. For the small address model, the default TLS size is 16MiB and the
3963 // maximum TLS size is 4GiB.
3964 // FIXME: add -mtls-size command line option and make it control the 16MiB
3965 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003966 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3967
3968 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003969
Kristof Beylsaea84612015-03-04 09:12:08 +00003970 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3971 if (Model == TLSModel::LocalDynamic)
3972 Model = TLSModel::GeneralDynamic;
3973 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003974
3975 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003976 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003977 SDLoc DL(Op);
3978 const GlobalValue *GV = GA->getGlobal();
3979
3980 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3981
3982 if (Model == TLSModel::LocalExec) {
3983 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003984 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003985 SDValue LoVar = DAG.getTargetGlobalAddress(
3986 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003987 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003988
Kristof Beylsaea84612015-03-04 09:12:08 +00003989 SDValue TPWithOff_lo =
3990 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003991 HiVar,
3992 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003993 0);
3994 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00003995 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3996 LoVar,
3997 DAG.getTargetConstant(0, DL, MVT::i32)),
3998 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00003999 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004000 } else if (Model == TLSModel::InitialExec) {
4001 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4002 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4003 } else if (Model == TLSModel::LocalDynamic) {
4004 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4005 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4006 // the beginning of the module's TLS region, followed by a DTPREL offset
4007 // calculation.
4008
4009 // These accesses will need deduplicating if there's more than one.
4010 AArch64FunctionInfo *MFI =
4011 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4012 MFI->incNumLocalDynamicTLSAccesses();
4013
Tim Northover3b0846e2014-05-24 12:50:23 +00004014 // The call needs a relocation too for linker relaxation. It doesn't make
4015 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4016 // the address.
4017 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4018 AArch64II::MO_TLS);
4019
4020 // Now we can calculate the offset from TPIDR_EL0 to this module's
4021 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004022 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004023
4024 // Now use :dtprel_whatever: operations to calculate this variable's offset
4025 // in its thread-storage area.
4026 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004027 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004028 SDValue LoVar = DAG.getTargetGlobalAddress(
4029 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004030 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4031
Kristof Beylsaea84612015-03-04 09:12:08 +00004032 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004033 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004034 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004035 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4036 DAG.getTargetConstant(0, DL, MVT::i32)),
4037 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004038 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004039 // The call needs a relocation too for linker relaxation. It doesn't make
4040 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4041 // the address.
4042 SDValue SymAddr =
4043 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4044
4045 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004046 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004047 } else
4048 llvm_unreachable("Unsupported ELF TLS access model");
4049
4050 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4051}
4052
Martin Storsjocc240962018-03-10 19:05:21 +00004053SDValue
4054AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4055 SelectionDAG &DAG) const {
4056 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4057
4058 SDValue Chain = DAG.getEntryNode();
4059 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4060 SDLoc DL(Op);
4061
4062 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4063
4064 // Load the ThreadLocalStoragePointer from the TEB
4065 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4066 SDValue TLSArray =
4067 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4068 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4069 Chain = TLSArray.getValue(1);
4070
4071 // Load the TLS index from the C runtime;
4072 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4073 // This also does the same as LOADgot, but using a generic i32 load,
4074 // while LOADgot only loads i64.
4075 SDValue TLSIndexHi =
4076 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4077 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4078 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4079 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4080 SDValue TLSIndex =
4081 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4082 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4083 Chain = TLSIndex.getValue(1);
4084
4085 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4086 // offset into the TLSArray.
4087 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4088 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4089 DAG.getConstant(3, DL, PtrVT));
4090 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4091 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4092 MachinePointerInfo());
4093 Chain = TLS.getValue(1);
4094
4095 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4096 const GlobalValue *GV = GA->getGlobal();
4097 SDValue TGAHi = DAG.getTargetGlobalAddress(
4098 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4099 SDValue TGALo = DAG.getTargetGlobalAddress(
4100 GV, DL, PtrVT, 0,
4101 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4102
4103 // Add the offset from the start of the .tls section (section base).
4104 SDValue Addr =
4105 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4106 DAG.getTargetConstant(0, DL, MVT::i32)),
4107 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004108 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004109 return Addr;
4110}
4111
Tim Northover3b0846e2014-05-24 12:50:23 +00004112SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4113 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004114 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004115 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004116 return LowerToTLSEmulatedModel(GA, DAG);
4117
Tim Northover3b0846e2014-05-24 12:50:23 +00004118 if (Subtarget->isTargetDarwin())
4119 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004120 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004121 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004122 if (Subtarget->isTargetWindows())
4123 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004124
4125 llvm_unreachable("Unexpected platform trying to use TLS");
4126}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004127
Tim Northover3b0846e2014-05-24 12:50:23 +00004128SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4129 SDValue Chain = Op.getOperand(0);
4130 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4131 SDValue LHS = Op.getOperand(2);
4132 SDValue RHS = Op.getOperand(3);
4133 SDValue Dest = Op.getOperand(4);
4134 SDLoc dl(Op);
4135
4136 // Handle f128 first, since lowering it will result in comparing the return
4137 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4138 // is expecting to deal with.
4139 if (LHS.getValueType() == MVT::f128) {
4140 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4141
4142 // If softenSetCCOperands returned a scalar, we need to compare the result
4143 // against zero to select between true and false values.
4144 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004145 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004146 CC = ISD::SETNE;
4147 }
4148 }
4149
4150 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4151 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004152 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4153 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004154 // Only lower legal XALUO ops.
4155 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4156 return SDValue();
4157
4158 // The actual operation with overflow check.
4159 AArch64CC::CondCode OFCC;
4160 SDValue Value, Overflow;
4161 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4162
4163 if (CC == ISD::SETNE)
4164 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004165 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004166
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004167 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4168 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004169 }
4170
4171 if (LHS.getValueType().isInteger()) {
4172 assert((LHS.getValueType() == RHS.getValueType()) &&
4173 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4174
4175 // If the RHS of the comparison is zero, we can potentially fold this
4176 // to a specialized branch.
4177 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4178 if (RHSC && RHSC->getZExtValue() == 0) {
4179 if (CC == ISD::SETEQ) {
4180 // See if we can use a TBZ to fold in an AND as well.
4181 // TBZ has a smaller branch displacement than CBZ. If the offset is
4182 // out of bounds, a late MI-layer pass rewrites branches.
4183 // 403.gcc is an example that hits this case.
4184 if (LHS.getOpcode() == ISD::AND &&
4185 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4186 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4187 SDValue Test = LHS.getOperand(0);
4188 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004189 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004190 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4191 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004192 }
4193
4194 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4195 } else if (CC == ISD::SETNE) {
4196 // See if we can use a TBZ to fold in an AND as well.
4197 // TBZ has a smaller branch displacement than CBZ. If the offset is
4198 // out of bounds, a late MI-layer pass rewrites branches.
4199 // 403.gcc is an example that hits this case.
4200 if (LHS.getOpcode() == ISD::AND &&
4201 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4202 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4203 SDValue Test = LHS.getOperand(0);
4204 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004205 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004206 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4207 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004208 }
4209
4210 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004211 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4212 // Don't combine AND since emitComparison converts the AND to an ANDS
4213 // (a.k.a. TST) and the test in the test bit and branch instruction
4214 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004215 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004216 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004217 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004218 }
4219 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004220 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4221 LHS.getOpcode() != ISD::AND) {
4222 // Don't combine AND since emitComparison converts the AND to an ANDS
4223 // (a.k.a. TST) and the test in the test bit and branch instruction
4224 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004225 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004226 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004227 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004228 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004229
4230 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004231 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004232 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4233 Cmp);
4234 }
4235
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004236 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4237 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004238
4239 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4240 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004241 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004242 AArch64CC::CondCode CC1, CC2;
4243 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004244 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004245 SDValue BR1 =
4246 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4247 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004248 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004249 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4250 Cmp);
4251 }
4252
4253 return BR1;
4254}
4255
4256SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4257 SelectionDAG &DAG) const {
4258 EVT VT = Op.getValueType();
4259 SDLoc DL(Op);
4260
4261 SDValue In1 = Op.getOperand(0);
4262 SDValue In2 = Op.getOperand(1);
4263 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004264
4265 if (SrcVT.bitsLT(VT))
4266 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4267 else if (SrcVT.bitsGT(VT))
4268 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004269
4270 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004271 uint64_t EltMask;
4272 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004273
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004274 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004275 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004276 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004277 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004278 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004279 DAG.getUNDEF(VecVT), In2);
4280 } else {
4281 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4282 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4283 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004284 };
4285
4286 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4287 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4288 EltMask = 0x80000000ULL;
4289 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004290 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004291 VecVT = MVT::v2i64;
4292
Eric Christopher572e03a2015-06-19 01:53:21 +00004293 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004294 // immediate moves cannot materialize that in a single instruction for
4295 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004296 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004297
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004298 setVecVal(AArch64::dsub);
4299 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4300 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4301 EltMask = 0x8000ULL;
4302 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004303 } else {
4304 llvm_unreachable("Invalid type for copysign!");
4305 }
4306
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004307 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004308
4309 // If we couldn't materialize the mask above, then the mask vector will be
4310 // the zero vector, and we need to negate it here.
4311 if (VT == MVT::f64 || VT == MVT::v2f64) {
4312 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4313 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4314 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4315 }
4316
4317 SDValue Sel =
4318 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4319
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004320 if (VT == MVT::f16)
4321 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004322 if (VT == MVT::f32)
4323 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4324 else if (VT == MVT::f64)
4325 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4326 else
4327 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4328}
4329
4330SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004331 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004332 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004333 return SDValue();
4334
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004335 if (!Subtarget->hasNEON())
4336 return SDValue();
4337
Tim Northover3b0846e2014-05-24 12:50:23 +00004338 // While there is no integer popcount instruction, it can
4339 // be more efficiently lowered to the following sequence that uses
4340 // AdvSIMD registers/instructions as long as the copies to/from
4341 // the AdvSIMD registers are cheap.
4342 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4343 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4344 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4345 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4346 SDValue Val = Op.getOperand(0);
4347 SDLoc DL(Op);
4348 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004349
Hao Liue0335d72015-01-30 02:13:53 +00004350 if (VT == MVT::i32)
4351 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4352 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004353
Hao Liue0335d72015-01-30 02:13:53 +00004354 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004355 SDValue UaddLV = DAG.getNode(
4356 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004357 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004358
4359 if (VT == MVT::i64)
4360 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4361 return UaddLV;
4362}
4363
4364SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4365
4366 if (Op.getValueType().isVector())
4367 return LowerVSETCC(Op, DAG);
4368
4369 SDValue LHS = Op.getOperand(0);
4370 SDValue RHS = Op.getOperand(1);
4371 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4372 SDLoc dl(Op);
4373
4374 // We chose ZeroOrOneBooleanContents, so use zero and one.
4375 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004376 SDValue TVal = DAG.getConstant(1, dl, VT);
4377 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004378
4379 // Handle f128 first, since one possible outcome is a normal integer
4380 // comparison which gets picked up by the next if statement.
4381 if (LHS.getValueType() == MVT::f128) {
4382 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4383
4384 // If softenSetCCOperands returned a scalar, use it.
4385 if (!RHS.getNode()) {
4386 assert(LHS.getValueType() == Op.getValueType() &&
4387 "Unexpected setcc expansion!");
4388 return LHS;
4389 }
4390 }
4391
4392 if (LHS.getValueType().isInteger()) {
4393 SDValue CCVal;
4394 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004395 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004396
4397 // Note that we inverted the condition above, so we reverse the order of
4398 // the true and false operands here. This will allow the setcc to be
4399 // matched to a single CSINC instruction.
4400 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4401 }
4402
4403 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004404 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4405 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004406
4407 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4408 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004409 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004410
4411 AArch64CC::CondCode CC1, CC2;
4412 changeFPCCToAArch64CC(CC, CC1, CC2);
4413 if (CC2 == AArch64CC::AL) {
4414 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004415 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004416
4417 // Note that we inverted the condition above, so we reverse the order of
4418 // the true and false operands here. This will allow the setcc to be
4419 // matched to a single CSINC instruction.
4420 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4421 } else {
4422 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4423 // totally clean. Some of them require two CSELs to implement. As is in
4424 // this case, we emit the first CSEL and then emit a second using the output
4425 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4426
4427 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004428 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004429 SDValue CS1 =
4430 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4431
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004432 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004433 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4434 }
4435}
4436
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004437SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4438 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004439 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004440 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004441 // Handle f128 first, because it will result in a comparison of some RTLIB
4442 // call result against zero.
4443 if (LHS.getValueType() == MVT::f128) {
4444 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4445
4446 // If softenSetCCOperands returned a scalar, we need to compare the result
4447 // against zero to select between true and false values.
4448 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004449 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004450 CC = ISD::SETNE;
4451 }
4452 }
4453
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004454 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004455 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004456 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4457 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4458 }
4459
4460 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004461 if (LHS.getValueType().isInteger()) {
4462 assert((LHS.getValueType() == RHS.getValueType()) &&
4463 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4464
4465 unsigned Opcode = AArch64ISD::CSEL;
4466
4467 // If both the TVal and the FVal are constants, see if we can swap them in
4468 // order to for a CSINV or CSINC out of them.
4469 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4470 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4471
4472 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4473 std::swap(TVal, FVal);
4474 std::swap(CTVal, CFVal);
4475 CC = ISD::getSetCCInverse(CC, true);
4476 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4477 std::swap(TVal, FVal);
4478 std::swap(CTVal, CFVal);
4479 CC = ISD::getSetCCInverse(CC, true);
4480 } else if (TVal.getOpcode() == ISD::XOR) {
4481 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4482 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004483 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004484 std::swap(TVal, FVal);
4485 std::swap(CTVal, CFVal);
4486 CC = ISD::getSetCCInverse(CC, true);
4487 }
4488 } else if (TVal.getOpcode() == ISD::SUB) {
4489 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4490 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004491 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004492 std::swap(TVal, FVal);
4493 std::swap(CTVal, CFVal);
4494 CC = ISD::getSetCCInverse(CC, true);
4495 }
4496 } else if (CTVal && CFVal) {
4497 const int64_t TrueVal = CTVal->getSExtValue();
4498 const int64_t FalseVal = CFVal->getSExtValue();
4499 bool Swap = false;
4500
4501 // If both TVal and FVal are constants, see if FVal is the
4502 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4503 // instead of a CSEL in that case.
4504 if (TrueVal == ~FalseVal) {
4505 Opcode = AArch64ISD::CSINV;
4506 } else if (TrueVal == -FalseVal) {
4507 Opcode = AArch64ISD::CSNEG;
4508 } else if (TVal.getValueType() == MVT::i32) {
4509 // If our operands are only 32-bit wide, make sure we use 32-bit
4510 // arithmetic for the check whether we can use CSINC. This ensures that
4511 // the addition in the check will wrap around properly in case there is
4512 // an overflow (which would not be the case if we do the check with
4513 // 64-bit arithmetic).
4514 const uint32_t TrueVal32 = CTVal->getZExtValue();
4515 const uint32_t FalseVal32 = CFVal->getZExtValue();
4516
4517 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4518 Opcode = AArch64ISD::CSINC;
4519
4520 if (TrueVal32 > FalseVal32) {
4521 Swap = true;
4522 }
4523 }
4524 // 64-bit check whether we can use CSINC.
4525 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4526 Opcode = AArch64ISD::CSINC;
4527
4528 if (TrueVal > FalseVal) {
4529 Swap = true;
4530 }
4531 }
4532
4533 // Swap TVal and FVal if necessary.
4534 if (Swap) {
4535 std::swap(TVal, FVal);
4536 std::swap(CTVal, CFVal);
4537 CC = ISD::getSetCCInverse(CC, true);
4538 }
4539
4540 if (Opcode != AArch64ISD::CSEL) {
4541 // Drop FVal since we can get its value by simply inverting/negating
4542 // TVal.
4543 FVal = TVal;
4544 }
4545 }
4546
Chad Rosier58f505b2016-08-26 18:05:50 +00004547 // Avoid materializing a constant when possible by reusing a known value in
4548 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004549 // is one, zero or negative one in the case of a CSEL. We can always
4550 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4551 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004552 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4553 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4554 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4555 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4556 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4557 // "a != C ? x : a" to avoid materializing C.
4558 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4559 TVal = LHS;
4560 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4561 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004562 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4563 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4564 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4565 // avoid materializing C.
4566 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4567 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4568 Opcode = AArch64ISD::CSINV;
4569 TVal = LHS;
4570 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4571 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004572 }
4573
Tim Northover3b0846e2014-05-24 12:50:23 +00004574 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004575 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004576 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004577 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4578 }
4579
4580 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004581 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4582 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004583 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004584 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004585 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004586
4587 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4588 // clean. Some of them require two CSELs to implement.
4589 AArch64CC::CondCode CC1, CC2;
4590 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004591
4592 if (DAG.getTarget().Options.UnsafeFPMath) {
4593 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4594 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4595 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4596 if (RHSVal && RHSVal->isZero()) {
4597 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4598 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4599
4600 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004601 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004602 TVal = LHS;
4603 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004604 CFVal && CFVal->isZero() &&
4605 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004606 FVal = LHS;
4607 }
4608 }
4609
4610 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004611 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004612 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4613
4614 // If we need a second CSEL, emit it, using the output of the first as the
4615 // RHS. We're effectively OR'ing the two CC's together.
4616 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004617 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004618 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4619 }
4620
4621 // Otherwise, return the output of the first CSEL.
4622 return CS1;
4623}
4624
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004625SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4626 SelectionDAG &DAG) const {
4627 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4628 SDValue LHS = Op.getOperand(0);
4629 SDValue RHS = Op.getOperand(1);
4630 SDValue TVal = Op.getOperand(2);
4631 SDValue FVal = Op.getOperand(3);
4632 SDLoc DL(Op);
4633 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4634}
4635
4636SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4637 SelectionDAG &DAG) const {
4638 SDValue CCVal = Op->getOperand(0);
4639 SDValue TVal = Op->getOperand(1);
4640 SDValue FVal = Op->getOperand(2);
4641 SDLoc DL(Op);
4642
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004643 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4644 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004645 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004646 // Only lower legal XALUO ops.
4647 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4648 return SDValue();
4649
4650 AArch64CC::CondCode OFCC;
4651 SDValue Value, Overflow;
4652 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004653 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004654
4655 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4656 CCVal, Overflow);
4657 }
4658
4659 // Lower it the same way as we would lower a SELECT_CC node.
4660 ISD::CondCode CC;
4661 SDValue LHS, RHS;
4662 if (CCVal.getOpcode() == ISD::SETCC) {
4663 LHS = CCVal.getOperand(0);
4664 RHS = CCVal.getOperand(1);
4665 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4666 } else {
4667 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004668 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004669 CC = ISD::SETNE;
4670 }
4671 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4672}
4673
Tim Northover3b0846e2014-05-24 12:50:23 +00004674SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4675 SelectionDAG &DAG) const {
4676 // Jump table entries as PC relative offsets. No additional tweaking
4677 // is necessary here. Just get the address of the jump table.
4678 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004679
4680 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4681 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004682 return getAddrLarge(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004683 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004684 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004685}
4686
4687SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4688 SelectionDAG &DAG) const {
4689 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004690
4691 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4692 // Use the GOT for the large code model on iOS.
4693 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004694 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004695 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004696 return getAddrLarge(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004697 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004698 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004699 }
4700}
4701
4702SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4703 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004704 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004705 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4706 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004707 return getAddrLarge(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004708 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004709 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004710 }
4711}
4712
4713SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4714 SelectionDAG &DAG) const {
4715 AArch64FunctionInfo *FuncInfo =
4716 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4717
4718 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004719 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4720 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004721 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4722 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004723 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004724}
4725
Martin Storsjo68266fa2017-07-13 17:03:12 +00004726SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4727 SelectionDAG &DAG) const {
4728 AArch64FunctionInfo *FuncInfo =
4729 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4730
4731 SDLoc DL(Op);
4732 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4733 ? FuncInfo->getVarArgsGPRIndex()
4734 : FuncInfo->getVarArgsStackIndex(),
4735 getPointerTy(DAG.getDataLayout()));
4736 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4737 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4738 MachinePointerInfo(SV));
4739}
4740
Tim Northover3b0846e2014-05-24 12:50:23 +00004741SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4742 SelectionDAG &DAG) const {
4743 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4744 // Standard, section B.3.
4745 MachineFunction &MF = DAG.getMachineFunction();
4746 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004747 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004748 SDLoc DL(Op);
4749
4750 SDValue Chain = Op.getOperand(0);
4751 SDValue VAList = Op.getOperand(1);
4752 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4753 SmallVector<SDValue, 4> MemOps;
4754
4755 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004756 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004757 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004758 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004759
4760 // void *__gr_top at offset 8
4761 int GPRSize = FuncInfo->getVarArgsGPRSize();
4762 if (GPRSize > 0) {
4763 SDValue GRTop, GRTopAddr;
4764
Mehdi Amini44ede332015-07-09 02:09:04 +00004765 GRTopAddr =
4766 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004767
Mehdi Amini44ede332015-07-09 02:09:04 +00004768 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4769 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4770 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004771
4772 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004773 MachinePointerInfo(SV, 8),
4774 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004775 }
4776
4777 // void *__vr_top at offset 16
4778 int FPRSize = FuncInfo->getVarArgsFPRSize();
4779 if (FPRSize > 0) {
4780 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004781 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4782 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004783
Mehdi Amini44ede332015-07-09 02:09:04 +00004784 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4785 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4786 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004787
4788 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004789 MachinePointerInfo(SV, 16),
4790 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004791 }
4792
4793 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004794 SDValue GROffsAddr =
4795 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004796 MemOps.push_back(DAG.getStore(
4797 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4798 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004799
4800 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004801 SDValue VROffsAddr =
4802 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004803 MemOps.push_back(DAG.getStore(
4804 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4805 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004806
4807 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4808}
4809
4810SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4811 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00004812 MachineFunction &MF = DAG.getMachineFunction();
4813
Matthias Braunf1caa282017-12-15 22:22:58 +00004814 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00004815 return LowerWin64_VASTART(Op, DAG);
4816 else if (Subtarget->isTargetDarwin())
4817 return LowerDarwin_VASTART(Op, DAG);
4818 else
4819 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004820}
4821
4822SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4823 SelectionDAG &DAG) const {
4824 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4825 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004826 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00004827 unsigned VaListSize =
4828 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00004829 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4830 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4831
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004832 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4833 Op.getOperand(2),
4834 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004835 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004836 MachinePointerInfo(SrcSV));
4837}
4838
4839SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4840 assert(Subtarget->isTargetDarwin() &&
4841 "automatic va_arg instruction only works on Darwin");
4842
4843 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4844 EVT VT = Op.getValueType();
4845 SDLoc DL(Op);
4846 SDValue Chain = Op.getOperand(0);
4847 SDValue Addr = Op.getOperand(1);
4848 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004849 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004850
Justin Lebar9c375812016-07-15 18:27:10 +00004851 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004852 Chain = VAList.getValue(1);
4853
4854 if (Align > 8) {
4855 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004856 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4857 DAG.getConstant(Align - 1, DL, PtrVT));
4858 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4859 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004860 }
4861
4862 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004863 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004864
4865 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4866 // up to 64 bits. At the very least, we have to increase the striding of the
4867 // vaargs list to match this, and for FP values we need to introduce
4868 // FP_ROUND nodes as well.
4869 if (VT.isInteger() && !VT.isVector())
4870 ArgSize = 8;
4871 bool NeedFPTrunc = false;
4872 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4873 ArgSize = 8;
4874 NeedFPTrunc = true;
4875 }
4876
4877 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004878 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4879 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004880 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004881 SDValue APStore =
4882 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004883
4884 // Load the actual argument out of the pointer VAList
4885 if (NeedFPTrunc) {
4886 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004887 SDValue WideFP =
4888 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004889 // Round the value down to an f32.
4890 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004891 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004892 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4893 // Merge the rounded value with the chain output of the load.
4894 return DAG.getMergeValues(Ops, DL);
4895 }
4896
Justin Lebar9c375812016-07-15 18:27:10 +00004897 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004898}
4899
4900SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4901 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004902 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4903 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004904
4905 EVT VT = Op.getValueType();
4906 SDLoc DL(Op);
4907 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4908 SDValue FrameAddr =
4909 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4910 while (Depth--)
4911 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004912 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004913 return FrameAddr;
4914}
4915
4916// FIXME? Maybe this could be a TableGen attribute on some registers and
4917// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004918unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4919 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004920 unsigned Reg = StringSwitch<unsigned>(RegName)
4921 .Case("sp", AArch64::SP)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004922 .Case("x18", AArch64::X18)
4923 .Case("w18", AArch64::W18)
Tim Northover3b0846e2014-05-24 12:50:23 +00004924 .Default(0);
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004925 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4926 !Subtarget->isX18Reserved())
4927 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004928 if (Reg)
4929 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004930 report_fatal_error(Twine("Invalid register name \""
4931 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004932}
4933
4934SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4935 SelectionDAG &DAG) const {
4936 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004937 MachineFrameInfo &MFI = MF.getFrameInfo();
4938 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004939
4940 EVT VT = Op.getValueType();
4941 SDLoc DL(Op);
4942 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4943 if (Depth) {
4944 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004945 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004946 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4947 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004948 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004949 }
4950
4951 // Return LR, which contains the return address. Mark it an implicit live-in.
4952 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4953 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4954}
4955
4956/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4957/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4958SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4959 SelectionDAG &DAG) const {
4960 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4961 EVT VT = Op.getValueType();
4962 unsigned VTBits = VT.getSizeInBits();
4963 SDLoc dl(Op);
4964 SDValue ShOpLo = Op.getOperand(0);
4965 SDValue ShOpHi = Op.getOperand(1);
4966 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004967 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4968
4969 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4970
4971 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004972 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004973 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4974
4975 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4976 // is "undef". We wanted 0, so CSEL it directly.
4977 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4978 ISD::SETEQ, dl, DAG);
4979 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4980 HiBitsForLo =
4981 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4982 HiBitsForLo, CCVal, Cmp);
4983
Tim Northover3b0846e2014-05-24 12:50:23 +00004984 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004985 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004986
Tim Northoverf3be9d52015-12-02 00:33:54 +00004987 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4988 SDValue LoForNormalShift =
4989 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004990
Tim Northoverf3be9d52015-12-02 00:33:54 +00004991 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4992 dl, DAG);
4993 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4994 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4995 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4996 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004997
4998 // AArch64 shifts larger than the register width are wrapped rather than
4999 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005000 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5001 SDValue HiForBigShift =
5002 Opc == ISD::SRA
5003 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5004 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5005 : DAG.getConstant(0, dl, VT);
5006 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5007 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005008
5009 SDValue Ops[2] = { Lo, Hi };
5010 return DAG.getMergeValues(Ops, dl);
5011}
5012
5013/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5014/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5015SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005016 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005017 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5018 EVT VT = Op.getValueType();
5019 unsigned VTBits = VT.getSizeInBits();
5020 SDLoc dl(Op);
5021 SDValue ShOpLo = Op.getOperand(0);
5022 SDValue ShOpHi = Op.getOperand(1);
5023 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005024
5025 assert(Op.getOpcode() == ISD::SHL_PARTS);
5026 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005027 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005028 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5029
5030 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5031 // is "undef". We wanted 0, so CSEL it directly.
5032 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5033 ISD::SETEQ, dl, DAG);
5034 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5035 LoBitsForHi =
5036 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5037 LoBitsForHi, CCVal, Cmp);
5038
Tim Northover3b0846e2014-05-24 12:50:23 +00005039 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005040 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005041 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5042 SDValue HiForNormalShift =
5043 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005044
Tim Northoverf3be9d52015-12-02 00:33:54 +00005045 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005046
Tim Northoverf3be9d52015-12-02 00:33:54 +00005047 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5048 dl, DAG);
5049 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5050 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5051 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005052
5053 // AArch64 shifts of larger than register sizes are wrapped rather than
5054 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005055 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5056 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5057 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5058 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005059
5060 SDValue Ops[2] = { Lo, Hi };
5061 return DAG.getMergeValues(Ops, dl);
5062}
5063
5064bool AArch64TargetLowering::isOffsetFoldingLegal(
5065 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005066 // Offsets are folded in the DAG combine rather than here so that we can
5067 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005068 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005069}
5070
5071bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
5072 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
5073 // FIXME: We should be able to handle f128 as well with a clever lowering.
Sjoerd Meijer5ea465d2018-02-08 08:39:05 +00005074 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
5075 (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005076 DEBUG(dbgs() << "Legal fp imm: materialize 0 using the zero register\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005077 return true;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005078 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005079
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005080 StringRef FPType;
5081 bool IsLegal = false;
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00005082 SmallString<128> ImmStrVal;
5083 Imm.toString(ImmStrVal);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005084
5085 if (VT == MVT::f64) {
5086 FPType = "f64";
5087 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
5088 } else if (VT == MVT::f32) {
5089 FPType = "f32";
5090 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
5091 } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) {
5092 FPType = "f16";
5093 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
5094 }
5095
5096 if (IsLegal) {
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00005097 DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005098 return true;
5099 }
5100
5101 if (!FPType.empty())
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00005102 DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005103 else
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00005104 DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal << ": unsupported fp type\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005105
Tim Northover3b0846e2014-05-24 12:50:23 +00005106 return false;
5107}
5108
5109//===----------------------------------------------------------------------===//
5110// AArch64 Optimization Hooks
5111//===----------------------------------------------------------------------===//
5112
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005113static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5114 SDValue Operand, SelectionDAG &DAG,
5115 int &ExtraSteps) {
5116 EVT VT = Operand.getValueType();
5117 if (ST->hasNEON() &&
5118 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5119 VT == MVT::f32 || VT == MVT::v1f32 ||
5120 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5121 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5122 // For the reciprocal estimates, convergence is quadratic, so the number
5123 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5124 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5125 // the result for float (23 mantissa bits) is 2 and for double (52
5126 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005127 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005128
5129 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5130 }
5131
5132 return SDValue();
5133}
5134
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005135SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5136 SelectionDAG &DAG, int Enabled,
5137 int &ExtraSteps,
5138 bool &UseOneConst,
5139 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005140 if (Enabled == ReciprocalEstimate::Enabled ||
5141 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5142 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5143 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005144 SDLoc DL(Operand);
5145 EVT VT = Operand.getValueType();
5146
5147 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005148 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005149
5150 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5151 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5152 for (int i = ExtraSteps; i > 0; --i) {
5153 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005154 Flags);
5155 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5156 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005157 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005158 if (!Reciprocal) {
5159 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5160 VT);
5161 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5162 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5163
Amara Emersond28f0cd42017-05-01 15:17:51 +00005164 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005165 // Correct the result if the operand is 0.0.
5166 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5167 VT, Eq, Operand, Estimate);
5168 }
5169
5170 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005171 return Estimate;
5172 }
5173
5174 return SDValue();
5175}
5176
5177SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5178 SelectionDAG &DAG, int Enabled,
5179 int &ExtraSteps) const {
5180 if (Enabled == ReciprocalEstimate::Enabled)
5181 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005182 DAG, ExtraSteps)) {
5183 SDLoc DL(Operand);
5184 EVT VT = Operand.getValueType();
5185
5186 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005187 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005188
5189 // Newton reciprocal iteration: E * (2 - X * E)
5190 // AArch64 reciprocal iteration instruction: (2 - M * N)
5191 for (int i = ExtraSteps; i > 0; --i) {
5192 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005193 Estimate, Flags);
5194 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005195 }
5196
5197 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005198 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005199 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005200
5201 return SDValue();
5202}
5203
Tim Northover3b0846e2014-05-24 12:50:23 +00005204//===----------------------------------------------------------------------===//
5205// AArch64 Inline Assembly Support
5206//===----------------------------------------------------------------------===//
5207
5208// Table of Constraints
5209// TODO: This is the current set of constraints supported by ARM for the
5210// compiler, not all of them may make sense, e.g. S may be difficult to support.
5211//
5212// r - A general register
5213// w - An FP/SIMD register of some size in the range v0-v31
5214// x - An FP/SIMD register of some size in the range v0-v15
5215// I - Constant that can be used with an ADD instruction
5216// J - Constant that can be used with a SUB instruction
5217// K - Constant that can be used with a 32-bit logical instruction
5218// L - Constant that can be used with a 64-bit logical instruction
5219// M - Constant that can be used as a 32-bit MOV immediate
5220// N - Constant that can be used as a 64-bit MOV immediate
5221// Q - A memory reference with base register and no offset
5222// S - A symbolic address
5223// Y - Floating point constant zero
5224// Z - Integer constant zero
5225//
5226// Note that general register operands will be output using their 64-bit x
5227// register name, whatever the size of the variable, unless the asm operand
5228// is prefixed by the %w modifier. Floating-point and SIMD register operands
5229// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5230// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005231const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5232 // At this point, we have to lower this constraint to something else, so we
5233 // lower it to an "r" or "w". However, by doing this we will force the result
5234 // to be in register, while the X constraint is much more permissive.
5235 //
5236 // Although we are correct (we are free to emit anything, without
5237 // constraints), we might break use cases that would expect us to be more
5238 // efficient and emit something else.
5239 if (!Subtarget->hasFPARMv8())
5240 return "r";
5241
5242 if (ConstraintVT.isFloatingPoint())
5243 return "w";
5244
5245 if (ConstraintVT.isVector() &&
5246 (ConstraintVT.getSizeInBits() == 64 ||
5247 ConstraintVT.getSizeInBits() == 128))
5248 return "w";
5249
5250 return "r";
5251}
Tim Northover3b0846e2014-05-24 12:50:23 +00005252
5253/// getConstraintType - Given a constraint letter, return the type of
5254/// constraint it is for this target.
5255AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005256AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005257 if (Constraint.size() == 1) {
5258 switch (Constraint[0]) {
5259 default:
5260 break;
5261 case 'z':
5262 return C_Other;
5263 case 'x':
5264 case 'w':
5265 return C_RegisterClass;
5266 // An address with a single base register. Due to the way we
5267 // currently handle addresses it is the same as 'r'.
5268 case 'Q':
5269 return C_Memory;
5270 }
5271 }
5272 return TargetLowering::getConstraintType(Constraint);
5273}
5274
5275/// Examine constraint type and operand type and determine a weight value.
5276/// This object must already have been set up with the operand type
5277/// and the current alternative constraint selected.
5278TargetLowering::ConstraintWeight
5279AArch64TargetLowering::getSingleConstraintMatchWeight(
5280 AsmOperandInfo &info, const char *constraint) const {
5281 ConstraintWeight weight = CW_Invalid;
5282 Value *CallOperandVal = info.CallOperandVal;
5283 // If we don't have a value, we can't do a match,
5284 // but allow it at the lowest weight.
5285 if (!CallOperandVal)
5286 return CW_Default;
5287 Type *type = CallOperandVal->getType();
5288 // Look at the constraint type.
5289 switch (*constraint) {
5290 default:
5291 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5292 break;
5293 case 'x':
5294 case 'w':
5295 if (type->isFloatingPointTy() || type->isVectorTy())
5296 weight = CW_Register;
5297 break;
5298 case 'z':
5299 weight = CW_Constant;
5300 break;
5301 }
5302 return weight;
5303}
5304
5305std::pair<unsigned, const TargetRegisterClass *>
5306AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005307 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005308 if (Constraint.size() == 1) {
5309 switch (Constraint[0]) {
5310 case 'r':
5311 if (VT.getSizeInBits() == 64)
5312 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5313 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5314 case 'w':
Amara Emerson614b44b2016-11-07 15:42:12 +00005315 if (VT.getSizeInBits() == 16)
5316 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005317 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005318 return std::make_pair(0U, &AArch64::FPR32RegClass);
5319 if (VT.getSizeInBits() == 64)
5320 return std::make_pair(0U, &AArch64::FPR64RegClass);
5321 if (VT.getSizeInBits() == 128)
5322 return std::make_pair(0U, &AArch64::FPR128RegClass);
5323 break;
5324 // The instructions that this constraint is designed for can
5325 // only take 128-bit registers so just use that regclass.
5326 case 'x':
5327 if (VT.getSizeInBits() == 128)
5328 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5329 break;
5330 }
5331 }
5332 if (StringRef("{cc}").equals_lower(Constraint))
5333 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5334
5335 // Use the default implementation in TargetLowering to convert the register
5336 // constraint into a member of a register class.
5337 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005338 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005339
5340 // Not found as a standard register?
5341 if (!Res.second) {
5342 unsigned Size = Constraint.size();
5343 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5344 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005345 int RegNo;
5346 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5347 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005348 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005349 // By default we'll emit v0-v31 for this unless there's a modifier where
5350 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005351 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5352 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5353 Res.second = &AArch64::FPR64RegClass;
5354 } else {
5355 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5356 Res.second = &AArch64::FPR128RegClass;
5357 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005358 }
5359 }
5360 }
5361
5362 return Res;
5363}
5364
5365/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5366/// vector. If it is invalid, don't add anything to Ops.
5367void AArch64TargetLowering::LowerAsmOperandForConstraint(
5368 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5369 SelectionDAG &DAG) const {
5370 SDValue Result;
5371
5372 // Currently only support length 1 constraints.
5373 if (Constraint.length() != 1)
5374 return;
5375
5376 char ConstraintLetter = Constraint[0];
5377 switch (ConstraintLetter) {
5378 default:
5379 break;
5380
5381 // This set of constraints deal with valid constants for various instructions.
5382 // Validate and return a target constant for them if we can.
5383 case 'z': {
5384 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005385 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005386 return;
5387
5388 if (Op.getValueType() == MVT::i64)
5389 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5390 else
5391 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5392 break;
5393 }
5394
5395 case 'I':
5396 case 'J':
5397 case 'K':
5398 case 'L':
5399 case 'M':
5400 case 'N':
5401 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5402 if (!C)
5403 return;
5404
5405 // Grab the value and do some validation.
5406 uint64_t CVal = C->getZExtValue();
5407 switch (ConstraintLetter) {
5408 // The I constraint applies only to simple ADD or SUB immediate operands:
5409 // i.e. 0 to 4095 with optional shift by 12
5410 // The J constraint applies only to ADD or SUB immediates that would be
5411 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5412 // instruction [or vice versa], in other words -1 to -4095 with optional
5413 // left shift by 12.
5414 case 'I':
5415 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5416 break;
5417 return;
5418 case 'J': {
5419 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005420 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5421 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005422 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005423 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005424 return;
5425 }
5426 // The K and L constraints apply *only* to logical immediates, including
5427 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5428 // been removed and MOV should be used). So these constraints have to
5429 // distinguish between bit patterns that are valid 32-bit or 64-bit
5430 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5431 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5432 // versa.
5433 case 'K':
5434 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5435 break;
5436 return;
5437 case 'L':
5438 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5439 break;
5440 return;
5441 // The M and N constraints are a superset of K and L respectively, for use
5442 // with the MOV (immediate) alias. As well as the logical immediates they
5443 // also match 32 or 64-bit immediates that can be loaded either using a
5444 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5445 // (M) or 64-bit 0x1234000000000000 (N) etc.
5446 // As a note some of this code is liberally stolen from the asm parser.
5447 case 'M': {
5448 if (!isUInt<32>(CVal))
5449 return;
5450 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5451 break;
5452 if ((CVal & 0xFFFF) == CVal)
5453 break;
5454 if ((CVal & 0xFFFF0000ULL) == CVal)
5455 break;
5456 uint64_t NCVal = ~(uint32_t)CVal;
5457 if ((NCVal & 0xFFFFULL) == NCVal)
5458 break;
5459 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5460 break;
5461 return;
5462 }
5463 case 'N': {
5464 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5465 break;
5466 if ((CVal & 0xFFFFULL) == CVal)
5467 break;
5468 if ((CVal & 0xFFFF0000ULL) == CVal)
5469 break;
5470 if ((CVal & 0xFFFF00000000ULL) == CVal)
5471 break;
5472 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5473 break;
5474 uint64_t NCVal = ~CVal;
5475 if ((NCVal & 0xFFFFULL) == NCVal)
5476 break;
5477 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5478 break;
5479 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5480 break;
5481 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5482 break;
5483 return;
5484 }
5485 default:
5486 return;
5487 }
5488
5489 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005490 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005491 break;
5492 }
5493
5494 if (Result.getNode()) {
5495 Ops.push_back(Result);
5496 return;
5497 }
5498
5499 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5500}
5501
5502//===----------------------------------------------------------------------===//
5503// AArch64 Advanced SIMD Support
5504//===----------------------------------------------------------------------===//
5505
5506/// WidenVector - Given a value in the V64 register class, produce the
5507/// equivalent value in the V128 register class.
5508static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5509 EVT VT = V64Reg.getValueType();
5510 unsigned NarrowSize = VT.getVectorNumElements();
5511 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5512 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5513 SDLoc DL(V64Reg);
5514
5515 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005516 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005517}
5518
5519/// getExtFactor - Determine the adjustment factor for the position when
5520/// generating an "extract from vector registers" instruction.
5521static unsigned getExtFactor(SDValue &V) {
5522 EVT EltType = V.getValueType().getVectorElementType();
5523 return EltType.getSizeInBits() / 8;
5524}
5525
5526/// NarrowVector - Given a value in the V128 register class, produce the
5527/// equivalent value in the V64 register class.
5528static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5529 EVT VT = V128Reg.getValueType();
5530 unsigned WideSize = VT.getVectorNumElements();
5531 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5532 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5533 SDLoc DL(V128Reg);
5534
5535 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5536}
5537
5538// Gather data to see if the operation can be modelled as a
5539// shuffle in combination with VEXTs.
5540SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5541 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005542 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005543 DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005544 SDLoc dl(Op);
5545 EVT VT = Op.getValueType();
5546 unsigned NumElts = VT.getVectorNumElements();
5547
Tim Northover7324e842014-07-24 15:39:55 +00005548 struct ShuffleSourceInfo {
5549 SDValue Vec;
5550 unsigned MinElt;
5551 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005552
Tim Northover7324e842014-07-24 15:39:55 +00005553 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5554 // be compatible with the shuffle we intend to construct. As a result
5555 // ShuffleVec will be some sliding window into the original Vec.
5556 SDValue ShuffleVec;
5557
5558 // Code should guarantee that element i in Vec starts at element "WindowBase
5559 // + i * WindowScale in ShuffleVec".
5560 int WindowBase;
5561 int WindowScale;
5562
Tim Northover7324e842014-07-24 15:39:55 +00005563 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005564 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5565 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5566
5567 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005568 };
5569
5570 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5571 // node.
5572 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005573 for (unsigned i = 0; i < NumElts; ++i) {
5574 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005575 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005576 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005577 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5578 !isa<ConstantSDNode>(V.getOperand(1))) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005579 DEBUG(dbgs() << "Reshuffle failed: "
5580 "a shuffle can only come from building a vector from "
5581 "various elements of other vectors, provided their "
5582 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005583 return SDValue();
5584 }
5585
Tim Northover7324e842014-07-24 15:39:55 +00005586 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005587 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005588 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005589 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005590 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005591
Tim Northover7324e842014-07-24 15:39:55 +00005592 // Update the minimum and maximum lane number seen.
5593 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5594 Source->MinElt = std::min(Source->MinElt, EltNo);
5595 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005596 }
5597
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005598 if (Sources.size() > 2) {
5599 DEBUG(dbgs() << "Reshuffle failed: currently only do something sane when at "
5600 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005601 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005602 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005603
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005604 // Find out the smallest element size among result and two sources, and use
5605 // it as element size to build the shuffle_vector.
5606 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005607 for (auto &Source : Sources) {
5608 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005609 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5610 SmallestEltTy = SrcEltTy;
5611 }
5612 }
5613 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005614 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005615 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5616 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005617
Tim Northover7324e842014-07-24 15:39:55 +00005618 // If the source vector is too wide or too narrow, we may nevertheless be able
5619 // to construct a compatible shuffle either by concatenating it with UNDEF or
5620 // extracting a suitable range of elements.
5621 for (auto &Src : Sources) {
5622 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005623
Tim Northover7324e842014-07-24 15:39:55 +00005624 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005625 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005626
5627 // This stage of the search produces a source with the same element type as
5628 // the original, but with a total width matching the BUILD_VECTOR output.
5629 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005630 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5631 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005632
5633 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5634 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005635 // We can pad out the smaller vector for free, so if it's part of a
5636 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005637 Src.ShuffleVec =
5638 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5639 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005640 continue;
5641 }
5642
Tim Northover7324e842014-07-24 15:39:55 +00005643 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005644
James Molloyf497d552014-10-17 17:06:31 +00005645 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005646 DEBUG(dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005647 return SDValue();
5648 }
5649
James Molloyf497d552014-10-17 17:06:31 +00005650 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005651 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005652 Src.ShuffleVec =
5653 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005654 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005655 Src.WindowBase = -NumSrcElts;
5656 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005657 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005658 Src.ShuffleVec =
5659 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005660 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005661 } else {
5662 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005663 SDValue VEXTSrc1 =
5664 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005665 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005666 SDValue VEXTSrc2 =
5667 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005668 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005669 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5670
5671 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005672 VEXTSrc2,
5673 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005674 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005675 }
5676 }
5677
Tim Northover7324e842014-07-24 15:39:55 +00005678 // Another possible incompatibility occurs from the vector element types. We
5679 // can fix this by bitcasting the source vectors to the same type we intend
5680 // for the shuffle.
5681 for (auto &Src : Sources) {
5682 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5683 if (SrcEltTy == SmallestEltTy)
5684 continue;
5685 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5686 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5687 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5688 Src.WindowBase *= Src.WindowScale;
5689 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005690
Tim Northover7324e842014-07-24 15:39:55 +00005691 // Final sanity check before we try to actually produce a shuffle.
5692 DEBUG(
5693 for (auto Src : Sources)
5694 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5695 );
5696
5697 // The stars all align, our next step is to produce the mask for the shuffle.
5698 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005699 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005700 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005701 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005702 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005703 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005704
David Majnemer0d955d02016-08-11 22:21:41 +00005705 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005706 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5707
5708 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5709 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5710 // segment.
5711 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005712 int BitsDefined =
5713 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005714 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5715
5716 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5717 // starting at the appropriate offset.
5718 int *LaneMask = &Mask[i * ResMultiplier];
5719
5720 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5721 ExtractBase += NumElts * (Src - Sources.begin());
5722 for (int j = 0; j < LanesDefined; ++j)
5723 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005724 }
5725
5726 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005727 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
5728 DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00005729 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005730 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005731
Tim Northover7324e842014-07-24 15:39:55 +00005732 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5733 for (unsigned i = 0; i < Sources.size(); ++i)
5734 ShuffleOps[i] = Sources[i].ShuffleVec;
5735
5736 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005737 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005738 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5739
5740 DEBUG(
5741 dbgs() << "Reshuffle, creating node: ";
5742 Shuffle.dump();
5743 dbgs() << "Reshuffle, creating node: ";
5744 V.dump();
5745 );
5746
5747 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00005748}
5749
5750// check if an EXT instruction can handle the shuffle mask when the
5751// vector sources of the shuffle are the same.
5752static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5753 unsigned NumElts = VT.getVectorNumElements();
5754
5755 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5756 if (M[0] < 0)
5757 return false;
5758
5759 Imm = M[0];
5760
5761 // If this is a VEXT shuffle, the immediate value is the index of the first
5762 // element. The other shuffle indices must be the successive elements after
5763 // the first one.
5764 unsigned ExpectedElt = Imm;
5765 for (unsigned i = 1; i < NumElts; ++i) {
5766 // Increment the expected index. If it wraps around, just follow it
5767 // back to index zero and keep going.
5768 ++ExpectedElt;
5769 if (ExpectedElt == NumElts)
5770 ExpectedElt = 0;
5771
5772 if (M[i] < 0)
5773 continue; // ignore UNDEF indices
5774 if (ExpectedElt != static_cast<unsigned>(M[i]))
5775 return false;
5776 }
5777
5778 return true;
5779}
5780
5781// check if an EXT instruction can handle the shuffle mask when the
5782// vector sources of the shuffle are different.
5783static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5784 unsigned &Imm) {
5785 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005786 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005787
5788 // Benefit form APInt to handle overflow when calculating expected element.
5789 unsigned NumElts = VT.getVectorNumElements();
5790 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5791 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5792 // The following shuffle indices must be the successive elements after the
5793 // first real element.
5794 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5795 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5796 if (FirstWrongElt != M.end())
5797 return false;
5798
5799 // The index of an EXT is the first element if it is not UNDEF.
5800 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005801 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005802 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5803 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5804 // ExpectedElt is the last mask index plus 1.
5805 Imm = ExpectedElt.getZExtValue();
5806
5807 // There are two difference cases requiring to reverse input vectors.
5808 // For example, for vector <4 x i32> we have the following cases,
5809 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5810 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5811 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5812 // to reverse two input vectors.
5813 if (Imm < NumElts)
5814 ReverseEXT = true;
5815 else
5816 Imm -= NumElts;
5817
5818 return true;
5819}
5820
5821/// isREVMask - Check if a vector shuffle corresponds to a REV
5822/// instruction with the specified blocksize. (The order of the elements
5823/// within each block of the vector is reversed.)
5824static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5825 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5826 "Only possible block sizes for REV are: 16, 32, 64");
5827
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005828 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00005829 if (EltSz == 64)
5830 return false;
5831
5832 unsigned NumElts = VT.getVectorNumElements();
5833 unsigned BlockElts = M[0] + 1;
5834 // If the first shuffle index is UNDEF, be optimistic.
5835 if (M[0] < 0)
5836 BlockElts = BlockSize / EltSz;
5837
5838 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5839 return false;
5840
5841 for (unsigned i = 0; i < NumElts; ++i) {
5842 if (M[i] < 0)
5843 continue; // ignore UNDEF indices
5844 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5845 return false;
5846 }
5847
5848 return true;
5849}
5850
5851static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5852 unsigned NumElts = VT.getVectorNumElements();
5853 WhichResult = (M[0] == 0 ? 0 : 1);
5854 unsigned Idx = WhichResult * NumElts / 2;
5855 for (unsigned i = 0; i != NumElts; i += 2) {
5856 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5857 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5858 return false;
5859 Idx += 1;
5860 }
5861
5862 return true;
5863}
5864
5865static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5866 unsigned NumElts = VT.getVectorNumElements();
5867 WhichResult = (M[0] == 0 ? 0 : 1);
5868 for (unsigned i = 0; i != NumElts; ++i) {
5869 if (M[i] < 0)
5870 continue; // ignore UNDEF indices
5871 if ((unsigned)M[i] != 2 * i + WhichResult)
5872 return false;
5873 }
5874
5875 return true;
5876}
5877
5878static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5879 unsigned NumElts = VT.getVectorNumElements();
5880 WhichResult = (M[0] == 0 ? 0 : 1);
5881 for (unsigned i = 0; i < NumElts; i += 2) {
5882 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5883 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5884 return false;
5885 }
5886 return true;
5887}
5888
5889/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5890/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5891/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5892static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5893 unsigned NumElts = VT.getVectorNumElements();
5894 WhichResult = (M[0] == 0 ? 0 : 1);
5895 unsigned Idx = WhichResult * NumElts / 2;
5896 for (unsigned i = 0; i != NumElts; i += 2) {
5897 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5898 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5899 return false;
5900 Idx += 1;
5901 }
5902
5903 return true;
5904}
5905
5906/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5907/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5908/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5909static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5910 unsigned Half = VT.getVectorNumElements() / 2;
5911 WhichResult = (M[0] == 0 ? 0 : 1);
5912 for (unsigned j = 0; j != 2; ++j) {
5913 unsigned Idx = WhichResult;
5914 for (unsigned i = 0; i != Half; ++i) {
5915 int MIdx = M[i + j * Half];
5916 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5917 return false;
5918 Idx += 2;
5919 }
5920 }
5921
5922 return true;
5923}
5924
5925/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5926/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5927/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5928static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5929 unsigned NumElts = VT.getVectorNumElements();
5930 WhichResult = (M[0] == 0 ? 0 : 1);
5931 for (unsigned i = 0; i < NumElts; i += 2) {
5932 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5933 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5934 return false;
5935 }
5936 return true;
5937}
5938
5939static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5940 bool &DstIsLeft, int &Anomaly) {
5941 if (M.size() != static_cast<size_t>(NumInputElements))
5942 return false;
5943
5944 int NumLHSMatch = 0, NumRHSMatch = 0;
5945 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5946
5947 for (int i = 0; i < NumInputElements; ++i) {
5948 if (M[i] == -1) {
5949 ++NumLHSMatch;
5950 ++NumRHSMatch;
5951 continue;
5952 }
5953
5954 if (M[i] == i)
5955 ++NumLHSMatch;
5956 else
5957 LastLHSMismatch = i;
5958
5959 if (M[i] == i + NumInputElements)
5960 ++NumRHSMatch;
5961 else
5962 LastRHSMismatch = i;
5963 }
5964
5965 if (NumLHSMatch == NumInputElements - 1) {
5966 DstIsLeft = true;
5967 Anomaly = LastLHSMismatch;
5968 return true;
5969 } else if (NumRHSMatch == NumInputElements - 1) {
5970 DstIsLeft = false;
5971 Anomaly = LastRHSMismatch;
5972 return true;
5973 }
5974
5975 return false;
5976}
5977
5978static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5979 if (VT.getSizeInBits() != 128)
5980 return false;
5981
5982 unsigned NumElts = VT.getVectorNumElements();
5983
5984 for (int I = 0, E = NumElts / 2; I != E; I++) {
5985 if (Mask[I] != I)
5986 return false;
5987 }
5988
5989 int Offset = NumElts / 2;
5990 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5991 if (Mask[I] != I + SplitLHS * Offset)
5992 return false;
5993 }
5994
5995 return true;
5996}
5997
5998static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5999 SDLoc DL(Op);
6000 EVT VT = Op.getValueType();
6001 SDValue V0 = Op.getOperand(0);
6002 SDValue V1 = Op.getOperand(1);
6003 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6004
6005 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6006 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6007 return SDValue();
6008
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006009 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006010
6011 if (!isConcatMask(Mask, VT, SplitV0))
6012 return SDValue();
6013
6014 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6015 VT.getVectorNumElements() / 2);
6016 if (SplitV0) {
6017 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006018 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006019 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006020 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006021 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006022 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006023 }
6024 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6025}
6026
6027/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6028/// the specified operations to build the shuffle.
6029static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6030 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006031 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006032 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6033 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6034 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6035
6036 enum {
6037 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6038 OP_VREV,
6039 OP_VDUP0,
6040 OP_VDUP1,
6041 OP_VDUP2,
6042 OP_VDUP3,
6043 OP_VEXT1,
6044 OP_VEXT2,
6045 OP_VEXT3,
6046 OP_VUZPL, // VUZP, left result
6047 OP_VUZPR, // VUZP, right result
6048 OP_VZIPL, // VZIP, left result
6049 OP_VZIPR, // VZIP, right result
6050 OP_VTRNL, // VTRN, left result
6051 OP_VTRNR // VTRN, right result
6052 };
6053
6054 if (OpNum == OP_COPY) {
6055 if (LHSID == (1 * 9 + 2) * 9 + 3)
6056 return LHS;
6057 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6058 return RHS;
6059 }
6060
6061 SDValue OpLHS, OpRHS;
6062 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6063 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6064 EVT VT = OpLHS.getValueType();
6065
6066 switch (OpNum) {
6067 default:
6068 llvm_unreachable("Unknown shuffle opcode!");
6069 case OP_VREV:
6070 // VREV divides the vector in half and swaps within the half.
6071 if (VT.getVectorElementType() == MVT::i32 ||
6072 VT.getVectorElementType() == MVT::f32)
6073 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6074 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006075 if (VT.getVectorElementType() == MVT::i16 ||
6076 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006077 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6078 // vrev <4 x i8> -> REV16
6079 assert(VT.getVectorElementType() == MVT::i8);
6080 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6081 case OP_VDUP0:
6082 case OP_VDUP1:
6083 case OP_VDUP2:
6084 case OP_VDUP3: {
6085 EVT EltTy = VT.getVectorElementType();
6086 unsigned Opcode;
6087 if (EltTy == MVT::i8)
6088 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006089 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006090 Opcode = AArch64ISD::DUPLANE16;
6091 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6092 Opcode = AArch64ISD::DUPLANE32;
6093 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6094 Opcode = AArch64ISD::DUPLANE64;
6095 else
6096 llvm_unreachable("Invalid vector element type?");
6097
6098 if (VT.getSizeInBits() == 64)
6099 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006100 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006101 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6102 }
6103 case OP_VEXT1:
6104 case OP_VEXT2:
6105 case OP_VEXT3: {
6106 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6107 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006108 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006109 }
6110 case OP_VUZPL:
6111 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6112 OpRHS);
6113 case OP_VUZPR:
6114 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6115 OpRHS);
6116 case OP_VZIPL:
6117 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6118 OpRHS);
6119 case OP_VZIPR:
6120 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6121 OpRHS);
6122 case OP_VTRNL:
6123 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6124 OpRHS);
6125 case OP_VTRNR:
6126 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6127 OpRHS);
6128 }
6129}
6130
6131static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6132 SelectionDAG &DAG) {
6133 // Check to see if we can use the TBL instruction.
6134 SDValue V1 = Op.getOperand(0);
6135 SDValue V2 = Op.getOperand(1);
6136 SDLoc DL(Op);
6137
6138 EVT EltVT = Op.getValueType().getVectorElementType();
6139 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6140
6141 SmallVector<SDValue, 8> TBLMask;
6142 for (int Val : ShuffleMask) {
6143 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6144 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006145 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006146 }
6147 }
6148
6149 MVT IndexVT = MVT::v8i8;
6150 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006151 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006152 IndexVT = MVT::v16i8;
6153 IndexLen = 16;
6154 }
6155
6156 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6157 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6158
6159 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006160 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006161 if (IndexLen == 8)
6162 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6163 Shuffle = DAG.getNode(
6164 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006165 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006166 DAG.getBuildVector(IndexVT, DL,
6167 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006168 } else {
6169 if (IndexLen == 8) {
6170 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6171 Shuffle = DAG.getNode(
6172 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006173 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006174 DAG.getBuildVector(IndexVT, DL,
6175 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006176 } else {
6177 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6178 // cannot currently represent the register constraints on the input
6179 // table registers.
6180 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006181 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6182 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006183 Shuffle = DAG.getNode(
6184 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006185 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6186 V2Cst, DAG.getBuildVector(IndexVT, DL,
6187 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006188 }
6189 }
6190 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6191}
6192
6193static unsigned getDUPLANEOp(EVT EltType) {
6194 if (EltType == MVT::i8)
6195 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006196 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006197 return AArch64ISD::DUPLANE16;
6198 if (EltType == MVT::i32 || EltType == MVT::f32)
6199 return AArch64ISD::DUPLANE32;
6200 if (EltType == MVT::i64 || EltType == MVT::f64)
6201 return AArch64ISD::DUPLANE64;
6202
6203 llvm_unreachable("Invalid vector element type?");
6204}
6205
6206SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6207 SelectionDAG &DAG) const {
6208 SDLoc dl(Op);
6209 EVT VT = Op.getValueType();
6210
6211 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6212
6213 // Convert shuffles that are directly supported on NEON to target-specific
6214 // DAG nodes, instead of keeping them as shuffles and matching them again
6215 // during code selection. This is more efficient and avoids the possibility
6216 // of inconsistencies between legalization and selection.
6217 ArrayRef<int> ShuffleMask = SVN->getMask();
6218
6219 SDValue V1 = Op.getOperand(0);
6220 SDValue V2 = Op.getOperand(1);
6221
Craig Topperbc56e3b2016-06-30 04:38:51 +00006222 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006223 int Lane = SVN->getSplatIndex();
6224 // If this is undef splat, generate it via "just" vdup, if possible.
6225 if (Lane == -1)
6226 Lane = 0;
6227
6228 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6229 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6230 V1.getOperand(0));
6231 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6232 // constant. If so, we can just reference the lane's definition directly.
6233 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6234 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6235 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6236
6237 // Otherwise, duplicate from the lane of the input vector.
6238 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6239
6240 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6241 // to make a vector of the same size as this SHUFFLE. We can ignore the
6242 // extract entirely, and canonicalise the concat using WidenVector.
6243 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6244 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6245 V1 = V1.getOperand(0);
6246 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6247 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6248 Lane -= Idx * VT.getVectorNumElements() / 2;
6249 V1 = WidenVector(V1.getOperand(Idx), DAG);
6250 } else if (VT.getSizeInBits() == 64)
6251 V1 = WidenVector(V1, DAG);
6252
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006253 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006254 }
6255
6256 if (isREVMask(ShuffleMask, VT, 64))
6257 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6258 if (isREVMask(ShuffleMask, VT, 32))
6259 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6260 if (isREVMask(ShuffleMask, VT, 16))
6261 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6262
6263 bool ReverseEXT = false;
6264 unsigned Imm;
6265 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6266 if (ReverseEXT)
6267 std::swap(V1, V2);
6268 Imm *= getExtFactor(V1);
6269 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006270 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006271 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006272 Imm *= getExtFactor(V1);
6273 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006274 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006275 }
6276
6277 unsigned WhichResult;
6278 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6279 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6280 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6281 }
6282 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6283 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6284 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6285 }
6286 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6287 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6288 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6289 }
6290
6291 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6292 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6293 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6294 }
6295 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6296 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6297 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6298 }
6299 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6300 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6301 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6302 }
6303
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006304 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006305 return Concat;
6306
6307 bool DstIsLeft;
6308 int Anomaly;
6309 int NumInputElements = V1.getValueType().getVectorNumElements();
6310 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6311 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006312 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006313
6314 SDValue SrcVec = V1;
6315 int SrcLane = ShuffleMask[Anomaly];
6316 if (SrcLane >= NumInputElements) {
6317 SrcVec = V2;
6318 SrcLane -= VT.getVectorNumElements();
6319 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006320 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006321
6322 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006323
6324 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006325 ScalarVT = MVT::i32;
6326
6327 return DAG.getNode(
6328 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6329 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6330 DstLaneV);
6331 }
6332
6333 // If the shuffle is not directly supported and it has 4 elements, use
6334 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6335 unsigned NumElts = VT.getVectorNumElements();
6336 if (NumElts == 4) {
6337 unsigned PFIndexes[4];
6338 for (unsigned i = 0; i != 4; ++i) {
6339 if (ShuffleMask[i] < 0)
6340 PFIndexes[i] = 8;
6341 else
6342 PFIndexes[i] = ShuffleMask[i];
6343 }
6344
6345 // Compute the index in the perfect shuffle table.
6346 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6347 PFIndexes[2] * 9 + PFIndexes[3];
6348 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6349 unsigned Cost = (PFEntry >> 30);
6350
6351 if (Cost <= 4)
6352 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6353 }
6354
6355 return GenerateTBL(Op, ShuffleMask, DAG);
6356}
6357
6358static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6359 APInt &UndefBits) {
6360 EVT VT = BVN->getValueType(0);
6361 APInt SplatBits, SplatUndef;
6362 unsigned SplatBitSize;
6363 bool HasAnyUndefs;
6364 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6365 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6366
6367 for (unsigned i = 0; i < NumSplats; ++i) {
6368 CnstBits <<= SplatBitSize;
6369 UndefBits <<= SplatBitSize;
6370 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6371 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6372 }
6373
6374 return true;
6375 }
6376
6377 return false;
6378}
6379
Evandro Menezes72f39832018-02-20 20:31:45 +00006380// Try 64-bit splatted SIMD immediate.
6381static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6382 const APInt &Bits) {
6383 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6384 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6385 EVT VT = Op.getValueType();
6386 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6387
6388 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6389 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6390
6391 SDLoc dl(Op);
6392 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6393 DAG.getConstant(Value, dl, MVT::i32));
6394 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6395 }
6396 }
6397
6398 return SDValue();
6399}
6400
6401// Try 32-bit splatted SIMD immediate.
6402static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6403 const APInt &Bits,
6404 const SDValue *LHS = nullptr) {
6405 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6406 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6407 EVT VT = Op.getValueType();
6408 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6409 bool isAdvSIMDModImm = false;
6410 uint64_t Shift;
6411
6412 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6413 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6414 Shift = 0;
6415 }
6416 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6417 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6418 Shift = 8;
6419 }
6420 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6421 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6422 Shift = 16;
6423 }
6424 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6425 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6426 Shift = 24;
6427 }
6428
6429 if (isAdvSIMDModImm) {
6430 SDLoc dl(Op);
6431 SDValue Mov;
6432
6433 if (LHS)
6434 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6435 DAG.getConstant(Value, dl, MVT::i32),
6436 DAG.getConstant(Shift, dl, MVT::i32));
6437 else
6438 Mov = DAG.getNode(NewOp, dl, MovTy,
6439 DAG.getConstant(Value, dl, MVT::i32),
6440 DAG.getConstant(Shift, dl, MVT::i32));
6441
6442 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6443 }
6444 }
6445
6446 return SDValue();
6447}
6448
6449// Try 16-bit splatted SIMD immediate.
6450static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6451 const APInt &Bits,
6452 const SDValue *LHS = nullptr) {
6453 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6454 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6455 EVT VT = Op.getValueType();
6456 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6457 bool isAdvSIMDModImm = false;
6458 uint64_t Shift;
6459
6460 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6461 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6462 Shift = 0;
6463 }
6464 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6465 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6466 Shift = 8;
6467 }
6468
6469 if (isAdvSIMDModImm) {
6470 SDLoc dl(Op);
6471 SDValue Mov;
6472
6473 if (LHS)
6474 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006475 DAG.getConstant(Value, dl, MVT::i32),
6476 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006477 else
6478 Mov = DAG.getNode(NewOp, dl, MovTy,
6479 DAG.getConstant(Value, dl, MVT::i32),
6480 DAG.getConstant(Shift, dl, MVT::i32));
6481
6482 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6483 }
6484 }
6485
6486 return SDValue();
6487}
6488
6489// Try 32-bit splatted SIMD immediate with shifted ones.
6490static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6491 SelectionDAG &DAG, const APInt &Bits) {
6492 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6493 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6494 EVT VT = Op.getValueType();
6495 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6496 bool isAdvSIMDModImm = false;
6497 uint64_t Shift;
6498
6499 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6500 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6501 Shift = 264;
6502 }
6503 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6504 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6505 Shift = 272;
6506 }
6507
6508 if (isAdvSIMDModImm) {
6509 SDLoc dl(Op);
6510 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6511 DAG.getConstant(Value, dl, MVT::i32),
6512 DAG.getConstant(Shift, dl, MVT::i32));
6513 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6514 }
6515 }
6516
6517 return SDValue();
6518}
6519
6520// Try 8-bit splatted SIMD immediate.
6521static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6522 const APInt &Bits) {
6523 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6524 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6525 EVT VT = Op.getValueType();
6526 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6527
6528 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6529 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6530
6531 SDLoc dl(Op);
6532 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6533 DAG.getConstant(Value, dl, MVT::i32));
6534 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6535 }
6536 }
6537
6538 return SDValue();
6539}
6540
6541// Try FP splatted SIMD immediate.
6542static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6543 const APInt &Bits) {
6544 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6545 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6546 EVT VT = Op.getValueType();
6547 bool isWide = (VT.getSizeInBits() == 128);
6548 MVT MovTy;
6549 bool isAdvSIMDModImm = false;
6550
6551 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6552 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6553 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6554 }
6555 else if (isWide &&
6556 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6557 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6558 MovTy = MVT::v2f64;
6559 }
6560
6561 if (isAdvSIMDModImm) {
6562 SDLoc dl(Op);
6563 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6564 DAG.getConstant(Value, dl, MVT::i32));
6565 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6566 }
6567 }
6568
6569 return SDValue();
6570}
6571
Tim Northover3b0846e2014-05-24 12:50:23 +00006572SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6573 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006574 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006575 EVT VT = Op.getValueType();
6576
Evandro Menezes72f39832018-02-20 20:31:45 +00006577 BuildVectorSDNode *BVN =
6578 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6579 if (!BVN) {
6580 // AND commutes, so try swapping the operands.
6581 LHS = Op.getOperand(1);
6582 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6583 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006584 if (!BVN)
6585 return Op;
6586
Evandro Menezes72f39832018-02-20 20:31:45 +00006587 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006588 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006589 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6590 SDValue NewOp;
6591
Tim Northover3b0846e2014-05-24 12:50:23 +00006592 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006593 DefBits = ~DefBits;
6594 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6595 DefBits, &LHS)) ||
6596 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6597 DefBits, &LHS)))
6598 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006599
6600 UndefBits = ~UndefBits;
6601 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6602 UndefBits, &LHS)) ||
6603 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6604 UndefBits, &LHS)))
6605 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006606 }
6607
Evandro Menezes72f39832018-02-20 20:31:45 +00006608 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006609 return Op;
6610}
6611
6612// Specialized code to quickly find if PotentialBVec is a BuildVector that
6613// consists of only the same constant int value, returned in reference arg
6614// ConstVal
6615static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6616 uint64_t &ConstVal) {
6617 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6618 if (!Bvec)
6619 return false;
6620 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6621 if (!FirstElt)
6622 return false;
6623 EVT VT = Bvec->getValueType(0);
6624 unsigned NumElts = VT.getVectorNumElements();
6625 for (unsigned i = 1; i < NumElts; ++i)
6626 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6627 return false;
6628 ConstVal = FirstElt->getZExtValue();
6629 return true;
6630}
6631
6632static unsigned getIntrinsicID(const SDNode *N) {
6633 unsigned Opcode = N->getOpcode();
6634 switch (Opcode) {
6635 default:
6636 return Intrinsic::not_intrinsic;
6637 case ISD::INTRINSIC_WO_CHAIN: {
6638 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6639 if (IID < Intrinsic::num_intrinsics)
6640 return IID;
6641 return Intrinsic::not_intrinsic;
6642 }
6643 }
6644}
6645
6646// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6647// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6648// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6649// Also, logical shift right -> sri, with the same structure.
6650static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6651 EVT VT = N->getValueType(0);
6652
6653 if (!VT.isVector())
6654 return SDValue();
6655
6656 SDLoc DL(N);
6657
6658 // Is the first op an AND?
6659 const SDValue And = N->getOperand(0);
6660 if (And.getOpcode() != ISD::AND)
6661 return SDValue();
6662
6663 // Is the second op an shl or lshr?
6664 SDValue Shift = N->getOperand(1);
6665 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6666 // or AArch64ISD::VLSHR vector, #shift
6667 unsigned ShiftOpc = Shift.getOpcode();
6668 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6669 return SDValue();
6670 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6671
6672 // Is the shift amount constant?
6673 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6674 if (!C2node)
6675 return SDValue();
6676
6677 // Is the and mask vector all constant?
6678 uint64_t C1;
6679 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6680 return SDValue();
6681
6682 // Is C1 == ~C2, taking into account how much one can shift elements of a
6683 // particular size?
6684 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006685 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006686 if (C2 > ElemSizeInBits)
6687 return SDValue();
6688 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6689 if ((C1 & ElemMask) != (~C2 & ElemMask))
6690 return SDValue();
6691
6692 SDValue X = And.getOperand(0);
6693 SDValue Y = Shift.getOperand(0);
6694
6695 unsigned Intrin =
6696 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6697 SDValue ResultSLI =
6698 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006699 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6700 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006701
6702 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6703 DEBUG(N->dump(&DAG));
6704 DEBUG(dbgs() << "into: \n");
6705 DEBUG(ResultSLI->dump(&DAG));
6706
6707 ++NumShiftInserts;
6708 return ResultSLI;
6709}
6710
6711SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6712 SelectionDAG &DAG) const {
6713 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6714 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006715 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006716 return Res;
6717 }
6718
Tim Northover3b0846e2014-05-24 12:50:23 +00006719 EVT VT = Op.getValueType();
6720
Evandro Menezescd855f72018-03-05 17:02:47 +00006721 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006722 BuildVectorSDNode *BVN =
6723 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006724 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00006725 // OR commutes, so try swapping the operands.
6726 LHS = Op.getOperand(1);
6727 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006728 }
6729 if (!BVN)
6730 return Op;
6731
Evandro Menezes72f39832018-02-20 20:31:45 +00006732 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006733 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006734 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6735 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006736
Evandro Menezes72f39832018-02-20 20:31:45 +00006737 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
6738 DefBits, &LHS)) ||
6739 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
6740 DefBits, &LHS)))
6741 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006742
6743 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
6744 UndefBits, &LHS)) ||
6745 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
6746 UndefBits, &LHS)))
6747 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006748 }
6749
Evandro Menezes72f39832018-02-20 20:31:45 +00006750 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00006751 return Op;
6752}
6753
Kevin Qin4473c192014-07-07 02:45:40 +00006754// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6755// be truncated to fit element width.
6756static SDValue NormalizeBuildVector(SDValue Op,
6757 SelectionDAG &DAG) {
6758 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006759 SDLoc dl(Op);
6760 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006761 EVT EltTy= VT.getVectorElementType();
6762
6763 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6764 return Op;
6765
6766 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006767 for (SDValue Lane : Op->ops()) {
6768 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006769 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006770 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006771 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006772 }
6773 Ops.push_back(Lane);
6774 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006775 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006776}
6777
Evandro Menezescd855f72018-03-05 17:02:47 +00006778static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00006779 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00006780
Evandro Menezes72f39832018-02-20 20:31:45 +00006781 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006782 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00006783 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00006784 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00006785 SDValue NewOp;
6786 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
6787 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6788 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
6789 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6790 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
6791 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
6792 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006793
Evandro Menezes72f39832018-02-20 20:31:45 +00006794 DefBits = ~DefBits;
6795 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
6796 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
6797 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
6798 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006799
Evandro Menezes72f39832018-02-20 20:31:45 +00006800 DefBits = UndefBits;
6801 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
6802 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6803 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
6804 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6805 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
6806 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
6807 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006808
Evandro Menezes72f39832018-02-20 20:31:45 +00006809 DefBits = ~UndefBits;
6810 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
6811 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
6812 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
6813 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006814 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006815
Evandro Menezescd855f72018-03-05 17:02:47 +00006816 return SDValue();
6817}
6818
6819SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6820 SelectionDAG &DAG) const {
6821 EVT VT = Op.getValueType();
6822
6823 // Try to build a simple constant vector.
6824 Op = NormalizeBuildVector(Op, DAG);
6825 if (VT.isInteger()) {
6826 // Certain vector constants, used to express things like logical NOT and
6827 // arithmetic NEG, are passed through unmodified. This allows special
6828 // patterns for these operations to match, which will lower these constants
6829 // to whatever is proven necessary.
6830 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6831 if (BVN->isConstant())
6832 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
6833 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
6834 APInt Val(BitSize,
6835 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
6836 if (Val.isNullValue() || Val.isAllOnesValue())
6837 return Op;
6838 }
6839 }
6840
6841 if (SDValue V = ConstantBuildVector(Op, DAG))
6842 return V;
6843
Tim Northover3b0846e2014-05-24 12:50:23 +00006844 // Scan through the operands to find some interesting properties we can
6845 // exploit:
6846 // 1) If only one value is used, we can use a DUP, or
6847 // 2) if only the low element is not undef, we can just insert that, or
6848 // 3) if only one constant value is used (w/ some non-constant lanes),
6849 // we can splat the constant value into the whole vector then fill
6850 // in the non-constant lanes.
6851 // 4) FIXME: If different constant values are used, but we can intelligently
6852 // select the values we'll be overwriting for the non-constant
6853 // lanes such that we can directly materialize the vector
6854 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00006855 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00006856 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00006857 unsigned NumElts = VT.getVectorNumElements();
6858 bool isOnlyLowElement = true;
6859 bool usesOnlyOneValue = true;
6860 bool usesOnlyOneConstantValue = true;
6861 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00006862 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00006863 unsigned NumConstantLanes = 0;
6864 SDValue Value;
6865 SDValue ConstantValue;
6866 for (unsigned i = 0; i < NumElts; ++i) {
6867 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00006868 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6869 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00006870 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006871 continue;
6872 if (i > 0)
6873 isOnlyLowElement = false;
6874 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6875 isConstant = false;
6876
6877 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6878 ++NumConstantLanes;
6879 if (!ConstantValue.getNode())
6880 ConstantValue = V;
6881 else if (ConstantValue != V)
6882 usesOnlyOneConstantValue = false;
6883 }
6884
6885 if (!Value.getNode())
6886 Value = V;
6887 else if (V != Value)
6888 usesOnlyOneValue = false;
6889 }
6890
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006891 if (!Value.getNode()) {
6892 DEBUG(dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006893 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006894 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006895
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006896 if (isOnlyLowElement) {
6897 DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
6898 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006899 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006900 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006901
Sebastian Popc33af712018-03-01 15:47:39 +00006902 if (AllLanesExtractElt) {
6903 SDNode *Vector = nullptr;
6904 bool Even = false;
6905 bool Odd = false;
6906 // Check whether the extract elements match the Even pattern <0,2,4,...> or
6907 // the Odd pattern <1,3,5,...>.
6908 for (unsigned i = 0; i < NumElts; ++i) {
6909 SDValue V = Op.getOperand(i);
6910 const SDNode *N = V.getNode();
6911 if (!isa<ConstantSDNode>(N->getOperand(1)))
6912 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00006913 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00006914
6915 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00006916 if (!Vector) {
6917 Vector = N0.getNode();
6918 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
6919 // BUILD_VECTOR.
6920 if (VT.getVectorElementType() !=
6921 N0.getValueType().getVectorElementType())
6922 break;
6923 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00006924 Odd = false;
6925 Even = false;
6926 break;
6927 }
6928
6929 // Extracted values are either at Even indices <0,2,4,...> or at Odd
6930 // indices <1,3,5,...>.
6931 uint64_t Val = N->getConstantOperandVal(1);
6932 if (Val == 2 * i) {
6933 Even = true;
6934 continue;
6935 }
6936 if (Val - 1 == 2 * i) {
6937 Odd = true;
6938 continue;
6939 }
6940
6941 // Something does not match: abort.
6942 Odd = false;
6943 Even = false;
6944 break;
6945 }
6946 if (Even || Odd) {
6947 SDValue LHS =
6948 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
6949 DAG.getConstant(0, dl, MVT::i64));
6950 SDValue RHS =
6951 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
6952 DAG.getConstant(NumElts, dl, MVT::i64));
6953
6954 if (Even && !Odd)
6955 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
6956 RHS);
6957 if (Odd && !Even)
6958 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
6959 RHS);
6960 }
6961 }
6962
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006963 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00006964 // i32 and try again.
6965 if (usesOnlyOneValue) {
6966 if (!isConstant) {
6967 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006968 Value.getValueType() != VT) {
6969 DEBUG(dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006970 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006971 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006972
6973 // This is actually a DUPLANExx operation, which keeps everything vectory.
6974
Tim Northover3b0846e2014-05-24 12:50:23 +00006975 SDValue Lane = Value.getOperand(1);
6976 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006977 if (Value.getValueSizeInBits() == 64) {
6978 DEBUG(dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
6979 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006980 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006981 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006982
6983 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6984 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6985 }
6986
6987 if (VT.getVectorElementType().isFloatingPoint()) {
6988 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006989 EVT EltTy = VT.getVectorElementType();
6990 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6991 "Unsupported floating-point vector type");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006992 DEBUG(dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
6993 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006994 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006995 for (unsigned i = 0; i < NumElts; ++i)
6996 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6997 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006998 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006999 DEBUG(
7000 dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7001 Val.dump();
7002 );
Tim Northover3b0846e2014-05-24 12:50:23 +00007003 Val = LowerBUILD_VECTOR(Val, DAG);
7004 if (Val.getNode())
7005 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7006 }
7007 }
7008
7009 // If there was only one constant value used and for more than one lane,
7010 // start by splatting that value, then replace the non-constant lanes. This
7011 // is better than the default, which will perform a separate initialization
7012 // for each lane.
7013 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007014 // Firstly, try to materialize the splat constant.
7015 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7016 Val = ConstantBuildVector(Vec, DAG);
7017 if (!Val) {
7018 // Otherwise, materialize the constant and splat it.
7019 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7020 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7021 }
7022
Tim Northover3b0846e2014-05-24 12:50:23 +00007023 // Now insert the non-constant lanes.
7024 for (unsigned i = 0; i < NumElts; ++i) {
7025 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007026 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007027 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007028 // Note that type legalization likely mucked about with the VT of the
7029 // source operand, so we may have to convert it here before inserting.
7030 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007031 }
7032 return Val;
7033 }
7034
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007035 // This will generate a load from the constant pool.
7036 if (isConstant) {
7037 DEBUG(dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7038 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007039 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007040 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007041
7042 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7043 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007044 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007045 return shuffle;
7046 }
7047
7048 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7049 // know the default expansion would otherwise fall back on something even
7050 // worse. For a vector with one or two non-undef values, that's
7051 // scalar_to_vector for the elements followed by a shuffle (provided the
7052 // shuffle is valid for the target) and materialization element by element
7053 // on the stack followed by a load for everything else.
7054 if (!isConstant && !usesOnlyOneValue) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007055 DEBUG(dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7056 "of INSERT_VECTOR_ELT\n");
7057
Tim Northover3b0846e2014-05-24 12:50:23 +00007058 SDValue Vec = DAG.getUNDEF(VT);
7059 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007060 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007061
7062 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007063 // a) Avoid a RMW dependency on the full vector register, and
7064 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007065 // value is already in an S or D register, and we're forced to emit an
7066 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007067 //
7068 // We also allow types like i8 and i16 which are illegal scalar but legal
7069 // vector element types. After type-legalization the inserted value is
7070 // extended (i32) and it is safe to cast them to the vector type by ignoring
7071 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7072 if (!Op0.isUndef()) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007073 DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007074 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007075 ++i;
7076 }
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007077 DEBUG(
7078 if (i < NumElts)
7079 dbgs() << "Creating nodes for the other vector elements:\n";
7080 );
Tim Northover3b0846e2014-05-24 12:50:23 +00007081 for (; i < NumElts; ++i) {
7082 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007083 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007084 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007085 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007086 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7087 }
7088 return Vec;
7089 }
7090
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007091 DEBUG(dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7092 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007093 return SDValue();
7094}
7095
7096SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7097 SelectionDAG &DAG) const {
7098 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7099
Tim Northovere4b8e132014-07-15 10:00:26 +00007100 // Check for non-constant or out of range lane.
7101 EVT VT = Op.getOperand(0).getValueType();
7102 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7103 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007104 return SDValue();
7105
Tim Northover3b0846e2014-05-24 12:50:23 +00007106
7107 // Insertion/extraction are legal for V128 types.
7108 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007109 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7110 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007111 return Op;
7112
7113 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007114 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007115 return SDValue();
7116
7117 // For V64 types, we perform insertion by expanding the value
7118 // to a V128 type and perform the insertion on that.
7119 SDLoc DL(Op);
7120 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7121 EVT WideTy = WideVec.getValueType();
7122
7123 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7124 Op.getOperand(1), Op.getOperand(2));
7125 // Re-narrow the resultant vector.
7126 return NarrowVector(Node, DAG);
7127}
7128
7129SDValue
7130AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7131 SelectionDAG &DAG) const {
7132 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7133
Tim Northovere4b8e132014-07-15 10:00:26 +00007134 // Check for non-constant or out of range lane.
7135 EVT VT = Op.getOperand(0).getValueType();
7136 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7137 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007138 return SDValue();
7139
Tim Northover3b0846e2014-05-24 12:50:23 +00007140
7141 // Insertion/extraction are legal for V128 types.
7142 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007143 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7144 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007145 return Op;
7146
7147 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007148 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007149 return SDValue();
7150
7151 // For V64 types, we perform extraction by expanding the value
7152 // to a V128 type and perform the extraction on that.
7153 SDLoc DL(Op);
7154 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7155 EVT WideTy = WideVec.getValueType();
7156
7157 EVT ExtrTy = WideTy.getVectorElementType();
7158 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7159 ExtrTy = MVT::i32;
7160
7161 // For extractions, we just return the result directly.
7162 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7163 Op.getOperand(1));
7164}
7165
7166SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7167 SelectionDAG &DAG) const {
7168 EVT VT = Op.getOperand(0).getValueType();
7169 SDLoc dl(Op);
7170 // Just in case...
7171 if (!VT.isVector())
7172 return SDValue();
7173
7174 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7175 if (!Cst)
7176 return SDValue();
7177 unsigned Val = Cst->getZExtValue();
7178
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007179 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007180
7181 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7182 if (Val == 0)
7183 return Op;
7184
Tim Northover3b0846e2014-05-24 12:50:23 +00007185 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7186 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007187 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007188 return Op;
7189
7190 return SDValue();
7191}
7192
Zvi Rackover1b736822017-07-26 08:06:58 +00007193bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007194 if (VT.getVectorNumElements() == 4 &&
7195 (VT.is128BitVector() || VT.is64BitVector())) {
7196 unsigned PFIndexes[4];
7197 for (unsigned i = 0; i != 4; ++i) {
7198 if (M[i] < 0)
7199 PFIndexes[i] = 8;
7200 else
7201 PFIndexes[i] = M[i];
7202 }
7203
7204 // Compute the index in the perfect shuffle table.
7205 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7206 PFIndexes[2] * 9 + PFIndexes[3];
7207 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7208 unsigned Cost = (PFEntry >> 30);
7209
7210 if (Cost <= 4)
7211 return true;
7212 }
7213
7214 bool DummyBool;
7215 int DummyInt;
7216 unsigned DummyUnsigned;
7217
7218 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7219 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7220 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7221 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7222 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7223 isZIPMask(M, VT, DummyUnsigned) ||
7224 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7225 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7226 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7227 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7228 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7229}
7230
7231/// getVShiftImm - Check if this is a valid build_vector for the immediate
7232/// operand of a vector shift operation, where all the elements of the
7233/// build_vector must have the same constant integer value.
7234static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7235 // Ignore bit_converts.
7236 while (Op.getOpcode() == ISD::BITCAST)
7237 Op = Op.getOperand(0);
7238 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7239 APInt SplatBits, SplatUndef;
7240 unsigned SplatBitSize;
7241 bool HasAnyUndefs;
7242 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7243 HasAnyUndefs, ElementBits) ||
7244 SplatBitSize > ElementBits)
7245 return false;
7246 Cnt = SplatBits.getSExtValue();
7247 return true;
7248}
7249
7250/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7251/// operand of a vector shift left operation. That value must be in the range:
7252/// 0 <= Value < ElementBits for a left shift; or
7253/// 0 <= Value <= ElementBits for a long left shift.
7254static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7255 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007256 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007257 if (!getVShiftImm(Op, ElementBits, Cnt))
7258 return false;
7259 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7260}
7261
7262/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007263/// operand of a vector shift right operation. The value must be in the range:
7264/// 1 <= Value <= ElementBits for a right shift; or
7265static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007266 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007267 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007268 if (!getVShiftImm(Op, ElementBits, Cnt))
7269 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007270 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7271}
7272
7273SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7274 SelectionDAG &DAG) const {
7275 EVT VT = Op.getValueType();
7276 SDLoc DL(Op);
7277 int64_t Cnt;
7278
7279 if (!Op.getOperand(1).getValueType().isVector())
7280 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007281 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007282
7283 switch (Op.getOpcode()) {
7284 default:
7285 llvm_unreachable("unexpected shift opcode");
7286
7287 case ISD::SHL:
7288 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007289 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7290 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007291 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007292 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7293 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007294 Op.getOperand(0), Op.getOperand(1));
7295 case ISD::SRA:
7296 case ISD::SRL:
7297 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007298 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007299 unsigned Opc =
7300 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007301 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7302 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007303 }
7304
7305 // Right shift register. Note, there is not a shift right register
7306 // instruction, but the shift left register instruction takes a signed
7307 // value, where negative numbers specify a right shift.
7308 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7309 : Intrinsic::aarch64_neon_ushl;
7310 // negate the shift amount
7311 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7312 SDValue NegShiftLeft =
7313 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007314 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7315 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007316 return NegShiftLeft;
7317 }
7318
7319 return SDValue();
7320}
7321
7322static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7323 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007324 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007325 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007326 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7327 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007328
7329 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7330 APInt CnstBits(VT.getSizeInBits(), 0);
7331 APInt UndefBits(VT.getSizeInBits(), 0);
7332 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7333 bool IsZero = IsCnst && (CnstBits == 0);
7334
7335 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7336 switch (CC) {
7337 default:
7338 return SDValue();
7339 case AArch64CC::NE: {
7340 SDValue Fcmeq;
7341 if (IsZero)
7342 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7343 else
7344 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7345 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7346 }
7347 case AArch64CC::EQ:
7348 if (IsZero)
7349 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7350 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7351 case AArch64CC::GE:
7352 if (IsZero)
7353 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7354 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7355 case AArch64CC::GT:
7356 if (IsZero)
7357 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7358 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7359 case AArch64CC::LS:
7360 if (IsZero)
7361 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7362 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7363 case AArch64CC::LT:
7364 if (!NoNans)
7365 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007366 // If we ignore NaNs then we can use to the MI implementation.
7367 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007368 case AArch64CC::MI:
7369 if (IsZero)
7370 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7371 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7372 }
7373 }
7374
7375 switch (CC) {
7376 default:
7377 return SDValue();
7378 case AArch64CC::NE: {
7379 SDValue Cmeq;
7380 if (IsZero)
7381 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7382 else
7383 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7384 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7385 }
7386 case AArch64CC::EQ:
7387 if (IsZero)
7388 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7389 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7390 case AArch64CC::GE:
7391 if (IsZero)
7392 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7393 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7394 case AArch64CC::GT:
7395 if (IsZero)
7396 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7397 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7398 case AArch64CC::LE:
7399 if (IsZero)
7400 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7401 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7402 case AArch64CC::LS:
7403 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7404 case AArch64CC::LO:
7405 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7406 case AArch64CC::LT:
7407 if (IsZero)
7408 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7409 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7410 case AArch64CC::HI:
7411 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7412 case AArch64CC::HS:
7413 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7414 }
7415}
7416
7417SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7418 SelectionDAG &DAG) const {
7419 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7420 SDValue LHS = Op.getOperand(0);
7421 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007422 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007423 SDLoc dl(Op);
7424
7425 if (LHS.getValueType().getVectorElementType().isInteger()) {
7426 assert(LHS.getValueType() == RHS.getValueType());
7427 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007428 SDValue Cmp =
7429 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7430 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007431 }
7432
Carey Williamsda15b5b2018-01-22 14:16:11 +00007433 const bool FullFP16 =
7434 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7435
7436 // Make v4f16 (only) fcmp operations utilise vector instructions
7437 // v8f16 support will be a litle more complicated
7438 if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7439 if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7440 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7441 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7442 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7443 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7444 CmpVT = MVT::v4i32;
7445 } else
7446 return SDValue();
7447 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007448
Tim Northover3b0846e2014-05-24 12:50:23 +00007449 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7450 LHS.getValueType().getVectorElementType() == MVT::f64);
7451
7452 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7453 // clean. Some of them require two branches to implement.
7454 AArch64CC::CondCode CC1, CC2;
7455 bool ShouldInvert;
7456 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7457
7458 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7459 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007460 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007461 if (!Cmp.getNode())
7462 return SDValue();
7463
7464 if (CC2 != AArch64CC::AL) {
7465 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007466 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007467 if (!Cmp2.getNode())
7468 return SDValue();
7469
Tim Northover45aa89c2015-02-08 00:50:47 +00007470 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007471 }
7472
Tim Northover45aa89c2015-02-08 00:50:47 +00007473 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7474
Tim Northover3b0846e2014-05-24 12:50:23 +00007475 if (ShouldInvert)
7476 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7477
7478 return Cmp;
7479}
7480
Amara Emersonc9916d72017-05-16 21:29:22 +00007481static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7482 SelectionDAG &DAG) {
7483 SDValue VecOp = ScalarOp.getOperand(0);
7484 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7485 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7486 DAG.getConstant(0, DL, MVT::i64));
7487}
7488
7489SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7490 SelectionDAG &DAG) const {
7491 SDLoc dl(Op);
7492 switch (Op.getOpcode()) {
7493 case ISD::VECREDUCE_ADD:
7494 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7495 case ISD::VECREDUCE_SMAX:
7496 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7497 case ISD::VECREDUCE_SMIN:
7498 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7499 case ISD::VECREDUCE_UMAX:
7500 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7501 case ISD::VECREDUCE_UMIN:
7502 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7503 case ISD::VECREDUCE_FMAX: {
7504 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7505 return DAG.getNode(
7506 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7507 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7508 Op.getOperand(0));
7509 }
7510 case ISD::VECREDUCE_FMIN: {
7511 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7512 return DAG.getNode(
7513 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7514 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7515 Op.getOperand(0));
7516 }
7517 default:
7518 llvm_unreachable("Unhandled reduction");
7519 }
7520}
7521
Oliver Stannard42699172018-02-12 14:22:03 +00007522SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7523 SelectionDAG &DAG) const {
7524 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7525 if (!Subtarget.hasLSE())
7526 return SDValue();
7527
7528 // LSE has an atomic load-add instruction, but not a load-sub.
7529 SDLoc dl(Op);
7530 MVT VT = Op.getSimpleValueType();
7531 SDValue RHS = Op.getOperand(2);
7532 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7533 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7534 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7535 Op.getOperand(0), Op.getOperand(1), RHS,
7536 AN->getMemOperand());
7537}
7538
Oliver Stannard02f08c92018-02-12 17:03:11 +00007539SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7540 SelectionDAG &DAG) const {
7541 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7542 if (!Subtarget.hasLSE())
7543 return SDValue();
7544
7545 // LSE has an atomic load-clear instruction, but not a load-and.
7546 SDLoc dl(Op);
7547 MVT VT = Op.getSimpleValueType();
7548 SDValue RHS = Op.getOperand(2);
7549 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7550 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7551 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7552 Op.getOperand(0), Op.getOperand(1), RHS,
7553 AN->getMemOperand());
7554}
7555
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007556SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7557 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7558 SDLoc dl(Op);
7559 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7560 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7561
7562 const uint32_t *Mask =
7563 Subtarget->getRegisterInfo()->getWindowsStackProbePreservedMask();
7564
7565 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7566 DAG.getConstant(4, dl, MVT::i64));
7567 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7568 Chain =
7569 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7570 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7571 DAG.getRegisterMask(Mask), Chain.getValue(1));
7572 // To match the actual intent better, we should read the output from X15 here
7573 // again (instead of potentially spilling it to the stack), but rereading Size
7574 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7575 // here.
7576
7577 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7578 DAG.getConstant(4, dl, MVT::i64));
7579 return Chain;
7580}
7581
7582SDValue
7583AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7584 SelectionDAG &DAG) const {
7585 assert(Subtarget->isTargetWindows() &&
7586 "Only Windows alloca probing supported");
7587 SDLoc dl(Op);
7588 // Get the inputs.
7589 SDNode *Node = Op.getNode();
7590 SDValue Chain = Op.getOperand(0);
7591 SDValue Size = Op.getOperand(1);
7592 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7593 EVT VT = Node->getValueType(0);
7594
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007595 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7596 "no-stack-arg-probe")) {
7597 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7598 Chain = SP.getValue(1);
7599 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7600 if (Align)
7601 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7602 DAG.getConstant(-(uint64_t)Align, dl, VT));
7603 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7604 SDValue Ops[2] = {SP, Chain};
7605 return DAG.getMergeValues(Ops, dl);
7606 }
7607
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007608 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7609
7610 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7611
7612 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7613 Chain = SP.getValue(1);
7614 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00007615 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007616 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7617 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00007618 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007619
7620 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7621 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7622
7623 SDValue Ops[2] = {SP, Chain};
7624 return DAG.getMergeValues(Ops, dl);
7625}
7626
Tim Northover3b0846e2014-05-24 12:50:23 +00007627/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7628/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7629/// specified in the intrinsic calls.
7630bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7631 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00007632 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00007633 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007634 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007635 switch (Intrinsic) {
7636 case Intrinsic::aarch64_neon_ld2:
7637 case Intrinsic::aarch64_neon_ld3:
7638 case Intrinsic::aarch64_neon_ld4:
7639 case Intrinsic::aarch64_neon_ld1x2:
7640 case Intrinsic::aarch64_neon_ld1x3:
7641 case Intrinsic::aarch64_neon_ld1x4:
7642 case Intrinsic::aarch64_neon_ld2lane:
7643 case Intrinsic::aarch64_neon_ld3lane:
7644 case Intrinsic::aarch64_neon_ld4lane:
7645 case Intrinsic::aarch64_neon_ld2r:
7646 case Intrinsic::aarch64_neon_ld3r:
7647 case Intrinsic::aarch64_neon_ld4r: {
7648 Info.opc = ISD::INTRINSIC_W_CHAIN;
7649 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007650 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007651 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7652 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7653 Info.offset = 0;
7654 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00007655 // volatile loads with NEON intrinsics not supported
7656 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00007657 return true;
7658 }
7659 case Intrinsic::aarch64_neon_st2:
7660 case Intrinsic::aarch64_neon_st3:
7661 case Intrinsic::aarch64_neon_st4:
7662 case Intrinsic::aarch64_neon_st1x2:
7663 case Intrinsic::aarch64_neon_st1x3:
7664 case Intrinsic::aarch64_neon_st1x4:
7665 case Intrinsic::aarch64_neon_st2lane:
7666 case Intrinsic::aarch64_neon_st3lane:
7667 case Intrinsic::aarch64_neon_st4lane: {
7668 Info.opc = ISD::INTRINSIC_VOID;
7669 // Conservatively set memVT to the entire set of vectors stored.
7670 unsigned NumElts = 0;
7671 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7672 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7673 if (!ArgTy->isVectorTy())
7674 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007675 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007676 }
7677 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7678 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7679 Info.offset = 0;
7680 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00007681 // volatile stores with NEON intrinsics not supported
7682 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00007683 return true;
7684 }
7685 case Intrinsic::aarch64_ldaxr:
7686 case Intrinsic::aarch64_ldxr: {
7687 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7688 Info.opc = ISD::INTRINSIC_W_CHAIN;
7689 Info.memVT = MVT::getVT(PtrTy->getElementType());
7690 Info.ptrVal = I.getArgOperand(0);
7691 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007692 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00007693 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007694 return true;
7695 }
7696 case Intrinsic::aarch64_stlxr:
7697 case Intrinsic::aarch64_stxr: {
7698 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7699 Info.opc = ISD::INTRINSIC_W_CHAIN;
7700 Info.memVT = MVT::getVT(PtrTy->getElementType());
7701 Info.ptrVal = I.getArgOperand(1);
7702 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007703 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00007704 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007705 return true;
7706 }
7707 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007708 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007709 Info.opc = ISD::INTRINSIC_W_CHAIN;
7710 Info.memVT = MVT::i128;
7711 Info.ptrVal = I.getArgOperand(0);
7712 Info.offset = 0;
7713 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00007714 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007715 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007716 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007717 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007718 Info.opc = ISD::INTRINSIC_W_CHAIN;
7719 Info.memVT = MVT::i128;
7720 Info.ptrVal = I.getArgOperand(2);
7721 Info.offset = 0;
7722 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00007723 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007724 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007725 default:
7726 break;
7727 }
7728
7729 return false;
7730}
7731
John Brawne3b44f92018-03-23 14:47:07 +00007732bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
7733 ISD::LoadExtType ExtTy,
7734 EVT NewVT) const {
7735 // If we're reducing the load width in order to avoid having to use an extra
7736 // instruction to do extension then it's probably a good idea.
7737 if (ExtTy != ISD::NON_EXTLOAD)
7738 return true;
7739 // Don't reduce load width if it would prevent us from combining a shift into
7740 // the offset.
7741 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
7742 assert(Mem);
7743 const SDValue &Base = Mem->getBasePtr();
7744 if (Base.getOpcode() == ISD::ADD &&
7745 Base.getOperand(1).getOpcode() == ISD::SHL &&
7746 Base.getOperand(1).hasOneUse() &&
7747 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
7748 // The shift can be combined if it matches the size of the value being
7749 // loaded (and so reducing the width would make it not match).
7750 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
7751 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
7752 if (ShiftAmount == Log2_32(LoadBytes))
7753 return false;
7754 }
7755 // We have no reason to disallow reducing the load width, so allow it.
7756 return true;
7757}
7758
Tim Northover3b0846e2014-05-24 12:50:23 +00007759// Truncations from 64-bit GPR to 32-bit GPR is free.
7760bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7761 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7762 return false;
7763 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7764 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007765 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007766}
7767bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007768 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007769 return false;
7770 unsigned NumBits1 = VT1.getSizeInBits();
7771 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007772 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007773}
7774
Chad Rosier54390052015-02-23 19:15:16 +00007775/// Check if it is profitable to hoist instruction in then/else to if.
7776/// Not profitable if I and it's user can form a FMA instruction
7777/// because we prefer FMSUB/FMADD.
7778bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7779 if (I->getOpcode() != Instruction::FMul)
7780 return true;
7781
Davide Italiano3e9986f2017-04-18 00:29:54 +00007782 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00007783 return true;
7784
7785 Instruction *User = I->user_back();
7786
7787 if (User &&
7788 !(User->getOpcode() == Instruction::FSub ||
7789 User->getOpcode() == Instruction::FAdd))
7790 return true;
7791
7792 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007793 const DataLayout &DL = I->getModule()->getDataLayout();
7794 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007795
Eric Christopher114fa1c2016-02-29 22:50:49 +00007796 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7797 isOperationLegalOrCustom(ISD::FMA, VT) &&
7798 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7799 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007800}
7801
Tim Northover3b0846e2014-05-24 12:50:23 +00007802// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7803// 64-bit GPR.
7804bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7805 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7806 return false;
7807 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7808 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007809 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007810}
7811bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007812 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007813 return false;
7814 unsigned NumBits1 = VT1.getSizeInBits();
7815 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007816 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007817}
7818
7819bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7820 EVT VT1 = Val.getValueType();
7821 if (isZExtFree(VT1, VT2)) {
7822 return true;
7823 }
7824
7825 if (Val.getOpcode() != ISD::LOAD)
7826 return false;
7827
7828 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007829 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7830 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7831 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007832}
7833
Quentin Colombet6843ac42015-03-31 20:52:32 +00007834bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7835 if (isa<FPExtInst>(Ext))
7836 return false;
7837
Haicheng Wu50692a22017-08-01 21:26:45 +00007838 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00007839 if (Ext->getType()->isVectorTy())
7840 return false;
7841
7842 for (const Use &U : Ext->uses()) {
7843 // The extension is free if we can fold it with a left shift in an
7844 // addressing mode or an arithmetic operation: add, sub, and cmp.
7845
7846 // Is there a shift?
7847 const Instruction *Instr = cast<Instruction>(U.getUser());
7848
7849 // Is this a constant shift?
7850 switch (Instr->getOpcode()) {
7851 case Instruction::Shl:
7852 if (!isa<ConstantInt>(Instr->getOperand(1)))
7853 return false;
7854 break;
7855 case Instruction::GetElementPtr: {
7856 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007857 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00007858 std::advance(GTI, U.getOperandNo()-1);
7859 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007860 // This extension will end up with a shift because of the scaling factor.
7861 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7862 // Get the shift amount based on the scaling factor:
7863 // log2(sizeof(IdxTy)) - log2(8).
7864 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007865 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007866 // Is the constant foldable in the shift of the addressing mode?
7867 // I.e., shift amount is between 1 and 4 inclusive.
7868 if (ShiftAmt == 0 || ShiftAmt > 4)
7869 return false;
7870 break;
7871 }
7872 case Instruction::Trunc:
7873 // Check if this is a noop.
7874 // trunc(sext ty1 to ty2) to ty1.
7875 if (Instr->getType() == Ext->getOperand(0)->getType())
7876 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007877 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007878 default:
7879 return false;
7880 }
7881
7882 // At this point we can use the bfm family, so this extension is free
7883 // for that use.
7884 }
7885 return true;
7886}
7887
Tim Northover3b0846e2014-05-24 12:50:23 +00007888bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7889 unsigned &RequiredAligment) const {
7890 if (!LoadedType.isSimple() ||
7891 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7892 return false;
7893 // Cyclone supports unaligned accesses.
7894 RequiredAligment = 0;
7895 unsigned NumBits = LoadedType.getSizeInBits();
7896 return NumBits == 32 || NumBits == 64;
7897}
7898
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007899/// A helper function for determining the number of interleaved accesses we
7900/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007901unsigned
7902AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7903 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007904 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7905}
7906
Geoff Berryb1e87142017-07-14 21:44:12 +00007907MachineMemOperand::Flags
7908AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
7909 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
7910 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
7911 return MOStridedAccess;
7912 return MachineMemOperand::MONone;
7913}
7914
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007915bool AArch64TargetLowering::isLegalInterleavedAccessType(
7916 VectorType *VecTy, const DataLayout &DL) const {
7917
7918 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7919 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7920
7921 // Ensure the number of vector elements is greater than 1.
7922 if (VecTy->getNumElements() < 2)
7923 return false;
7924
7925 // Ensure the element type is legal.
7926 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7927 return false;
7928
7929 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7930 // 128 will be split into multiple interleaved accesses.
7931 return VecSize == 64 || VecSize % 128 == 0;
7932}
7933
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007934/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00007935///
7936/// E.g. Lower an interleaved load (Factor = 2):
7937/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7938/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7939/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7940///
7941/// Into:
7942/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7943/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7944/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7945bool AArch64TargetLowering::lowerInterleavedLoad(
7946 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7947 ArrayRef<unsigned> Indices, unsigned Factor) const {
7948 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7949 "Invalid interleave factor");
7950 assert(!Shuffles.empty() && "Empty shufflevector input");
7951 assert(Shuffles.size() == Indices.size() &&
7952 "Unmatched number of shufflevectors and indices");
7953
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007954 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007955
7956 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007957
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007958 // Skip if we do not have NEON and skip illegal vector types. We can
7959 // "legalize" wide vector types into multiple interleaved accesses as long as
7960 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007961 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007962 return false;
7963
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007964 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7965
Hao Liu7ec8ee32015-06-26 02:32:07 +00007966 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7967 // load integer vectors first and then convert to pointer vectors.
7968 Type *EltTy = VecTy->getVectorElementType();
7969 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007970 VecTy =
7971 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007972
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007973 IRBuilder<> Builder(LI);
7974
7975 // The base address of the load.
7976 Value *BaseAddr = LI->getPointerOperand();
7977
7978 if (NumLoads > 1) {
7979 // If we're going to generate more than one load, reset the sub-vector type
7980 // to something legal.
7981 VecTy = VectorType::get(VecTy->getVectorElementType(),
7982 VecTy->getVectorNumElements() / NumLoads);
7983
7984 // We will compute the pointer operand of each load from the original base
7985 // address using GEPs. Cast the base address to a pointer to the scalar
7986 // element type.
7987 BaseAddr = Builder.CreateBitCast(
7988 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7989 LI->getPointerAddressSpace()));
7990 }
7991
Hao Liu7ec8ee32015-06-26 02:32:07 +00007992 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7993 Type *Tys[2] = {VecTy, PtrTy};
7994 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7995 Intrinsic::aarch64_neon_ld3,
7996 Intrinsic::aarch64_neon_ld4};
7997 Function *LdNFunc =
7998 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7999
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008000 // Holds sub-vectors extracted from the load intrinsic return values. The
8001 // sub-vectors are associated with the shufflevector instructions they will
8002 // replace.
8003 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008004
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008005 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008006
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008007 // If we're generating more than one load, compute the base address of
8008 // subsequent loads as an offset from the previous.
8009 if (LoadCount > 0)
8010 BaseAddr = Builder.CreateConstGEP1_32(
8011 BaseAddr, VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008012
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008013 CallInst *LdN = Builder.CreateCall(
8014 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008015
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008016 // Extract and store the sub-vectors returned by the load intrinsic.
8017 for (unsigned i = 0; i < Shuffles.size(); i++) {
8018 ShuffleVectorInst *SVI = Shuffles[i];
8019 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008020
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008021 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8022
8023 // Convert the integer vector to pointer vector if the element is pointer.
8024 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008025 SubVec = Builder.CreateIntToPtr(
8026 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8027 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008028 SubVecs[SVI].push_back(SubVec);
8029 }
8030 }
8031
8032 // Replace uses of the shufflevector instructions with the sub-vectors
8033 // returned by the load intrinsic. If a shufflevector instruction is
8034 // associated with more than one sub-vector, those sub-vectors will be
8035 // concatenated into a single wide vector.
8036 for (ShuffleVectorInst *SVI : Shuffles) {
8037 auto &SubVec = SubVecs[SVI];
8038 auto *WideVec =
8039 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8040 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008041 }
8042
8043 return true;
8044}
8045
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008046/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008047///
8048/// E.g. Lower an interleaved store (Factor = 3):
8049/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008050/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008051/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8052///
8053/// Into:
8054/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8055/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8056/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8057/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8058///
8059/// Note that the new shufflevectors will be removed and we'll only generate one
8060/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008061///
8062/// Example for a more general valid mask (Factor 3). Lower:
8063/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8064/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8065/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8066///
8067/// Into:
8068/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8069/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8070/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8071/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008072bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8073 ShuffleVectorInst *SVI,
8074 unsigned Factor) const {
8075 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8076 "Invalid interleave factor");
8077
8078 VectorType *VecTy = SVI->getType();
8079 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8080 "Invalid interleaved store");
8081
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008082 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008083 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008084 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008085
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008086 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008087
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008088 // Skip if we do not have NEON and skip illegal vector types. We can
8089 // "legalize" wide vector types into multiple interleaved accesses as long as
8090 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008091 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008092 return false;
8093
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008094 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8095
Hao Liu7ec8ee32015-06-26 02:32:07 +00008096 Value *Op0 = SVI->getOperand(0);
8097 Value *Op1 = SVI->getOperand(1);
8098 IRBuilder<> Builder(SI);
8099
8100 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8101 // vectors to integer vectors.
8102 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008103 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008104 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008105
8106 // Convert to the corresponding integer vector.
8107 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8108 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8109 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8110
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008111 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008112 }
8113
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008114 // The base address of the store.
8115 Value *BaseAddr = SI->getPointerOperand();
8116
8117 if (NumStores > 1) {
8118 // If we're going to generate more than one store, reset the lane length
8119 // and sub-vector type to something legal.
8120 LaneLen /= NumStores;
8121 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8122
8123 // We will compute the pointer operand of each store from the original base
8124 // address using GEPs. Cast the base address to a pointer to the scalar
8125 // element type.
8126 BaseAddr = Builder.CreateBitCast(
8127 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8128 SI->getPointerAddressSpace()));
8129 }
8130
8131 auto Mask = SVI->getShuffleMask();
8132
Hao Liu7ec8ee32015-06-26 02:32:07 +00008133 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8134 Type *Tys[2] = {SubVecTy, PtrTy};
8135 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8136 Intrinsic::aarch64_neon_st3,
8137 Intrinsic::aarch64_neon_st4};
8138 Function *StNFunc =
8139 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8140
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008141 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008142
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008143 SmallVector<Value *, 5> Ops;
8144
8145 // Split the shufflevector operands into sub vectors for the new stN call.
8146 for (unsigned i = 0; i < Factor; i++) {
8147 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8148 if (Mask[IdxI] >= 0) {
8149 Ops.push_back(Builder.CreateShuffleVector(
8150 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8151 } else {
8152 unsigned StartMask = 0;
8153 for (unsigned j = 1; j < LaneLen; j++) {
8154 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8155 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8156 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8157 break;
8158 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008159 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008160 // Note: Filling undef gaps with random elements is ok, since
8161 // those elements were being written anyway (with undefs).
8162 // In the case of all undefs we're defaulting to using elems from 0
8163 // Note: StartMask cannot be negative, it's checked in
8164 // isReInterleaveMask
8165 Ops.push_back(Builder.CreateShuffleVector(
8166 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008167 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008168 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008169
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008170 // If we generating more than one store, we compute the base address of
8171 // subsequent stores as an offset from the previous.
8172 if (StoreCount > 0)
8173 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
8174
8175 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8176 Builder.CreateCall(StNFunc, Ops);
8177 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008178 return true;
8179}
8180
Tim Northover3b0846e2014-05-24 12:50:23 +00008181static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8182 unsigned AlignCheck) {
8183 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8184 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8185}
8186
8187EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8188 unsigned SrcAlign, bool IsMemset,
8189 bool ZeroMemset,
8190 bool MemcpyStrSrc,
8191 MachineFunction &MF) const {
8192 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
8193 // instruction to materialize the v2i64 zero and one store (with restrictive
8194 // addressing mode). Just do two i64 store of zero-registers.
8195 bool Fast;
Matthias Braunf1caa282017-12-15 22:22:58 +00008196 const Function &F = MF.getFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00008197 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Matthias Braunf1caa282017-12-15 22:22:58 +00008198 !F.hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008199 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00008200 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00008201 return MVT::f128;
8202
Lang Hames90333852015-04-09 03:40:33 +00008203 if (Size >= 8 &&
8204 (memOpAlign(SrcAlign, DstAlign, 8) ||
8205 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
8206 return MVT::i64;
8207
8208 if (Size >= 4 &&
8209 (memOpAlign(SrcAlign, DstAlign, 4) ||
8210 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00008211 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008212
8213 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008214}
8215
8216// 12-bit optionally shifted immediates are legal for adds.
8217bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008218 if (Immed == std::numeric_limits<int64_t>::min()) {
8219 DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008220 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008221 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008222 // Same encoding for add/sub, just flip the sign.
8223 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008224 bool IsLegal = ((Immed >> 12) == 0 ||
8225 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
8226 DEBUG(dbgs() << "Is " << Immed << " legal add imm: " <<
8227 (IsLegal ? "yes" : "no") << "\n");
8228 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008229}
8230
8231// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8232// immediates is the same as for an add or a sub.
8233bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008234 return isLegalAddImmediate(Immed);
8235}
8236
8237/// isLegalAddressingMode - Return true if the addressing mode represented
8238/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008239bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8240 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008241 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008242 // AArch64 has five basic addressing modes:
8243 // reg
8244 // reg + 9-bit signed offset
8245 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8246 // reg1 + reg2
8247 // reg + SIZE_IN_BYTES * reg
8248
8249 // No global is ever allowed as a base.
8250 if (AM.BaseGV)
8251 return false;
8252
8253 // No reg+reg+imm addressing.
8254 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8255 return false;
8256
8257 // check reg + imm case:
8258 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8259 uint64_t NumBytes = 0;
8260 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008261 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008262 NumBytes = NumBits / 8;
8263 if (!isPowerOf2_64(NumBits))
8264 NumBytes = 0;
8265 }
8266
8267 if (!AM.Scale) {
8268 int64_t Offset = AM.BaseOffs;
8269
8270 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008271 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008272 return true;
8273
8274 // 12-bit unsigned offset
8275 unsigned shift = Log2_64(NumBytes);
8276 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8277 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8278 (Offset >> shift) << shift == Offset)
8279 return true;
8280 return false;
8281 }
8282
8283 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8284
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008285 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008286}
8287
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008288bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8289 // Consider splitting large offset of struct or array.
8290 return true;
8291}
8292
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008293int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8294 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008295 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008296 // Scaling factors are not free at all.
8297 // Operands | Rt Latency
8298 // -------------------------------------------
8299 // Rt, [Xn, Xm] | 4
8300 // -------------------------------------------
8301 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8302 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008303 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008304 // Scale represents reg2 * scale, thus account for 1 if
8305 // it is not equal to 0 or 1.
8306 return AM.Scale != 0 && AM.Scale != 1;
8307 return -1;
8308}
8309
8310bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8311 VT = VT.getScalarType();
8312
8313 if (!VT.isSimple())
8314 return false;
8315
8316 switch (VT.getSimpleVT().SimpleTy) {
8317 case MVT::f32:
8318 case MVT::f64:
8319 return true;
8320 default:
8321 break;
8322 }
8323
8324 return false;
8325}
8326
8327const MCPhysReg *
8328AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8329 // LR is a callee-save register, but we must treat it as clobbered by any call
8330 // site. Hence we include LR in the scratch registers, which are in turn added
8331 // as implicit-defs for stackmaps and patchpoints.
8332 static const MCPhysReg ScratchRegs[] = {
8333 AArch64::X16, AArch64::X17, AArch64::LR, 0
8334 };
8335 return ScratchRegs;
8336}
8337
8338bool
8339AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
8340 EVT VT = N->getValueType(0);
8341 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8342 // it with shift to let it be lowered to UBFX.
8343 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8344 isa<ConstantSDNode>(N->getOperand(1))) {
8345 uint64_t TruncMask = N->getConstantOperandVal(1);
8346 if (isMask_64(TruncMask) &&
8347 N->getOperand(0).getOpcode() == ISD::SRL &&
8348 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8349 return false;
8350 }
8351 return true;
8352}
8353
8354bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8355 Type *Ty) const {
8356 assert(Ty->isIntegerTy());
8357
8358 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8359 if (BitSize == 0)
8360 return false;
8361
8362 int64_t Val = Imm.getSExtValue();
8363 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8364 return true;
8365
8366 if ((int64_t)Val < 0)
8367 Val = ~Val;
8368 if (BitSize == 32)
8369 Val &= (1LL << 32) - 1;
8370
8371 unsigned LZ = countLeadingZeros((uint64_t)Val);
8372 unsigned Shift = (63 - LZ) / 16;
8373 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008374 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008375}
8376
Sebastian Pop41073e82018-03-06 16:54:55 +00008377bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8378 unsigned Index) const {
8379 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8380 return false;
8381
8382 return (Index == 0 || Index == ResVT.getVectorNumElements());
8383}
8384
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008385/// Turn vector tests of the signbit in the form of:
8386/// xor (sra X, elt_size(X)-1), -1
8387/// into:
8388/// cmge X, X, #0
8389static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8390 const AArch64Subtarget *Subtarget) {
8391 EVT VT = N->getValueType(0);
8392 if (!Subtarget->hasNEON() || !VT.isVector())
8393 return SDValue();
8394
8395 // There must be a shift right algebraic before the xor, and the xor must be a
8396 // 'not' operation.
8397 SDValue Shift = N->getOperand(0);
8398 SDValue Ones = N->getOperand(1);
8399 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8400 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8401 return SDValue();
8402
8403 // The shift should be smearing the sign bit across each vector element.
8404 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8405 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8406 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8407 return SDValue();
8408
8409 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8410}
8411
Tim Northover3b0846e2014-05-24 12:50:23 +00008412// Generate SUBS and CSEL for integer abs.
8413static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8414 EVT VT = N->getValueType(0);
8415
8416 SDValue N0 = N->getOperand(0);
8417 SDValue N1 = N->getOperand(1);
8418 SDLoc DL(N);
8419
8420 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8421 // and change it to SUB and CSEL.
8422 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8423 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8424 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8425 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8426 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008427 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008428 N0.getOperand(0));
8429 // Generate SUBS & CSEL.
8430 SDValue Cmp =
8431 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008432 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008433 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008434 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008435 SDValue(Cmp.getNode(), 1));
8436 }
8437 return SDValue();
8438}
8439
Tim Northover3b0846e2014-05-24 12:50:23 +00008440static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8441 TargetLowering::DAGCombinerInfo &DCI,
8442 const AArch64Subtarget *Subtarget) {
8443 if (DCI.isBeforeLegalizeOps())
8444 return SDValue();
8445
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008446 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8447 return Cmp;
8448
Tim Northover3b0846e2014-05-24 12:50:23 +00008449 return performIntegerAbsCombine(N, DAG);
8450}
8451
Chad Rosier17020f92014-07-23 14:57:52 +00008452SDValue
8453AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8454 SelectionDAG &DAG,
8455 std::vector<SDNode *> *Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008456 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008457 if (isIntDivCheap(N->getValueType(0), Attr))
8458 return SDValue(N,0); // Lower SDIV as SDIV
8459
Chad Rosier17020f92014-07-23 14:57:52 +00008460 // fold (sdiv X, pow2)
8461 EVT VT = N->getValueType(0);
8462 if ((VT != MVT::i32 && VT != MVT::i64) ||
8463 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8464 return SDValue();
8465
8466 SDLoc DL(N);
8467 SDValue N0 = N->getOperand(0);
8468 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008469 SDValue Zero = DAG.getConstant(0, DL, VT);
8470 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008471
8472 // Add (N0 < 0) ? Pow2 - 1 : 0;
8473 SDValue CCVal;
8474 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8475 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8476 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8477
8478 if (Created) {
8479 Created->push_back(Cmp.getNode());
8480 Created->push_back(Add.getNode());
8481 Created->push_back(CSel.getNode());
8482 }
8483
8484 // Divide by pow2.
8485 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008486 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008487
8488 // If we're dividing by a positive value, we're done. Otherwise, we must
8489 // negate the result.
8490 if (Divisor.isNonNegative())
8491 return SRA;
8492
8493 if (Created)
8494 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008495 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008496}
8497
Tim Northover3b0846e2014-05-24 12:50:23 +00008498static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8499 TargetLowering::DAGCombinerInfo &DCI,
8500 const AArch64Subtarget *Subtarget) {
8501 if (DCI.isBeforeLegalizeOps())
8502 return SDValue();
8503
Chad Rosier31ee8132016-11-11 17:07:37 +00008504 // The below optimizations require a constant RHS.
8505 if (!isa<ConstantSDNode>(N->getOperand(1)))
8506 return SDValue();
8507
8508 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8509 const APInt &ConstValue = C->getAPIntValue();
8510
Tim Northover3b0846e2014-05-24 12:50:23 +00008511 // Multiplication of a power of two plus/minus one can be done more
8512 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8513 // future CPUs have a cheaper MADD instruction, this may need to be
8514 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8515 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008516 // More aggressively, some multiplications N0 * C can be lowered to
8517 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8518 // e.g. 6=3*2=(2+1)*2.
8519 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8520 // which equals to (1+2)*16-(1+2).
8521 SDValue N0 = N->getOperand(0);
8522 // TrailingZeroes is used to test if the mul can be lowered to
8523 // shift+add+shift.
8524 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8525 if (TrailingZeroes) {
8526 // Conservatively do not lower to shift+add+shift if the mul might be
8527 // folded into smul or umul.
8528 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8529 isZeroExtended(N0.getNode(), DAG)))
8530 return SDValue();
8531 // Conservatively do not lower to shift+add+shift if the mul might be
8532 // folded into madd or msub.
8533 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8534 N->use_begin()->getOpcode() == ISD::SUB))
8535 return SDValue();
8536 }
8537 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8538 // and shift+add+shift.
8539 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8540
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008541 unsigned ShiftAmt, AddSubOpc;
8542 // Is the shifted value the LHS operand of the add/sub?
8543 bool ShiftValUseIsN0 = true;
8544 // Do we need to negate the result?
8545 bool NegateResult = false;
8546
Chad Rosier31ee8132016-11-11 17:07:37 +00008547 if (ConstValue.isNonNegative()) {
8548 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00008549 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00008550 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8551 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008552 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00008553 if (SCVMinus1.isPowerOf2()) {
8554 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008555 AddSubOpc = ISD::ADD;
8556 } else if (CVPlus1.isPowerOf2()) {
8557 ShiftAmt = CVPlus1.logBase2();
8558 AddSubOpc = ISD::SUB;
8559 } else
8560 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00008561 } else {
8562 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00008563 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008564 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008565 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008566 if (CVNegPlus1.isPowerOf2()) {
8567 ShiftAmt = CVNegPlus1.logBase2();
8568 AddSubOpc = ISD::SUB;
8569 ShiftValUseIsN0 = false;
8570 } else if (CVNegMinus1.isPowerOf2()) {
8571 ShiftAmt = CVNegMinus1.logBase2();
8572 AddSubOpc = ISD::ADD;
8573 NegateResult = true;
8574 } else
8575 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008576 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008577
8578 SDLoc DL(N);
8579 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008580 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008581 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8582
8583 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8584 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8585 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008586 assert(!(NegateResult && TrailingZeroes) &&
8587 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008588 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008589 if (NegateResult)
8590 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8591 // Shift the result.
8592 if (TrailingZeroes)
8593 return DAG.getNode(ISD::SHL, DL, VT, Res,
8594 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8595 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00008596}
8597
Jim Grosbachf7502c42014-07-18 00:40:52 +00008598static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8599 SelectionDAG &DAG) {
8600 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8601 // optimize away operation when it's from a constant.
8602 //
8603 // The general transformation is:
8604 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8605 // AND(VECTOR_CMP(x,y), constant2)
8606 // constant2 = UNARYOP(constant)
8607
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008608 // Early exit if this isn't a vector operation, the operand of the
8609 // unary operation isn't a bitwise AND, or if the sizes of the operations
8610 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00008611 EVT VT = N->getValueType(0);
8612 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008613 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8614 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008615 return SDValue();
8616
Jim Grosbach724e4382014-07-23 20:41:43 +00008617 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00008618 // make the transformation for non-constant splats as well, but it's unclear
8619 // that would be a benefit as it would not eliminate any operations, just
8620 // perform one more step in scalar code before moving to the vector unit.
8621 if (BuildVectorSDNode *BV =
8622 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00008623 // Bail out if the vector isn't a constant.
8624 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008625 return SDValue();
8626
8627 // Everything checks out. Build up the new and improved node.
8628 SDLoc DL(N);
8629 EVT IntVT = BV->getValueType(0);
8630 // Create a new constant of the appropriate type for the transformed
8631 // DAG.
8632 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8633 // The AND node needs bitcasts to/from an integer vector type around it.
8634 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8635 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8636 N->getOperand(0)->getOperand(0), MaskConst);
8637 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8638 return Res;
8639 }
8640
8641 return SDValue();
8642}
8643
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008644static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8645 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00008646 // First try to optimize away the conversion when it's conditionally from
8647 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008648 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00008649 return Res;
8650
Tim Northover3b0846e2014-05-24 12:50:23 +00008651 EVT VT = N->getValueType(0);
8652 if (VT != MVT::f32 && VT != MVT::f64)
8653 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00008654
Tim Northover3b0846e2014-05-24 12:50:23 +00008655 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008656 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00008657 return SDValue();
8658
8659 // If the result of an integer load is only used by an integer-to-float
8660 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00008661 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00008662 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008663 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008664 // Do not change the width of a volatile load.
8665 !cast<LoadSDNode>(N0)->isVolatile()) {
8666 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8667 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00008668 LN0->getPointerInfo(), LN0->getAlignment(),
8669 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008670
8671 // Make sure successors of the original load stay after it by updating them
8672 // to use the new Chain.
8673 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8674
8675 unsigned Opcode =
8676 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8677 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8678 }
8679
8680 return SDValue();
8681}
8682
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008683/// Fold a floating-point multiply by power of two into floating-point to
8684/// fixed-point conversion.
8685static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00008686 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008687 const AArch64Subtarget *Subtarget) {
8688 if (!Subtarget->hasNEON())
8689 return SDValue();
8690
8691 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00008692 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8693 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008694 return SDValue();
8695
8696 SDValue ConstVec = Op->getOperand(1);
8697 if (!isa<BuildVectorSDNode>(ConstVec))
8698 return SDValue();
8699
8700 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8701 uint32_t FloatBits = FloatTy.getSizeInBits();
8702 if (FloatBits != 32 && FloatBits != 64)
8703 return SDValue();
8704
8705 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8706 uint32_t IntBits = IntTy.getSizeInBits();
8707 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8708 return SDValue();
8709
8710 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8711 if (IntBits > FloatBits)
8712 return SDValue();
8713
8714 BitVector UndefElements;
8715 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8716 int32_t Bits = IntBits == 64 ? 64 : 32;
8717 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8718 if (C == -1 || C == 0 || C > Bits)
8719 return SDValue();
8720
8721 MVT ResTy;
8722 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8723 switch (NumLanes) {
8724 default:
8725 return SDValue();
8726 case 2:
8727 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8728 break;
8729 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00008730 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008731 break;
8732 }
8733
Silviu Barangafa00ba32016-08-08 13:13:57 +00008734 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8735 return SDValue();
8736
8737 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8738 "Illegal vector type after legalization");
8739
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008740 SDLoc DL(N);
8741 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8742 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8743 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8744 SDValue FixConv =
8745 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8746 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8747 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8748 // We can handle smaller integers by generating an extra trunc.
8749 if (IntBits < FloatBits)
8750 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8751
8752 return FixConv;
8753}
8754
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008755/// Fold a floating-point divide by power of two into fixed-point to
8756/// floating-point conversion.
8757static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00008758 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008759 const AArch64Subtarget *Subtarget) {
8760 if (!Subtarget->hasNEON())
8761 return SDValue();
8762
8763 SDValue Op = N->getOperand(0);
8764 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00008765 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8766 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008767 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8768 return SDValue();
8769
8770 SDValue ConstVec = N->getOperand(1);
8771 if (!isa<BuildVectorSDNode>(ConstVec))
8772 return SDValue();
8773
8774 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8775 int32_t IntBits = IntTy.getSizeInBits();
8776 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8777 return SDValue();
8778
8779 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8780 int32_t FloatBits = FloatTy.getSizeInBits();
8781 if (FloatBits != 32 && FloatBits != 64)
8782 return SDValue();
8783
8784 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8785 if (IntBits > FloatBits)
8786 return SDValue();
8787
8788 BitVector UndefElements;
8789 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8790 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8791 if (C == -1 || C == 0 || C > FloatBits)
8792 return SDValue();
8793
8794 MVT ResTy;
8795 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8796 switch (NumLanes) {
8797 default:
8798 return SDValue();
8799 case 2:
8800 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8801 break;
8802 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00008803 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008804 break;
8805 }
8806
Tim Northover85cf5642016-08-26 18:52:31 +00008807 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8808 return SDValue();
8809
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008810 SDLoc DL(N);
8811 SDValue ConvInput = Op.getOperand(0);
8812 bool IsSigned = Opc == ISD::SINT_TO_FP;
8813 if (IntBits < FloatBits)
8814 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8815 ResTy, ConvInput);
8816
8817 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8818 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8819 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8820 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8821 DAG.getConstant(C, DL, MVT::i32));
8822}
8823
Tim Northover3b0846e2014-05-24 12:50:23 +00008824/// An EXTR instruction is made up of two shifts, ORed together. This helper
8825/// searches for and classifies those shifts.
8826static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8827 bool &FromHi) {
8828 if (N.getOpcode() == ISD::SHL)
8829 FromHi = false;
8830 else if (N.getOpcode() == ISD::SRL)
8831 FromHi = true;
8832 else
8833 return false;
8834
8835 if (!isa<ConstantSDNode>(N.getOperand(1)))
8836 return false;
8837
8838 ShiftAmount = N->getConstantOperandVal(1);
8839 Src = N->getOperand(0);
8840 return true;
8841}
8842
8843/// EXTR instruction extracts a contiguous chunk of bits from two existing
8844/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00008845/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
8846/// with an EXTR. Can't quite be done in TableGen because the two immediates
8847/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00008848static SDValue tryCombineToEXTR(SDNode *N,
8849 TargetLowering::DAGCombinerInfo &DCI) {
8850 SelectionDAG &DAG = DCI.DAG;
8851 SDLoc DL(N);
8852 EVT VT = N->getValueType(0);
8853
8854 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8855
8856 if (VT != MVT::i32 && VT != MVT::i64)
8857 return SDValue();
8858
8859 SDValue LHS;
8860 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008861 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008862 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8863 return SDValue();
8864
8865 SDValue RHS;
8866 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008867 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008868 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8869 return SDValue();
8870
8871 // If they're both trying to come from the high part of the register, they're
8872 // not really an EXTR.
8873 if (LHSFromHi == RHSFromHi)
8874 return SDValue();
8875
8876 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8877 return SDValue();
8878
8879 if (LHSFromHi) {
8880 std::swap(LHS, RHS);
8881 std::swap(ShiftLHS, ShiftRHS);
8882 }
8883
8884 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008885 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008886}
8887
8888static SDValue tryCombineToBSL(SDNode *N,
8889 TargetLowering::DAGCombinerInfo &DCI) {
8890 EVT VT = N->getValueType(0);
8891 SelectionDAG &DAG = DCI.DAG;
8892 SDLoc DL(N);
8893
8894 if (!VT.isVector())
8895 return SDValue();
8896
8897 SDValue N0 = N->getOperand(0);
8898 if (N0.getOpcode() != ISD::AND)
8899 return SDValue();
8900
8901 SDValue N1 = N->getOperand(1);
8902 if (N1.getOpcode() != ISD::AND)
8903 return SDValue();
8904
8905 // We only have to look for constant vectors here since the general, variable
8906 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008907 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008908 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8909 for (int i = 1; i >= 0; --i)
8910 for (int j = 1; j >= 0; --j) {
8911 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8912 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8913 if (!BVN0 || !BVN1)
8914 continue;
8915
8916 bool FoundMatch = true;
8917 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8918 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8919 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8920 if (!CN0 || !CN1 ||
8921 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8922 FoundMatch = false;
8923 break;
8924 }
8925 }
8926
8927 if (FoundMatch)
8928 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8929 N0->getOperand(1 - i), N1->getOperand(1 - j));
8930 }
8931
8932 return SDValue();
8933}
8934
8935static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8936 const AArch64Subtarget *Subtarget) {
8937 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00008938 SelectionDAG &DAG = DCI.DAG;
8939 EVT VT = N->getValueType(0);
8940
8941 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8942 return SDValue();
8943
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008944 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008945 return Res;
8946
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008947 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008948 return Res;
8949
8950 return SDValue();
8951}
8952
Chad Rosier14aa2ad2016-05-26 19:41:33 +00008953static SDValue performSRLCombine(SDNode *N,
8954 TargetLowering::DAGCombinerInfo &DCI) {
8955 SelectionDAG &DAG = DCI.DAG;
8956 EVT VT = N->getValueType(0);
8957 if (VT != MVT::i32 && VT != MVT::i64)
8958 return SDValue();
8959
8960 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8961 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8962 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8963 SDValue N0 = N->getOperand(0);
8964 if (N0.getOpcode() == ISD::BSWAP) {
8965 SDLoc DL(N);
8966 SDValue N1 = N->getOperand(1);
8967 SDValue N00 = N0.getOperand(0);
8968 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8969 uint64_t ShiftAmt = C->getZExtValue();
8970 if (VT == MVT::i32 && ShiftAmt == 16 &&
8971 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8972 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8973 if (VT == MVT::i64 && ShiftAmt == 32 &&
8974 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8975 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8976 }
8977 }
8978 return SDValue();
8979}
8980
Tim Northover3b0846e2014-05-24 12:50:23 +00008981static SDValue performBitcastCombine(SDNode *N,
8982 TargetLowering::DAGCombinerInfo &DCI,
8983 SelectionDAG &DAG) {
8984 // Wait 'til after everything is legalized to try this. That way we have
8985 // legal vector types and such.
8986 if (DCI.isBeforeLegalizeOps())
8987 return SDValue();
8988
8989 // Remove extraneous bitcasts around an extract_subvector.
8990 // For example,
8991 // (v4i16 (bitconvert
8992 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8993 // becomes
8994 // (extract_subvector ((v8i16 ...), (i64 4)))
8995
8996 // Only interested in 64-bit vectors as the ultimate result.
8997 EVT VT = N->getValueType(0);
8998 if (!VT.isVector())
8999 return SDValue();
9000 if (VT.getSimpleVT().getSizeInBits() != 64)
9001 return SDValue();
9002 // Is the operand an extract_subvector starting at the beginning or halfway
9003 // point of the vector? A low half may also come through as an
9004 // EXTRACT_SUBREG, so look for that, too.
9005 SDValue Op0 = N->getOperand(0);
9006 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9007 !(Op0->isMachineOpcode() &&
9008 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9009 return SDValue();
9010 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9011 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9012 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9013 return SDValue();
9014 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9015 if (idx != AArch64::dsub)
9016 return SDValue();
9017 // The dsub reference is equivalent to a lane zero subvector reference.
9018 idx = 0;
9019 }
9020 // Look through the bitcast of the input to the extract.
9021 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9022 return SDValue();
9023 SDValue Source = Op0->getOperand(0)->getOperand(0);
9024 // If the source type has twice the number of elements as our destination
9025 // type, we know this is an extract of the high or low half of the vector.
9026 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009027 if (!SVT.isVector() ||
9028 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009029 return SDValue();
9030
9031 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9032
9033 // Create the simplified form to just extract the low or high half of the
9034 // vector directly rather than bothering with the bitcasts.
9035 SDLoc dl(N);
9036 unsigned NumElements = VT.getVectorNumElements();
9037 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009038 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009039 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9040 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009041 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009042 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9043 Source, SubReg),
9044 0);
9045 }
9046}
9047
9048static SDValue performConcatVectorsCombine(SDNode *N,
9049 TargetLowering::DAGCombinerInfo &DCI,
9050 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009051 SDLoc dl(N);
9052 EVT VT = N->getValueType(0);
9053 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9054
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009055 // Optimize concat_vectors of truncated vectors, where the intermediate
9056 // type is illegal, to avoid said illegality, e.g.,
9057 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9058 // (v2i16 (truncate (v2i64)))))
9059 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009060 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9061 // (v4i32 (bitcast (v2i64))),
9062 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009063 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9064 // on both input and result type, so we might generate worse code.
9065 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9066 if (N->getNumOperands() == 2 &&
9067 N0->getOpcode() == ISD::TRUNCATE &&
9068 N1->getOpcode() == ISD::TRUNCATE) {
9069 SDValue N00 = N0->getOperand(0);
9070 SDValue N10 = N1->getOperand(0);
9071 EVT N00VT = N00.getValueType();
9072
9073 if (N00VT == N10.getValueType() &&
9074 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9075 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009076 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9077 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9078 for (size_t i = 0; i < Mask.size(); ++i)
9079 Mask[i] = i * 2;
9080 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9081 DAG.getVectorShuffle(
9082 MidVT, dl,
9083 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9084 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009085 }
9086 }
9087
Tim Northover3b0846e2014-05-24 12:50:23 +00009088 // Wait 'til after everything is legalized to try this. That way we have
9089 // legal vector types and such.
9090 if (DCI.isBeforeLegalizeOps())
9091 return SDValue();
9092
Tim Northover3b0846e2014-05-24 12:50:23 +00009093 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9094 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9095 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009096 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009097 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009098 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009099 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009100 }
9101
9102 // Canonicalise concat_vectors so that the right-hand vector has as few
9103 // bit-casts as possible before its real operation. The primary matching
9104 // destination for these operations will be the narrowing "2" instructions,
9105 // which depend on the operation being performed on this right-hand vector.
9106 // For example,
9107 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9108 // becomes
9109 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9110
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009111 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009112 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009113 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009114 MVT RHSTy = RHS.getValueType().getSimpleVT();
9115 // If the RHS is not a vector, this is not the pattern we're looking for.
9116 if (!RHSTy.isVector())
9117 return SDValue();
9118
9119 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9120
9121 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9122 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009123 return DAG.getNode(ISD::BITCAST, dl, VT,
9124 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9125 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9126 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009127}
9128
9129static SDValue tryCombineFixedPointConvert(SDNode *N,
9130 TargetLowering::DAGCombinerInfo &DCI,
9131 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009132 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009133 // legal vector types and such.
9134 if (DCI.isBeforeLegalizeOps())
9135 return SDValue();
9136 // Transform a scalar conversion of a value from a lane extract into a
9137 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9138 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9139 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9140 //
9141 // The second form interacts better with instruction selection and the
9142 // register allocator to avoid cross-class register copies that aren't
9143 // coalescable due to a lane reference.
9144
9145 // Check the operand and see if it originates from a lane extract.
9146 SDValue Op1 = N->getOperand(1);
9147 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9148 // Yep, no additional predication needed. Perform the transform.
9149 SDValue IID = N->getOperand(0);
9150 SDValue Shift = N->getOperand(2);
9151 SDValue Vec = Op1.getOperand(0);
9152 SDValue Lane = Op1.getOperand(1);
9153 EVT ResTy = N->getValueType(0);
9154 EVT VecResTy;
9155 SDLoc DL(N);
9156
9157 // The vector width should be 128 bits by the time we get here, even
9158 // if it started as 64 bits (the extract_vector handling will have
9159 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009160 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009161 "unexpected vector size on extract_vector_elt!");
9162 if (Vec.getValueType() == MVT::v4i32)
9163 VecResTy = MVT::v4f32;
9164 else if (Vec.getValueType() == MVT::v2i64)
9165 VecResTy = MVT::v2f64;
9166 else
Craig Topper2a30d782014-06-18 05:05:13 +00009167 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009168
9169 SDValue Convert =
9170 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9171 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9172 }
9173 return SDValue();
9174}
9175
9176// AArch64 high-vector "long" operations are formed by performing the non-high
9177// version on an extract_subvector of each operand which gets the high half:
9178//
9179// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9180//
9181// However, there are cases which don't have an extract_high explicitly, but
9182// have another operation that can be made compatible with one for free. For
9183// example:
9184//
9185// (dupv64 scalar) --> (extract_high (dup128 scalar))
9186//
9187// This routine does the actual conversion of such DUPs, once outer routines
9188// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009189// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9190// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009191static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009192 switch (N.getOpcode()) {
9193 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009194 case AArch64ISD::DUPLANE8:
9195 case AArch64ISD::DUPLANE16:
9196 case AArch64ISD::DUPLANE32:
9197 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009198 case AArch64ISD::MOVI:
9199 case AArch64ISD::MOVIshift:
9200 case AArch64ISD::MOVIedit:
9201 case AArch64ISD::MOVImsl:
9202 case AArch64ISD::MVNIshift:
9203 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009204 break;
9205 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009206 // FMOV could be supported, but isn't very useful, as it would only occur
9207 // if you passed a bitcast' floating point immediate to an eligible long
9208 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009209 return SDValue();
9210 }
9211
9212 MVT NarrowTy = N.getSimpleValueType();
9213 if (!NarrowTy.is64BitVector())
9214 return SDValue();
9215
9216 MVT ElementTy = NarrowTy.getVectorElementType();
9217 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009218 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009219
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009220 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009221 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9222 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009223 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009224}
9225
9226static bool isEssentiallyExtractSubvector(SDValue N) {
9227 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9228 return true;
9229
9230 return N.getOpcode() == ISD::BITCAST &&
9231 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9232}
9233
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009234/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009235struct GenericSetCCInfo {
9236 const SDValue *Opnd0;
9237 const SDValue *Opnd1;
9238 ISD::CondCode CC;
9239};
9240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009241/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009242struct AArch64SetCCInfo {
9243 const SDValue *Cmp;
9244 AArch64CC::CondCode CC;
9245};
9246
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009247/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009248union SetCCInfo {
9249 GenericSetCCInfo Generic;
9250 AArch64SetCCInfo AArch64;
9251};
9252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009253/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009254/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9255/// GenericSetCCInfo.
9256struct SetCCInfoAndKind {
9257 SetCCInfo Info;
9258 bool IsAArch64;
9259};
9260
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009261/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009262/// an
9263/// AArch64 lowered one.
9264/// \p SetCCInfo is filled accordingly.
9265/// \post SetCCInfo is meanginfull only when this function returns true.
9266/// \return True when Op is a kind of SET_CC operation.
9267static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9268 // If this is a setcc, this is straight forward.
9269 if (Op.getOpcode() == ISD::SETCC) {
9270 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9271 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9272 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9273 SetCCInfo.IsAArch64 = false;
9274 return true;
9275 }
9276 // Otherwise, check if this is a matching csel instruction.
9277 // In other words:
9278 // - csel 1, 0, cc
9279 // - csel 0, 1, !cc
9280 if (Op.getOpcode() != AArch64ISD::CSEL)
9281 return false;
9282 // Set the information about the operands.
9283 // TODO: we want the operands of the Cmp not the csel
9284 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9285 SetCCInfo.IsAArch64 = true;
9286 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9287 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9288
9289 // Check that the operands matches the constraints:
9290 // (1) Both operands must be constants.
9291 // (2) One must be 1 and the other must be 0.
9292 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9293 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9294
9295 // Check (1).
9296 if (!TValue || !FValue)
9297 return false;
9298
9299 // Check (2).
9300 if (!TValue->isOne()) {
9301 // Update the comparison when we are interested in !cc.
9302 std::swap(TValue, FValue);
9303 SetCCInfo.Info.AArch64.CC =
9304 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9305 }
9306 return TValue->isOne() && FValue->isNullValue();
9307}
9308
9309// Returns true if Op is setcc or zext of setcc.
9310static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9311 if (isSetCC(Op, Info))
9312 return true;
9313 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9314 isSetCC(Op->getOperand(0), Info));
9315}
9316
9317// The folding we want to perform is:
9318// (add x, [zext] (setcc cc ...) )
9319// -->
9320// (csel x, (add x, 1), !cc ...)
9321//
9322// The latter will get matched to a CSINC instruction.
9323static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9324 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9325 SDValue LHS = Op->getOperand(0);
9326 SDValue RHS = Op->getOperand(1);
9327 SetCCInfoAndKind InfoAndKind;
9328
9329 // If neither operand is a SET_CC, give up.
9330 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9331 std::swap(LHS, RHS);
9332 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9333 return SDValue();
9334 }
9335
9336 // FIXME: This could be generatized to work for FP comparisons.
9337 EVT CmpVT = InfoAndKind.IsAArch64
9338 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9339 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9340 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9341 return SDValue();
9342
9343 SDValue CCVal;
9344 SDValue Cmp;
9345 SDLoc dl(Op);
9346 if (InfoAndKind.IsAArch64) {
9347 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009348 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9349 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009350 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9351 } else
9352 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9353 *InfoAndKind.Info.Generic.Opnd1,
9354 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9355 CCVal, DAG, dl);
9356
9357 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009358 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009359 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9360}
9361
9362// The basic add/sub long vector instructions have variants with "2" on the end
9363// which act on the high-half of their inputs. They are normally matched by
9364// patterns like:
9365//
9366// (add (zeroext (extract_high LHS)),
9367// (zeroext (extract_high RHS)))
9368// -> uaddl2 vD, vN, vM
9369//
9370// However, if one of the extracts is something like a duplicate, this
9371// instruction can still be used profitably. This function puts the DAG into a
9372// more appropriate form for those patterns to trigger.
9373static SDValue performAddSubLongCombine(SDNode *N,
9374 TargetLowering::DAGCombinerInfo &DCI,
9375 SelectionDAG &DAG) {
9376 if (DCI.isBeforeLegalizeOps())
9377 return SDValue();
9378
9379 MVT VT = N->getSimpleValueType(0);
9380 if (!VT.is128BitVector()) {
9381 if (N->getOpcode() == ISD::ADD)
9382 return performSetccAddFolding(N, DAG);
9383 return SDValue();
9384 }
9385
9386 // Make sure both branches are extended in the same way.
9387 SDValue LHS = N->getOperand(0);
9388 SDValue RHS = N->getOperand(1);
9389 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9390 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9391 LHS.getOpcode() != RHS.getOpcode())
9392 return SDValue();
9393
9394 unsigned ExtType = LHS.getOpcode();
9395
9396 // It's not worth doing if at least one of the inputs isn't already an
9397 // extract, but we don't know which it'll be so we have to try both.
9398 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9399 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9400 if (!RHS.getNode())
9401 return SDValue();
9402
9403 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9404 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9405 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9406 if (!LHS.getNode())
9407 return SDValue();
9408
9409 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9410 }
9411
9412 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9413}
9414
9415// Massage DAGs which we can use the high-half "long" operations on into
9416// something isel will recognize better. E.g.
9417//
9418// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9419// (aarch64_neon_umull (extract_high (v2i64 vec)))
9420// (extract_high (v2i64 (dup128 scalar)))))
9421//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009422static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009423 TargetLowering::DAGCombinerInfo &DCI,
9424 SelectionDAG &DAG) {
9425 if (DCI.isBeforeLegalizeOps())
9426 return SDValue();
9427
Hal Finkelcd8664c2015-12-11 23:11:52 +00009428 SDValue LHS = N->getOperand(1);
9429 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009430 assert(LHS.getValueType().is64BitVector() &&
9431 RHS.getValueType().is64BitVector() &&
9432 "unexpected shape for long operation");
9433
9434 // Either node could be a DUP, but it's not worth doing both of them (you'd
9435 // just as well use the non-high version) so look for a corresponding extract
9436 // operation on the other "wing".
9437 if (isEssentiallyExtractSubvector(LHS)) {
9438 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9439 if (!RHS.getNode())
9440 return SDValue();
9441 } else if (isEssentiallyExtractSubvector(RHS)) {
9442 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9443 if (!LHS.getNode())
9444 return SDValue();
9445 }
9446
Hal Finkelcd8664c2015-12-11 23:11:52 +00009447 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9448 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009449}
9450
9451static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9452 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9453 unsigned ElemBits = ElemTy.getSizeInBits();
9454
9455 int64_t ShiftAmount;
9456 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9457 APInt SplatValue, SplatUndef;
9458 unsigned SplatBitSize;
9459 bool HasAnyUndefs;
9460 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9461 HasAnyUndefs, ElemBits) ||
9462 SplatBitSize != ElemBits)
9463 return SDValue();
9464
9465 ShiftAmount = SplatValue.getSExtValue();
9466 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9467 ShiftAmount = CVN->getSExtValue();
9468 } else
9469 return SDValue();
9470
9471 unsigned Opcode;
9472 bool IsRightShift;
9473 switch (IID) {
9474 default:
9475 llvm_unreachable("Unknown shift intrinsic");
9476 case Intrinsic::aarch64_neon_sqshl:
9477 Opcode = AArch64ISD::SQSHL_I;
9478 IsRightShift = false;
9479 break;
9480 case Intrinsic::aarch64_neon_uqshl:
9481 Opcode = AArch64ISD::UQSHL_I;
9482 IsRightShift = false;
9483 break;
9484 case Intrinsic::aarch64_neon_srshl:
9485 Opcode = AArch64ISD::SRSHR_I;
9486 IsRightShift = true;
9487 break;
9488 case Intrinsic::aarch64_neon_urshl:
9489 Opcode = AArch64ISD::URSHR_I;
9490 IsRightShift = true;
9491 break;
9492 case Intrinsic::aarch64_neon_sqshlu:
9493 Opcode = AArch64ISD::SQSHLU_I;
9494 IsRightShift = false;
9495 break;
9496 }
9497
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009498 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9499 SDLoc dl(N);
9500 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9501 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9502 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9503 SDLoc dl(N);
9504 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9505 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9506 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009507
9508 return SDValue();
9509}
9510
9511// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9512// the intrinsics must be legal and take an i32, this means there's almost
9513// certainly going to be a zext in the DAG which we can eliminate.
9514static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9515 SDValue AndN = N->getOperand(2);
9516 if (AndN.getOpcode() != ISD::AND)
9517 return SDValue();
9518
9519 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9520 if (!CMask || CMask->getZExtValue() != Mask)
9521 return SDValue();
9522
9523 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9524 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9525}
9526
Ahmed Bougachafab58922015-03-10 20:45:38 +00009527static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9528 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009529 SDLoc dl(N);
9530 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9531 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009532 N->getOperand(1).getSimpleValueType(),
9533 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009534 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009535}
9536
Tim Northover3b0846e2014-05-24 12:50:23 +00009537static SDValue performIntrinsicCombine(SDNode *N,
9538 TargetLowering::DAGCombinerInfo &DCI,
9539 const AArch64Subtarget *Subtarget) {
9540 SelectionDAG &DAG = DCI.DAG;
9541 unsigned IID = getIntrinsicID(N);
9542 switch (IID) {
9543 default:
9544 break;
9545 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9546 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9547 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00009548 case Intrinsic::aarch64_neon_saddv:
9549 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9550 case Intrinsic::aarch64_neon_uaddv:
9551 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9552 case Intrinsic::aarch64_neon_sminv:
9553 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9554 case Intrinsic::aarch64_neon_uminv:
9555 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9556 case Intrinsic::aarch64_neon_smaxv:
9557 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9558 case Intrinsic::aarch64_neon_umaxv:
9559 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009560 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00009561 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009562 N->getOperand(1), N->getOperand(2));
9563 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00009564 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009565 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00009566 case Intrinsic::aarch64_neon_fmaxnm:
9567 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9568 N->getOperand(1), N->getOperand(2));
9569 case Intrinsic::aarch64_neon_fminnm:
9570 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9571 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009572 case Intrinsic::aarch64_neon_smull:
9573 case Intrinsic::aarch64_neon_umull:
9574 case Intrinsic::aarch64_neon_pmull:
9575 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00009576 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009577 case Intrinsic::aarch64_neon_sqshl:
9578 case Intrinsic::aarch64_neon_uqshl:
9579 case Intrinsic::aarch64_neon_sqshlu:
9580 case Intrinsic::aarch64_neon_srshl:
9581 case Intrinsic::aarch64_neon_urshl:
9582 return tryCombineShiftImm(IID, N, DAG);
9583 case Intrinsic::aarch64_crc32b:
9584 case Intrinsic::aarch64_crc32cb:
9585 return tryCombineCRC32(0xff, N, DAG);
9586 case Intrinsic::aarch64_crc32h:
9587 case Intrinsic::aarch64_crc32ch:
9588 return tryCombineCRC32(0xffff, N, DAG);
9589 }
9590 return SDValue();
9591}
9592
9593static SDValue performExtendCombine(SDNode *N,
9594 TargetLowering::DAGCombinerInfo &DCI,
9595 SelectionDAG &DAG) {
9596 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9597 // we can convert that DUP into another extract_high (of a bigger DUP), which
9598 // helps the backend to decide that an sabdl2 would be useful, saving a real
9599 // extract_high operation.
9600 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00009601 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009602 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00009603 unsigned IID = getIntrinsicID(ABDNode);
9604 if (IID == Intrinsic::aarch64_neon_sabd ||
9605 IID == Intrinsic::aarch64_neon_uabd) {
9606 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9607 if (!NewABD.getNode())
9608 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009609
Hal Finkelcd8664c2015-12-11 23:11:52 +00009610 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9611 NewABD);
9612 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009613 }
9614
9615 // This is effectively a custom type legalization for AArch64.
9616 //
9617 // Type legalization will split an extend of a small, legal, type to a larger
9618 // illegal type by first splitting the destination type, often creating
9619 // illegal source types, which then get legalized in isel-confusing ways,
9620 // leading to really terrible codegen. E.g.,
9621 // %result = v8i32 sext v8i8 %value
9622 // becomes
9623 // %losrc = extract_subreg %value, ...
9624 // %hisrc = extract_subreg %value, ...
9625 // %lo = v4i32 sext v4i8 %losrc
9626 // %hi = v4i32 sext v4i8 %hisrc
9627 // Things go rapidly downhill from there.
9628 //
9629 // For AArch64, the [sz]ext vector instructions can only go up one element
9630 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9631 // take two instructions.
9632 //
9633 // This implies that the most efficient way to do the extend from v8i8
9634 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9635 // the normal splitting to happen for the v8i16->v8i32.
9636
9637 // This is pre-legalization to catch some cases where the default
9638 // type legalization will create ill-tempered code.
9639 if (!DCI.isBeforeLegalizeOps())
9640 return SDValue();
9641
9642 // We're only interested in cleaning things up for non-legal vector types
9643 // here. If both the source and destination are legal, things will just
9644 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00009645 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00009646 EVT ResVT = N->getValueType(0);
9647 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9648 return SDValue();
9649 // If the vector type isn't a simple VT, it's beyond the scope of what
9650 // we're worried about here. Let legalization do its thing and hope for
9651 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00009652 SDValue Src = N->getOperand(0);
9653 EVT SrcVT = Src->getValueType(0);
9654 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00009655 return SDValue();
9656
Tim Northover3b0846e2014-05-24 12:50:23 +00009657 // If the source VT is a 64-bit vector, we can play games and get the
9658 // better results we want.
9659 if (SrcVT.getSizeInBits() != 64)
9660 return SDValue();
9661
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009662 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009663 unsigned ElementCount = SrcVT.getVectorNumElements();
9664 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9665 SDLoc DL(N);
9666 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9667
9668 // Now split the rest of the operation into two halves, each with a 64
9669 // bit source.
9670 EVT LoVT, HiVT;
9671 SDValue Lo, Hi;
9672 unsigned NumElements = ResVT.getVectorNumElements();
9673 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9674 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9675 ResVT.getVectorElementType(), NumElements / 2);
9676
9677 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9678 LoVT.getVectorNumElements());
9679 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009680 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009681 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009682 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009683 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9684 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9685
9686 // Now combine the parts back together so we still have a single result
9687 // like the combiner expects.
9688 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9689}
9690
Geoff Berry8301c642016-11-16 19:35:19 +00009691static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9692 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009693 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +00009694 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009695
9696 // Create scalar stores. This is at least as good as the code sequence for a
9697 // split unaligned store which is a dup.s, ext.b, and two stores.
9698 // Most of the time the three stores should be replaced by store pair
9699 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009700 SDLoc DL(&St);
9701 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009702 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +00009703
John Brawn3a9c8422017-02-06 18:07:20 +00009704 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009705 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +00009706 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +00009707 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009708
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009709 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +00009710 if (BasePtr->getOpcode() == ISD::ADD &&
9711 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9712 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9713 BasePtr = BasePtr->getOperand(0);
9714 }
9715
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009716 unsigned Offset = EltOffset;
9717 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +00009718 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009719 SDValue OffsetPtr =
9720 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9721 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009722 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +00009723 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009724 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009725 Offset += EltOffset;
9726 }
9727 return NewST1;
9728}
9729
Geoff Berry526c5052016-11-14 19:39:04 +00009730/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9731/// load store optimizer pass will merge them to store pair stores. This should
9732/// be better than a movi to create the vector zero followed by a vector store
9733/// if the zero constant is not re-used, since one instructions and one register
9734/// live range will be removed.
9735///
9736/// For example, the final generated code should be:
9737///
9738/// stp xzr, xzr, [x0]
9739///
9740/// instead of:
9741///
9742/// movi v0.2d, #0
9743/// str q0, [x0]
9744///
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009745static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9746 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +00009747 EVT VT = StVal.getValueType();
9748
Geoff Berry8301c642016-11-16 19:35:19 +00009749 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9750 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +00009751 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +00009752 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9753 VT.getVectorElementType().getSizeInBits() == 64) ||
9754 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9755 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +00009756 return SDValue();
9757
9758 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9759 return SDValue();
9760
9761 // If the zero constant has more than one use then the vector store could be
9762 // better since the constant mov will be amortized and stp q instructions
9763 // should be able to be formed.
9764 if (!StVal.hasOneUse())
9765 return SDValue();
9766
9767 // If the immediate offset of the address operand is too large for the stp
9768 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009769 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9770 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +00009771 if (Offset < -512 || Offset > 504)
9772 return SDValue();
9773 }
9774
9775 for (int I = 0; I < NumVecElts; ++I) {
9776 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +00009777 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +00009778 return SDValue();
9779 }
Geoff Berry8301c642016-11-16 19:35:19 +00009780
Geoff Berrybb23df92017-09-21 21:10:06 +00009781 // Use a CopyFromReg WZR/XZR here to prevent
9782 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
9783 SDLoc DL(&St);
9784 unsigned ZeroReg;
9785 EVT ZeroVT;
9786 if (VT.getVectorElementType().getSizeInBits() == 32) {
9787 ZeroReg = AArch64::WZR;
9788 ZeroVT = MVT::i32;
9789 } else {
9790 ZeroReg = AArch64::XZR;
9791 ZeroVT = MVT::i64;
9792 }
9793 SDValue SplatVal =
9794 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +00009795 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +00009796}
9797
Tim Northover3b0846e2014-05-24 12:50:23 +00009798/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9799/// value. The load store optimizer pass will merge them to store pair stores.
9800/// This has better performance than a splat of the scalar followed by a split
9801/// vector store. Even if the stores are not merged it is four stores vs a dup,
9802/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009803static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9804 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009805 EVT VT = StVal.getValueType();
9806
9807 // Don't replace floating point stores, they possibly won't be transformed to
9808 // stp because of the store pair suppress pass.
9809 if (VT.isFloatingPoint())
9810 return SDValue();
9811
Tim Northover3b0846e2014-05-24 12:50:23 +00009812 // We can express a splat as store pair(s) for 2 or 4 elements.
9813 unsigned NumVecElts = VT.getVectorNumElements();
9814 if (NumVecElts != 4 && NumVecElts != 2)
9815 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009816
9817 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +00009818 // Make sure that each of the relevant vector element locations are inserted
9819 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9820 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9821 SDValue SplatVal;
9822 for (unsigned I = 0; I < NumVecElts; ++I) {
9823 // Check for insert vector elements.
9824 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +00009825 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009826
9827 // Check that same value is inserted at each vector element.
9828 if (I == 0)
9829 SplatVal = StVal.getOperand(1);
9830 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +00009831 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009832
9833 // Check insert element index.
9834 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9835 if (!CIndex)
9836 return SDValue();
9837 uint64_t IndexVal = CIndex->getZExtValue();
9838 if (IndexVal >= NumVecElts)
9839 return SDValue();
9840 IndexNotInserted.reset(IndexVal);
9841
9842 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009843 }
Geoff Berry25fa4992016-11-11 19:25:20 +00009844 // Check that all vector element locations were inserted to.
9845 if (IndexNotInserted.any())
9846 return SDValue();
9847
Geoff Berry8301c642016-11-16 19:35:19 +00009848 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009849}
9850
Geoff Berry8301c642016-11-16 19:35:19 +00009851static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9852 SelectionDAG &DAG,
9853 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009854
9855 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +00009856 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +00009857 return SDValue();
9858
Geoff Berry526c5052016-11-14 19:39:04 +00009859 SDValue StVal = S->getValue();
9860 EVT VT = StVal.getValueType();
9861 if (!VT.isVector())
9862 return SDValue();
9863
9864 // If we get a splat of zeros, convert this vector store to a store of
9865 // scalars. They will be merged into store pairs of xzr thereby removing one
9866 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009867 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +00009868 return ReplacedZeroSplat;
9869
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00009870 // FIXME: The logic for deciding if an unaligned store should be split should
9871 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9872 // a call to that function here.
9873
Matthias Braun651cff42016-06-02 18:03:53 +00009874 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00009875 return SDValue();
9876
Sanjay Patel924879a2015-08-04 15:49:57 +00009877 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +00009878 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00009879 return SDValue();
9880
Tim Northover3b0846e2014-05-24 12:50:23 +00009881 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9882 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +00009883 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +00009884 return SDValue();
9885
9886 // Split unaligned 16B stores. They are terrible for performance.
9887 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9888 // extensions can use this to mark that it does not want splitting to happen
9889 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9890 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9891 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9892 S->getAlignment() <= 2)
9893 return SDValue();
9894
9895 // If we get a splat of a scalar convert this vector store to a store of
9896 // scalars. They will be merged into store pairs thereby removing two
9897 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009898 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +00009899 return ReplacedSplat;
9900
9901 SDLoc DL(S);
9902 unsigned NumElts = VT.getVectorNumElements() / 2;
9903 // Split VT into two.
9904 EVT HalfVT =
9905 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9906 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009907 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009908 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009909 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009910 SDValue BasePtr = S->getBasePtr();
9911 SDValue NewST1 =
9912 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00009913 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009914 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009915 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009916 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00009917 S->getPointerInfo(), S->getAlignment(),
9918 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009919}
9920
9921/// Target-specific DAG combine function for post-increment LD1 (lane) and
9922/// post-increment LD1R.
9923static SDValue performPostLD1Combine(SDNode *N,
9924 TargetLowering::DAGCombinerInfo &DCI,
9925 bool IsLaneOp) {
9926 if (DCI.isBeforeLegalizeOps())
9927 return SDValue();
9928
9929 SelectionDAG &DAG = DCI.DAG;
9930 EVT VT = N->getValueType(0);
9931
9932 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9933 SDNode *LD = N->getOperand(LoadIdx).getNode();
9934 // If it is not LOAD, can not do such combine.
9935 if (LD->getOpcode() != ISD::LOAD)
9936 return SDValue();
9937
9938 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9939 EVT MemVT = LoadSDN->getMemoryVT();
9940 // Check if memory operand is the same type as the vector element.
9941 if (MemVT != VT.getVectorElementType())
9942 return SDValue();
9943
9944 // Check if there are other uses. If so, do not combine as it will introduce
9945 // an extra load.
9946 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9947 ++UI) {
9948 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9949 continue;
9950 if (*UI != N)
9951 return SDValue();
9952 }
9953
9954 SDValue Addr = LD->getOperand(1);
9955 SDValue Vector = N->getOperand(0);
9956 // Search for a use of the address operand that is an increment.
9957 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9958 Addr.getNode()->use_end(); UI != UE; ++UI) {
9959 SDNode *User = *UI;
9960 if (User->getOpcode() != ISD::ADD
9961 || UI.getUse().getResNo() != Addr.getResNo())
9962 continue;
9963
9964 // Check that the add is independent of the load. Otherwise, folding it
9965 // would create a cycle.
9966 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9967 continue;
9968 // Also check that add is not used in the vector operand. This would also
9969 // create a cycle.
9970 if (User->isPredecessorOf(Vector.getNode()))
9971 continue;
9972
9973 // If the increment is a constant, it must match the memory ref size.
9974 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9975 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9976 uint32_t IncVal = CInc->getZExtValue();
9977 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9978 if (IncVal != NumBytes)
9979 continue;
9980 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9981 }
9982
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00009983 // Finally, check that the vector doesn't depend on the load.
9984 // Again, this would create a cycle.
9985 // The load depending on the vector is fine, as that's the case for the
9986 // LD1*post we'll eventually generate anyway.
9987 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9988 continue;
9989
Tim Northover3b0846e2014-05-24 12:50:23 +00009990 SmallVector<SDValue, 8> Ops;
9991 Ops.push_back(LD->getOperand(0)); // Chain
9992 if (IsLaneOp) {
9993 Ops.push_back(Vector); // The vector to be inserted
9994 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9995 }
9996 Ops.push_back(Addr);
9997 Ops.push_back(Inc);
9998
9999 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010000 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010001 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10002 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10003 MemVT,
10004 LoadSDN->getMemOperand());
10005
10006 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010007 SDValue NewResults[] = {
10008 SDValue(LD, 0), // The result of load
10009 SDValue(UpdN.getNode(), 2) // Chain
10010 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010011 DCI.CombineTo(LD, NewResults);
10012 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10013 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10014
10015 break;
10016 }
10017 return SDValue();
10018}
10019
Joel Jones7466ccf2017-07-10 22:11:50 +000010020/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010021/// address translation.
10022static bool performTBISimplification(SDValue Addr,
10023 TargetLowering::DAGCombinerInfo &DCI,
10024 SelectionDAG &DAG) {
10025 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010026 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010027 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10028 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010029 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010030 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010031 DCI.CommitTargetLoweringOpt(TLO);
10032 return true;
10033 }
10034 return false;
10035}
10036
10037static SDValue performSTORECombine(SDNode *N,
10038 TargetLowering::DAGCombinerInfo &DCI,
10039 SelectionDAG &DAG,
10040 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010041 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010042 return Split;
10043
10044 if (Subtarget->supportsAddressTopByteIgnored() &&
10045 performTBISimplification(N->getOperand(2), DCI, DAG))
10046 return SDValue(N, 0);
10047
10048 return SDValue();
10049}
10050
Chad Rosier6c36eff2015-09-03 18:13:57 +000010051
Tim Northover3b0846e2014-05-24 12:50:23 +000010052/// Target-specific DAG combine function for NEON load/store intrinsics
10053/// to merge base address updates.
10054static SDValue performNEONPostLDSTCombine(SDNode *N,
10055 TargetLowering::DAGCombinerInfo &DCI,
10056 SelectionDAG &DAG) {
10057 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10058 return SDValue();
10059
10060 unsigned AddrOpIdx = N->getNumOperands() - 1;
10061 SDValue Addr = N->getOperand(AddrOpIdx);
10062
10063 // Search for a use of the address operand that is an increment.
10064 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10065 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10066 SDNode *User = *UI;
10067 if (User->getOpcode() != ISD::ADD ||
10068 UI.getUse().getResNo() != Addr.getResNo())
10069 continue;
10070
10071 // Check that the add is independent of the load/store. Otherwise, folding
10072 // it would create a cycle.
10073 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10074 continue;
10075
10076 // Find the new opcode for the updating load/store.
10077 bool IsStore = false;
10078 bool IsLaneOp = false;
10079 bool IsDupOp = false;
10080 unsigned NewOpc = 0;
10081 unsigned NumVecs = 0;
10082 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10083 switch (IntNo) {
10084 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10085 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10086 NumVecs = 2; break;
10087 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10088 NumVecs = 3; break;
10089 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10090 NumVecs = 4; break;
10091 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10092 NumVecs = 2; IsStore = true; break;
10093 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10094 NumVecs = 3; IsStore = true; break;
10095 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10096 NumVecs = 4; IsStore = true; break;
10097 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10098 NumVecs = 2; break;
10099 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10100 NumVecs = 3; break;
10101 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10102 NumVecs = 4; break;
10103 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10104 NumVecs = 2; IsStore = true; break;
10105 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10106 NumVecs = 3; IsStore = true; break;
10107 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10108 NumVecs = 4; IsStore = true; break;
10109 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10110 NumVecs = 2; IsDupOp = true; break;
10111 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10112 NumVecs = 3; IsDupOp = true; break;
10113 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10114 NumVecs = 4; IsDupOp = true; break;
10115 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10116 NumVecs = 2; IsLaneOp = true; break;
10117 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10118 NumVecs = 3; IsLaneOp = true; break;
10119 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10120 NumVecs = 4; IsLaneOp = true; break;
10121 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10122 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10123 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10124 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10125 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10126 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10127 }
10128
10129 EVT VecTy;
10130 if (IsStore)
10131 VecTy = N->getOperand(2).getValueType();
10132 else
10133 VecTy = N->getValueType(0);
10134
10135 // If the increment is a constant, it must match the memory ref size.
10136 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10137 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10138 uint32_t IncVal = CInc->getZExtValue();
10139 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10140 if (IsLaneOp || IsDupOp)
10141 NumBytes /= VecTy.getVectorNumElements();
10142 if (IncVal != NumBytes)
10143 continue;
10144 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10145 }
10146 SmallVector<SDValue, 8> Ops;
10147 Ops.push_back(N->getOperand(0)); // Incoming chain
10148 // Load lane and store have vector list as input.
10149 if (IsLaneOp || IsStore)
10150 for (unsigned i = 2; i < AddrOpIdx; ++i)
10151 Ops.push_back(N->getOperand(i));
10152 Ops.push_back(Addr); // Base register
10153 Ops.push_back(Inc);
10154
10155 // Return Types.
10156 EVT Tys[6];
10157 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10158 unsigned n;
10159 for (n = 0; n < NumResultVecs; ++n)
10160 Tys[n] = VecTy;
10161 Tys[n++] = MVT::i64; // Type of write back register
10162 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010163 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010164
10165 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10166 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10167 MemInt->getMemoryVT(),
10168 MemInt->getMemOperand());
10169
10170 // Update the uses.
10171 std::vector<SDValue> NewResults;
10172 for (unsigned i = 0; i < NumResultVecs; ++i) {
10173 NewResults.push_back(SDValue(UpdN.getNode(), i));
10174 }
10175 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10176 DCI.CombineTo(N, NewResults);
10177 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10178
10179 break;
10180 }
10181 return SDValue();
10182}
10183
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010184// Checks to see if the value is the prescribed width and returns information
10185// about its extension mode.
10186static
10187bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10188 ExtType = ISD::NON_EXTLOAD;
10189 switch(V.getNode()->getOpcode()) {
10190 default:
10191 return false;
10192 case ISD::LOAD: {
10193 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10194 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10195 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10196 ExtType = LoadNode->getExtensionType();
10197 return true;
10198 }
10199 return false;
10200 }
10201 case ISD::AssertSext: {
10202 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10203 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10204 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10205 ExtType = ISD::SEXTLOAD;
10206 return true;
10207 }
10208 return false;
10209 }
10210 case ISD::AssertZext: {
10211 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10212 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10213 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10214 ExtType = ISD::ZEXTLOAD;
10215 return true;
10216 }
10217 return false;
10218 }
10219 case ISD::Constant:
10220 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010221 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10222 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010223 }
10224 }
10225
10226 return true;
10227}
10228
10229// This function does a whole lot of voodoo to determine if the tests are
10230// equivalent without and with a mask. Essentially what happens is that given a
10231// DAG resembling:
10232//
10233// +-------------+ +-------------+ +-------------+ +-------------+
10234// | Input | | AddConstant | | CompConstant| | CC |
10235// +-------------+ +-------------+ +-------------+ +-------------+
10236// | | | |
10237// V V | +----------+
10238// +-------------+ +----+ | |
10239// | ADD | |0xff| | |
10240// +-------------+ +----+ | |
10241// | | | |
10242// V V | |
10243// +-------------+ | |
10244// | AND | | |
10245// +-------------+ | |
10246// | | |
10247// +-----+ | |
10248// | | |
10249// V V V
10250// +-------------+
10251// | CMP |
10252// +-------------+
10253//
10254// The AND node may be safely removed for some combinations of inputs. In
10255// particular we need to take into account the extension type of the Input,
10256// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10257// width of the input (this can work for any width inputs, the above graph is
10258// specific to 8 bits.
10259//
10260// The specific equations were worked out by generating output tables for each
10261// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10262// problem was simplified by working with 4 bit inputs, which means we only
10263// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10264// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10265// patterns present in both extensions (0,7). For every distinct set of
10266// AddConstant and CompConstants bit patterns we can consider the masked and
10267// unmasked versions to be equivalent if the result of this function is true for
10268// all 16 distinct bit patterns of for the current extension type of Input (w0).
10269//
10270// sub w8, w0, w1
10271// and w10, w8, #0x0f
10272// cmp w8, w2
10273// cset w9, AArch64CC
10274// cmp w10, w2
10275// cset w11, AArch64CC
10276// cmp w9, w11
10277// cset w0, eq
10278// ret
10279//
10280// Since the above function shows when the outputs are equivalent it defines
10281// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10282// would be expensive to run during compiles. The equations below were written
10283// in a test harness that confirmed they gave equivalent outputs to the above
10284// for all inputs function, so they can be used determine if the removal is
10285// legal instead.
10286//
10287// isEquivalentMaskless() is the code for testing if the AND can be removed
10288// factored out of the DAG recognition as the DAG can take several forms.
10289
David Majnemere61e4bf2016-06-21 05:10:24 +000010290static bool isEquivalentMaskless(unsigned CC, unsigned width,
10291 ISD::LoadExtType ExtType, int AddConstant,
10292 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010293 // By being careful about our equations and only writing the in term
10294 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10295 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010296 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010297
10298 // For the purposes of these comparisons sign extending the type is
10299 // equivalent to zero extending the add and displacing it by half the integer
10300 // width. Provided we are careful and make sure our equations are valid over
10301 // the whole range we can just adjust the input and avoid writing equations
10302 // for sign extended inputs.
10303 if (ExtType == ISD::SEXTLOAD)
10304 AddConstant -= (1 << (width-1));
10305
10306 switch(CC) {
10307 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010308 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010309 if ((AddConstant == 0) ||
10310 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10311 (AddConstant >= 0 && CompConstant < 0) ||
10312 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10313 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010314 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010315 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010316 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010317 if ((AddConstant == 0) ||
10318 (AddConstant >= 0 && CompConstant <= 0) ||
10319 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10320 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010321 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010322 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010323 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010324 if ((AddConstant >= 0 && CompConstant < 0) ||
10325 (AddConstant <= 0 && CompConstant >= -1 &&
10326 CompConstant < AddConstant + MaxUInt))
10327 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010328 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010329 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010330 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010331 if ((AddConstant == 0) ||
10332 (AddConstant > 0 && CompConstant <= 0) ||
10333 (AddConstant < 0 && CompConstant <= AddConstant))
10334 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010335 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010336 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010337 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010338 if ((AddConstant >= 0 && CompConstant <= 0) ||
10339 (AddConstant <= 0 && CompConstant >= 0 &&
10340 CompConstant <= AddConstant + MaxUInt))
10341 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010342 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010343 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010344 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010345 if ((AddConstant > 0 && CompConstant < 0) ||
10346 (AddConstant < 0 && CompConstant >= 0 &&
10347 CompConstant < AddConstant + MaxUInt) ||
10348 (AddConstant >= 0 && CompConstant >= 0 &&
10349 CompConstant >= AddConstant) ||
10350 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010351 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010352 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010353 case AArch64CC::VS:
10354 case AArch64CC::VC:
10355 case AArch64CC::AL:
10356 case AArch64CC::NV:
10357 return true;
10358 case AArch64CC::Invalid:
10359 break;
10360 }
10361
10362 return false;
10363}
10364
10365static
10366SDValue performCONDCombine(SDNode *N,
10367 TargetLowering::DAGCombinerInfo &DCI,
10368 SelectionDAG &DAG, unsigned CCIndex,
10369 unsigned CmpIndex) {
10370 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10371 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10372 unsigned CondOpcode = SubsNode->getOpcode();
10373
10374 if (CondOpcode != AArch64ISD::SUBS)
10375 return SDValue();
10376
10377 // There is a SUBS feeding this condition. Is it fed by a mask we can
10378 // use?
10379
10380 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10381 unsigned MaskBits = 0;
10382
10383 if (AndNode->getOpcode() != ISD::AND)
10384 return SDValue();
10385
10386 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10387 uint32_t CNV = CN->getZExtValue();
10388 if (CNV == 255)
10389 MaskBits = 8;
10390 else if (CNV == 65535)
10391 MaskBits = 16;
10392 }
10393
10394 if (!MaskBits)
10395 return SDValue();
10396
10397 SDValue AddValue = AndNode->getOperand(0);
10398
10399 if (AddValue.getOpcode() != ISD::ADD)
10400 return SDValue();
10401
10402 // The basic dag structure is correct, grab the inputs and validate them.
10403
10404 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10405 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10406 SDValue SubsInputValue = SubsNode->getOperand(1);
10407
10408 // The mask is present and the provenance of all the values is a smaller type,
10409 // lets see if the mask is superfluous.
10410
10411 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10412 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10413 return SDValue();
10414
10415 ISD::LoadExtType ExtType;
10416
10417 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10418 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10419 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10420 return SDValue();
10421
10422 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10423 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10424 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10425 return SDValue();
10426
10427 // The AND is not necessary, remove it.
10428
10429 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10430 SubsNode->getValueType(1));
10431 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10432
10433 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10434 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10435
10436 return SDValue(N, 0);
10437}
10438
Tim Northover3b0846e2014-05-24 12:50:23 +000010439// Optimize compare with zero and branch.
10440static SDValue performBRCONDCombine(SDNode *N,
10441 TargetLowering::DAGCombinerInfo &DCI,
10442 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010443 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010444 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010445 SDValue Chain = N->getOperand(0);
10446 SDValue Dest = N->getOperand(1);
10447 SDValue CCVal = N->getOperand(2);
10448 SDValue Cmp = N->getOperand(3);
10449
10450 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10451 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10452 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10453 return SDValue();
10454
10455 unsigned CmpOpc = Cmp.getOpcode();
10456 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10457 return SDValue();
10458
10459 // Only attempt folding if there is only one use of the flag and no use of the
10460 // value.
10461 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10462 return SDValue();
10463
10464 SDValue LHS = Cmp.getOperand(0);
10465 SDValue RHS = Cmp.getOperand(1);
10466
10467 assert(LHS.getValueType() == RHS.getValueType() &&
10468 "Expected the value type to be the same for both operands!");
10469 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10470 return SDValue();
10471
Artyom Skrobov314ee042015-11-25 19:41:11 +000010472 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010473 std::swap(LHS, RHS);
10474
Artyom Skrobov314ee042015-11-25 19:41:11 +000010475 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010476 return SDValue();
10477
10478 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10479 LHS.getOpcode() == ISD::SRL)
10480 return SDValue();
10481
10482 // Fold the compare into the branch instruction.
10483 SDValue BR;
10484 if (CC == AArch64CC::EQ)
10485 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10486 else
10487 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10488
10489 // Do not add new nodes to DAG combiner worklist.
10490 DCI.CombineTo(N, BR, false);
10491
10492 return SDValue();
10493}
10494
Geoff Berry9e934b02016-01-04 18:55:47 +000010495// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10496// as well as whether the test should be inverted. This code is required to
10497// catch these cases (as opposed to standard dag combines) because
10498// AArch64ISD::TBZ is matched during legalization.
10499static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10500 SelectionDAG &DAG) {
10501
10502 if (!Op->hasOneUse())
10503 return Op;
10504
10505 // We don't handle undef/constant-fold cases below, as they should have
10506 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10507 // etc.)
10508
10509 // (tbz (trunc x), b) -> (tbz x, b)
10510 // This case is just here to enable more of the below cases to be caught.
10511 if (Op->getOpcode() == ISD::TRUNCATE &&
10512 Bit < Op->getValueType(0).getSizeInBits()) {
10513 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10514 }
10515
10516 if (Op->getNumOperands() != 2)
10517 return Op;
10518
10519 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10520 if (!C)
10521 return Op;
10522
10523 switch (Op->getOpcode()) {
10524 default:
10525 return Op;
10526
10527 // (tbz (and x, m), b) -> (tbz x, b)
10528 case ISD::AND:
10529 if ((C->getZExtValue() >> Bit) & 1)
10530 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10531 return Op;
10532
10533 // (tbz (shl x, c), b) -> (tbz x, b-c)
10534 case ISD::SHL:
10535 if (C->getZExtValue() <= Bit &&
10536 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10537 Bit = Bit - C->getZExtValue();
10538 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10539 }
10540 return Op;
10541
10542 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10543 case ISD::SRA:
10544 Bit = Bit + C->getZExtValue();
10545 if (Bit >= Op->getValueType(0).getSizeInBits())
10546 Bit = Op->getValueType(0).getSizeInBits() - 1;
10547 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10548
10549 // (tbz (srl x, c), b) -> (tbz x, b+c)
10550 case ISD::SRL:
10551 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10552 Bit = Bit + C->getZExtValue();
10553 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10554 }
10555 return Op;
10556
10557 // (tbz (xor x, -1), b) -> (tbnz x, b)
10558 case ISD::XOR:
10559 if ((C->getZExtValue() >> Bit) & 1)
10560 Invert = !Invert;
10561 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10562 }
10563}
10564
10565// Optimize test single bit zero/non-zero and branch.
10566static SDValue performTBZCombine(SDNode *N,
10567 TargetLowering::DAGCombinerInfo &DCI,
10568 SelectionDAG &DAG) {
10569 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10570 bool Invert = false;
10571 SDValue TestSrc = N->getOperand(1);
10572 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10573
10574 if (TestSrc == NewTestSrc)
10575 return SDValue();
10576
10577 unsigned NewOpc = N->getOpcode();
10578 if (Invert) {
10579 if (NewOpc == AArch64ISD::TBZ)
10580 NewOpc = AArch64ISD::TBNZ;
10581 else {
10582 assert(NewOpc == AArch64ISD::TBNZ);
10583 NewOpc = AArch64ISD::TBZ;
10584 }
10585 }
10586
10587 SDLoc DL(N);
10588 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10589 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10590}
10591
Tim Northover3b0846e2014-05-24 12:50:23 +000010592// vselect (v1i1 setcc) ->
10593// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10594// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10595// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10596// such VSELECT.
10597static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10598 SDValue N0 = N->getOperand(0);
10599 EVT CCVT = N0.getValueType();
10600
10601 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10602 CCVT.getVectorElementType() != MVT::i1)
10603 return SDValue();
10604
10605 EVT ResVT = N->getValueType(0);
10606 EVT CmpVT = N0.getOperand(0).getValueType();
10607 // Only combine when the result type is of the same size as the compared
10608 // operands.
10609 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10610 return SDValue();
10611
10612 SDValue IfTrue = N->getOperand(1);
10613 SDValue IfFalse = N->getOperand(2);
10614 SDValue SetCC =
10615 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10616 N0.getOperand(0), N0.getOperand(1),
10617 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10618 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10619 IfTrue, IfFalse);
10620}
10621
10622/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10623/// the compare-mask instructions rather than going via NZCV, even if LHS and
10624/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10625/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010626static SDValue performSelectCombine(SDNode *N,
10627 TargetLowering::DAGCombinerInfo &DCI) {
10628 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010629 SDValue N0 = N->getOperand(0);
10630 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010631
Ahmed Bougachac004c602015-04-27 21:43:12 +000010632 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010633 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010634
Ahmed Bougachac004c602015-04-27 21:43:12 +000010635 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10636 // scalar SetCCResultType. We also don't expect vectors, because we assume
10637 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10638 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10639 "Scalar-SETCC feeding SELECT has unexpected result type!");
10640
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010641 // If NumMaskElts == 0, the comparison is larger than select result. The
10642 // largest real NEON comparison is 64-bits per lane, which means the result is
10643 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010644 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000010645
10646 // Don't try to do this optimization when the setcc itself has i1 operands.
10647 // There are no legal vectors of i1, so this would be pointless.
10648 if (SrcVT == MVT::i1)
10649 return SDValue();
10650
Tim Northover3c0915e2014-08-29 15:34:58 +000010651 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010652 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000010653 return SDValue();
10654
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010655 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010656 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10657
Ahmed Bougacha89bba612015-04-27 21:01:20 +000010658 // Also bail out if the vector CCVT isn't the same size as ResVT.
10659 // This can happen if the SETCC operand size doesn't divide the ResVT size
10660 // (e.g., f64 vs v3f32).
10661 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10662 return SDValue();
10663
Ahmed Bougachac004c602015-04-27 21:43:12 +000010664 // Make sure we didn't create illegal types, if we're not supposed to.
10665 assert(DCI.isBeforeLegalize() ||
10666 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10667
Tim Northover3b0846e2014-05-24 12:50:23 +000010668 // First perform a vector comparison, where lane 0 is the one we're interested
10669 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010670 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010671 SDValue LHS =
10672 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10673 SDValue RHS =
10674 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10675 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10676
10677 // Now duplicate the comparison mask we want across all other lanes.
10678 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000010679 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010680 Mask = DAG.getNode(ISD::BITCAST, DL,
10681 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000010682
10683 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10684}
10685
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010686/// Get rid of unnecessary NVCASTs (that don't change the type).
10687static SDValue performNVCASTCombine(SDNode *N) {
10688 if (N->getValueType(0) == N->getOperand(0).getValueType())
10689 return N->getOperand(0);
10690
10691 return SDValue();
10692}
10693
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000010694// If all users of the globaladdr are of the form (globaladdr + constant), find
10695// the smallest constant, fold it into the globaladdr's offset and rewrite the
10696// globaladdr as (globaladdr + constant) - constant.
10697static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
10698 const AArch64Subtarget *Subtarget,
10699 const TargetMachine &TM) {
10700 auto *GN = dyn_cast<GlobalAddressSDNode>(N);
10701 if (!GN || Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
10702 AArch64II::MO_NO_FLAG)
10703 return SDValue();
10704
10705 uint64_t MinOffset = -1ull;
10706 for (SDNode *N : GN->uses()) {
10707 if (N->getOpcode() != ISD::ADD)
10708 return SDValue();
10709 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
10710 if (!C)
10711 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10712 if (!C)
10713 return SDValue();
10714 MinOffset = std::min(MinOffset, C->getZExtValue());
10715 }
10716 uint64_t Offset = MinOffset + GN->getOffset();
10717
10718 // Require that the new offset is larger than the existing one. Otherwise, we
10719 // can end up oscillating between two possible DAGs, for example,
10720 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
10721 if (Offset <= uint64_t(GN->getOffset()))
10722 return SDValue();
10723
10724 // Check whether folding this offset is legal. It must not go out of bounds of
10725 // the referenced object to avoid violating the code model, and must be
10726 // smaller than 2^21 because this is the largest offset expressible in all
10727 // object formats.
10728 //
10729 // This check also prevents us from folding negative offsets, which will end
10730 // up being treated in the same way as large positive ones. They could also
10731 // cause code model violations, and aren't really common enough to matter.
10732 if (Offset >= (1 << 21))
10733 return SDValue();
10734
10735 const GlobalValue *GV = GN->getGlobal();
10736 Type *T = GV->getValueType();
10737 if (!T->isSized() ||
10738 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
10739 return SDValue();
10740
10741 SDLoc DL(GN);
10742 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
10743 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
10744 DAG.getConstant(MinOffset, DL, MVT::i64));
10745}
10746
Tim Northover3b0846e2014-05-24 12:50:23 +000010747SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10748 DAGCombinerInfo &DCI) const {
10749 SelectionDAG &DAG = DCI.DAG;
10750 switch (N->getOpcode()) {
10751 default:
Sjoerd Meijer24c98182017-08-23 08:18:37 +000010752 DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000010753 break;
10754 case ISD::ADD:
10755 case ISD::SUB:
10756 return performAddSubLongCombine(N, DCI, DAG);
10757 case ISD::XOR:
10758 return performXorCombine(N, DAG, DCI, Subtarget);
10759 case ISD::MUL:
10760 return performMulCombine(N, DAG, DCI, Subtarget);
10761 case ISD::SINT_TO_FP:
10762 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000010763 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000010764 case ISD::FP_TO_SINT:
10765 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000010766 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000010767 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000010768 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010769 case ISD::OR:
10770 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000010771 case ISD::SRL:
10772 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010773 case ISD::INTRINSIC_WO_CHAIN:
10774 return performIntrinsicCombine(N, DCI, Subtarget);
10775 case ISD::ANY_EXTEND:
10776 case ISD::ZERO_EXTEND:
10777 case ISD::SIGN_EXTEND:
10778 return performExtendCombine(N, DCI, DAG);
10779 case ISD::BITCAST:
10780 return performBitcastCombine(N, DCI, DAG);
10781 case ISD::CONCAT_VECTORS:
10782 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000010783 case ISD::SELECT:
10784 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010785 case ISD::VSELECT:
10786 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000010787 case ISD::LOAD:
10788 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10789 return SDValue(N, 0);
10790 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000010791 case ISD::STORE:
10792 return performSTORECombine(N, DCI, DAG, Subtarget);
10793 case AArch64ISD::BRCOND:
10794 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000010795 case AArch64ISD::TBNZ:
10796 case AArch64ISD::TBZ:
10797 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010798 case AArch64ISD::CSEL:
10799 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000010800 case AArch64ISD::DUP:
10801 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010802 case AArch64ISD::NVCAST:
10803 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000010804 case ISD::INSERT_VECTOR_ELT:
10805 return performPostLD1Combine(N, DCI, true);
10806 case ISD::INTRINSIC_VOID:
10807 case ISD::INTRINSIC_W_CHAIN:
10808 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10809 case Intrinsic::aarch64_neon_ld2:
10810 case Intrinsic::aarch64_neon_ld3:
10811 case Intrinsic::aarch64_neon_ld4:
10812 case Intrinsic::aarch64_neon_ld1x2:
10813 case Intrinsic::aarch64_neon_ld1x3:
10814 case Intrinsic::aarch64_neon_ld1x4:
10815 case Intrinsic::aarch64_neon_ld2lane:
10816 case Intrinsic::aarch64_neon_ld3lane:
10817 case Intrinsic::aarch64_neon_ld4lane:
10818 case Intrinsic::aarch64_neon_ld2r:
10819 case Intrinsic::aarch64_neon_ld3r:
10820 case Intrinsic::aarch64_neon_ld4r:
10821 case Intrinsic::aarch64_neon_st2:
10822 case Intrinsic::aarch64_neon_st3:
10823 case Intrinsic::aarch64_neon_st4:
10824 case Intrinsic::aarch64_neon_st1x2:
10825 case Intrinsic::aarch64_neon_st1x3:
10826 case Intrinsic::aarch64_neon_st1x4:
10827 case Intrinsic::aarch64_neon_st2lane:
10828 case Intrinsic::aarch64_neon_st3lane:
10829 case Intrinsic::aarch64_neon_st4lane:
10830 return performNEONPostLDSTCombine(N, DCI, DAG);
10831 default:
10832 break;
10833 }
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000010834 case ISD::GlobalAddress:
10835 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000010836 }
10837 return SDValue();
10838}
10839
10840// Check if the return value is used as only a return value, as otherwise
10841// we can't perform a tail-call. In particular, we need to check for
10842// target ISD nodes that are returns and any other "odd" constructs
10843// that the generic analysis code won't necessarily catch.
10844bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10845 SDValue &Chain) const {
10846 if (N->getNumValues() != 1)
10847 return false;
10848 if (!N->hasNUsesOfValue(1, 0))
10849 return false;
10850
10851 SDValue TCChain = Chain;
10852 SDNode *Copy = *N->use_begin();
10853 if (Copy->getOpcode() == ISD::CopyToReg) {
10854 // If the copy has a glue operand, we conservatively assume it isn't safe to
10855 // perform a tail call.
10856 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10857 MVT::Glue)
10858 return false;
10859 TCChain = Copy->getOperand(0);
10860 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10861 return false;
10862
10863 bool HasRet = false;
10864 for (SDNode *Node : Copy->uses()) {
10865 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10866 return false;
10867 HasRet = true;
10868 }
10869
10870 if (!HasRet)
10871 return false;
10872
10873 Chain = TCChain;
10874 return true;
10875}
10876
10877// Return whether the an instruction can potentially be optimized to a tail
10878// call. This will cause the optimizers to attempt to move, or duplicate,
10879// return instructions to help enable tail call optimizations for this
10880// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000010881bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010882 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010883}
10884
10885bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10886 SDValue &Offset,
10887 ISD::MemIndexedMode &AM,
10888 bool &IsInc,
10889 SelectionDAG &DAG) const {
10890 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10891 return false;
10892
10893 Base = Op->getOperand(0);
10894 // All of the indexed addressing mode instructions take a signed
10895 // 9 bit immediate offset.
10896 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000010897 int64_t RHSC = RHS->getSExtValue();
10898 if (Op->getOpcode() == ISD::SUB)
10899 RHSC = -(uint64_t)RHSC;
10900 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000010901 return false;
10902 IsInc = (Op->getOpcode() == ISD::ADD);
10903 Offset = Op->getOperand(1);
10904 return true;
10905 }
10906 return false;
10907}
10908
10909bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10910 SDValue &Offset,
10911 ISD::MemIndexedMode &AM,
10912 SelectionDAG &DAG) const {
10913 EVT VT;
10914 SDValue Ptr;
10915 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10916 VT = LD->getMemoryVT();
10917 Ptr = LD->getBasePtr();
10918 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10919 VT = ST->getMemoryVT();
10920 Ptr = ST->getBasePtr();
10921 } else
10922 return false;
10923
10924 bool IsInc;
10925 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10926 return false;
10927 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10928 return true;
10929}
10930
10931bool AArch64TargetLowering::getPostIndexedAddressParts(
10932 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10933 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10934 EVT VT;
10935 SDValue Ptr;
10936 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10937 VT = LD->getMemoryVT();
10938 Ptr = LD->getBasePtr();
10939 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10940 VT = ST->getMemoryVT();
10941 Ptr = ST->getBasePtr();
10942 } else
10943 return false;
10944
10945 bool IsInc;
10946 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10947 return false;
10948 // Post-indexing updates the base, so it's not a valid transform
10949 // if that's not the same as the load's pointer.
10950 if (Ptr != Base)
10951 return false;
10952 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10953 return true;
10954}
10955
Tim Northoverf8bfe212014-07-18 13:07:05 +000010956static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10957 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010958 SDLoc DL(N);
10959 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010960
10961 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10962 return;
10963
Tim Northoverf8bfe212014-07-18 13:07:05 +000010964 Op = SDValue(
10965 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10966 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010967 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010968 0);
10969 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10970 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10971}
10972
Charlie Turner434d4592015-10-16 15:38:25 +000010973static void ReplaceReductionResults(SDNode *N,
10974 SmallVectorImpl<SDValue> &Results,
10975 SelectionDAG &DAG, unsigned InterOp,
10976 unsigned AcrossOp) {
10977 EVT LoVT, HiVT;
10978 SDValue Lo, Hi;
10979 SDLoc dl(N);
10980 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10981 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10982 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10983 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10984 Results.push_back(SplitVal);
10985}
10986
Tim Northover2f32e7f2016-08-04 19:32:28 +000010987static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10988 SDLoc DL(N);
10989 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10990 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10991 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10992 DAG.getConstant(64, DL, MVT::i64)));
10993 return std::make_pair(Lo, Hi);
10994}
10995
Oliver Stannarda9d2e002018-01-29 09:18:37 +000010996// Create an even/odd pair of X registers holding integer value V.
10997static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
10998 SDLoc dl(V.getNode());
10999 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11000 SDValue VHi = DAG.getAnyExtOrTrunc(
11001 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11002 dl, MVT::i64);
11003 if (DAG.getDataLayout().isBigEndian())
11004 std::swap (VLo, VHi);
11005 SDValue RegClass =
11006 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11007 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11008 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11009 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11010 return SDValue(
11011 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11012}
11013
Tim Northovercdf15292016-04-14 17:03:29 +000011014static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011015 SmallVectorImpl<SDValue> &Results,
11016 SelectionDAG &DAG,
11017 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011018 assert(N->getValueType(0) == MVT::i128 &&
11019 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011020
11021 if (Subtarget->hasLSE()) {
11022 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11023 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11024 SDValue Ops[] = {
11025 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11026 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11027 N->getOperand(1), // Ptr
11028 N->getOperand(0), // Chain in
11029 };
11030
11031 MachineFunction &MF = DAG.getMachineFunction();
11032 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
11033 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
11034
11035 unsigned Opcode;
11036 switch (MemOp[0]->getOrdering()) {
11037 case AtomicOrdering::Monotonic:
11038 Opcode = AArch64::CASPX;
11039 break;
11040 case AtomicOrdering::Acquire:
11041 Opcode = AArch64::CASPAX;
11042 break;
11043 case AtomicOrdering::Release:
11044 Opcode = AArch64::CASPLX;
11045 break;
11046 case AtomicOrdering::AcquireRelease:
11047 case AtomicOrdering::SequentiallyConsistent:
11048 Opcode = AArch64::CASPALX;
11049 break;
11050 default:
11051 llvm_unreachable("Unexpected ordering!");
11052 }
11053
11054 MachineSDNode *CmpSwap = DAG.getMachineNode(
11055 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11056 CmpSwap->setMemRefs(MemOp, MemOp + 1);
11057
11058 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11059 if (DAG.getDataLayout().isBigEndian())
11060 std::swap(SubReg1, SubReg2);
11061 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11062 SDValue(CmpSwap, 0)));
11063 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11064 SDValue(CmpSwap, 0)));
11065 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11066 return;
11067 }
11068
Tim Northover2f32e7f2016-08-04 19:32:28 +000011069 auto Desired = splitInt128(N->getOperand(2), DAG);
11070 auto New = splitInt128(N->getOperand(3), DAG);
11071 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11072 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011073 SDNode *CmpSwap = DAG.getMachineNode(
11074 AArch64::CMP_SWAP_128, SDLoc(N),
11075 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11076
11077 MachineFunction &MF = DAG.getMachineFunction();
11078 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
11079 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
11080 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
11081
11082 Results.push_back(SDValue(CmpSwap, 0));
11083 Results.push_back(SDValue(CmpSwap, 1));
11084 Results.push_back(SDValue(CmpSwap, 3));
11085}
11086
Tim Northover3b0846e2014-05-24 12:50:23 +000011087void AArch64TargetLowering::ReplaceNodeResults(
11088 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11089 switch (N->getOpcode()) {
11090 default:
11091 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011092 case ISD::BITCAST:
11093 ReplaceBITCASTResults(N, Results, DAG);
11094 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011095 case ISD::VECREDUCE_ADD:
11096 case ISD::VECREDUCE_SMAX:
11097 case ISD::VECREDUCE_SMIN:
11098 case ISD::VECREDUCE_UMAX:
11099 case ISD::VECREDUCE_UMIN:
11100 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11101 return;
11102
Charlie Turner434d4592015-10-16 15:38:25 +000011103 case AArch64ISD::SADDV:
11104 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11105 return;
11106 case AArch64ISD::UADDV:
11107 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11108 return;
11109 case AArch64ISD::SMINV:
11110 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11111 return;
11112 case AArch64ISD::UMINV:
11113 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11114 return;
11115 case AArch64ISD::SMAXV:
11116 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11117 return;
11118 case AArch64ISD::UMAXV:
11119 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11120 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011121 case ISD::FP_TO_UINT:
11122 case ISD::FP_TO_SINT:
11123 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11124 // Let normal code take care of it by not adding anything to Results.
11125 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011126 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011127 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011128 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011129 }
11130}
11131
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011132bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011133 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11134 return TargetLowering::useLoadStackGuardNode();
11135 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011136}
11137
Sanjay Patel1dd15592015-07-28 23:05:48 +000011138unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011139 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11140 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011141 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011142}
11143
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011144TargetLoweringBase::LegalizeTypeAction
11145AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
11146 MVT SVT = VT.getSimpleVT();
11147 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11148 // v4i16, v2i32 instead of to promote.
11149 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
11150 || SVT == MVT::v1f32)
11151 return TypeWidenVector;
11152
11153 return TargetLoweringBase::getPreferredVectorAction(VT);
11154}
11155
Robin Morisseted3d48f2014-09-03 21:29:59 +000011156// Loads and stores less than 128-bits are already atomic; ones above that
11157// are doomed anyway, so defer to the default libcall and blame the OS when
11158// things go wrong.
11159bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11160 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11161 return Size == 128;
11162}
11163
11164// Loads and stores less than 128-bits are already atomic; ones above that
11165// are doomed anyway, so defer to the default libcall and blame the OS when
11166// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011167TargetLowering::AtomicExpansionKind
11168AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011169 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011170 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011171}
11172
11173// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011174TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011175AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011176 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011177 if (Size > 128) return AtomicExpansionKind::None;
11178 // Nand not supported in LSE.
11179 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011180 // Leave 128 bits to LLSC.
11181 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011182}
11183
Ahmed Bougacha52468672015-09-11 17:08:28 +000011184bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11185 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011186 // If subtarget has LSE, leave cmpxchg intact for codegen.
11187 if (Subtarget->hasLSE()) return false;
Tim Northovercdf15292016-04-14 17:03:29 +000011188 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11189 // implement cmpxchg without spilling. If the address being exchanged is also
11190 // on the stack and close enough to the spill slot, this can lead to a
11191 // situation where the monitor always gets cleared and the atomic operation
11192 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11193 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000011194}
11195
Tim Northover3b0846e2014-05-24 12:50:23 +000011196Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11197 AtomicOrdering Ord) const {
11198 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11199 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011200 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011201
11202 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11203 // intrinsic must return {i64, i64} and we have to recombine them into a
11204 // single i128 here.
11205 if (ValTy->getPrimitiveSizeInBits() == 128) {
11206 Intrinsic::ID Int =
11207 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011208 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011209
11210 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11211 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11212
11213 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11214 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11215 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11216 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11217 return Builder.CreateOr(
11218 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11219 }
11220
11221 Type *Tys[] = { Addr->getType() };
11222 Intrinsic::ID Int =
11223 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011224 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011225
11226 return Builder.CreateTruncOrBitCast(
11227 Builder.CreateCall(Ldxr, Addr),
11228 cast<PointerType>(Addr->getType())->getElementType());
11229}
11230
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011231void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11232 IRBuilder<> &Builder) const {
11233 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011234 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011235}
11236
Tim Northover3b0846e2014-05-24 12:50:23 +000011237Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11238 Value *Val, Value *Addr,
11239 AtomicOrdering Ord) const {
11240 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011241 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011242
11243 // Since the intrinsics must have legal type, the i128 intrinsics take two
11244 // parameters: "i64, i64". We must marshal Val into the appropriate form
11245 // before the call.
11246 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11247 Intrinsic::ID Int =
11248 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11249 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11250 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11251
11252 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11253 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11254 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011255 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011256 }
11257
11258 Intrinsic::ID Int =
11259 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11260 Type *Tys[] = { Addr->getType() };
11261 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11262
David Blaikieff6409d2015-05-18 22:13:54 +000011263 return Builder.CreateCall(Stxr,
11264 {Builder.CreateZExtOrBitCast(
11265 Val, Stxr->getFunctionType()->getParamType(0)),
11266 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011267}
Tim Northover3c55cca2014-11-27 21:02:42 +000011268
11269bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11270 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11271 return Ty->isArrayTy();
11272}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011273
11274bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11275 EVT) const {
11276 return false;
11277}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011278
Petr Hoseka7d59162017-02-24 03:10:10 +000011279static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011280 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11281 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011282 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011283 return IRB.CreatePointerCast(
Petr Hoseka7d59162017-02-24 03:10:10 +000011284 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011285 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
11286}
11287
Petr Hoseka7d59162017-02-24 03:10:10 +000011288Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11289 // Android provides a fixed TLS slot for the stack cookie. See the definition
11290 // of TLS_SLOT_STACK_GUARD in
11291 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11292 if (Subtarget->isTargetAndroid())
11293 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011294
Petr Hoseka7d59162017-02-24 03:10:10 +000011295 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011296 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011297 if (Subtarget->isTargetFuchsia())
11298 return UseTlsOffset(IRB, -0x10);
11299
11300 return TargetLowering::getIRStackGuard(IRB);
11301}
11302
11303Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011304 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11305 // definition of TLS_SLOT_SAFESTACK in
11306 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011307 if (Subtarget->isTargetAndroid())
11308 return UseTlsOffset(IRB, 0x48);
11309
11310 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011311 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011312 if (Subtarget->isTargetFuchsia())
11313 return UseTlsOffset(IRB, -0x8);
11314
11315 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011316}
Manman Rencbe4f942015-12-16 21:04:19 +000011317
Geoff Berry5d534b62017-02-21 18:53:14 +000011318bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11319 const Instruction &AndI) const {
11320 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11321 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11322 // may be beneficial to sink in other cases, but we would have to check that
11323 // the cmp would not get folded into the br to form a cbz for these to be
11324 // beneficial.
11325 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11326 if (!Mask)
11327 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011328 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011329}
11330
Manman Rencbe4f942015-12-16 21:04:19 +000011331void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11332 // Update IsSplitCSR in AArch64unctionInfo.
11333 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11334 AFI->setIsSplitCSR(true);
11335}
11336
11337void AArch64TargetLowering::insertCopiesSplitCSR(
11338 MachineBasicBlock *Entry,
11339 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11340 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11341 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11342 if (!IStart)
11343 return;
11344
11345 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11346 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011347 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011348 for (const MCPhysReg *I = IStart; *I; ++I) {
11349 const TargetRegisterClass *RC = nullptr;
11350 if (AArch64::GPR64RegClass.contains(*I))
11351 RC = &AArch64::GPR64RegClass;
11352 else if (AArch64::FPR64RegClass.contains(*I))
11353 RC = &AArch64::FPR64RegClass;
11354 else
11355 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11356
11357 unsigned NewVR = MRI->createVirtualRegister(RC);
11358 // Create copy from CSR to a virtual register.
11359 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11360 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11361 // nounwind. If we want to generalize this later, we may need to emit
11362 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011363 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011364 Attribute::NoUnwind) &&
11365 "Function should be nounwind in insertCopiesSplitCSR!");
11366 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011367 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011368 .addReg(*I);
11369
Manman Ren4632e8e2016-01-15 20:13:28 +000011370 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011371 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011372 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11373 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011374 .addReg(NewVR);
11375 }
11376}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011377
Reid Klecknerb5180542017-03-21 16:57:19 +000011378bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011379 // Integer division on AArch64 is expensive. However, when aggressively
11380 // optimizing for code size, we prefer to use a div instruction, as it is
11381 // usually smaller than the alternative sequence.
11382 // The exception to this is vector division. Since AArch64 doesn't have vector
11383 // integer division, leaving the division as-is is a loss even in terms of
11384 // size, because it will have to be scalarized, while the alternative code
11385 // sequence can be performed in vector form.
11386 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011387 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011388 return OptSize && !VT.isVector();
11389}
Tim Northoverf19d4672017-02-08 17:57:20 +000011390
Joel Jones07150922018-01-25 21:55:39 +000011391bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11392 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11393}
11394
Tim Northoverf19d4672017-02-08 17:57:20 +000011395unsigned
11396AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011397 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011398 return getPointerTy(DL).getSizeInBits();
11399
11400 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11401}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011402
11403void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11404 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11405 TargetLoweringBase::finalizeLowering(MF);
11406}