blob: f8761378e420000890540a2542e33a2295bbdf7e [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 Northover70666e72018-06-20 12:09:01 +0000472 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
473
Tim Northovercdf15292016-04-14 17:03:29 +0000474 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000475 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000477 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000479
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000480 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
481 // This requires the Performance Monitors extension.
482 if (Subtarget->hasPerfMon())
483 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
484
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000485 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
486 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
487 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
489 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
490 } else {
491 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
492 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
493 }
494
Juergen Ributzka23266502014-12-10 19:43:32 +0000495 // Make floating-point constants legal for the large code model, so they don't
496 // become loads from the constant pool.
497 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
498 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
499 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
500 }
501
Tim Northover3b0846e2014-05-24 12:50:23 +0000502 // AArch64 does not have floating-point extending loads, i1 sign-extending
503 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000504 for (MVT VT : MVT::fp_valuetypes()) {
505 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
506 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
507 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
508 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
509 }
510 for (MVT VT : MVT::integer_valuetypes())
511 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
512
Tim Northover3b0846e2014-05-24 12:50:23 +0000513 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
514 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
515 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
516 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
517 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
518 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
519 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000520
521 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
522 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
523
Tim Northover3b0846e2014-05-24 12:50:23 +0000524 // Indexed loads and stores are supported.
525 for (unsigned im = (unsigned)ISD::PRE_INC;
526 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
527 setIndexedLoadAction(im, MVT::i8, Legal);
528 setIndexedLoadAction(im, MVT::i16, Legal);
529 setIndexedLoadAction(im, MVT::i32, Legal);
530 setIndexedLoadAction(im, MVT::i64, Legal);
531 setIndexedLoadAction(im, MVT::f64, Legal);
532 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000533 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000534 setIndexedStoreAction(im, MVT::i8, Legal);
535 setIndexedStoreAction(im, MVT::i16, Legal);
536 setIndexedStoreAction(im, MVT::i32, Legal);
537 setIndexedStoreAction(im, MVT::i64, Legal);
538 setIndexedStoreAction(im, MVT::f64, Legal);
539 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000540 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000541 }
542
543 // Trap.
544 setOperationAction(ISD::TRAP, MVT::Other, Legal);
545
546 // We combine OR nodes for bitfield operations.
547 setTargetDAGCombine(ISD::OR);
548
549 // Vector add and sub nodes may conceal a high-half opportunity.
550 // Also, try to fold ADD into CSINC/CSINV..
551 setTargetDAGCombine(ISD::ADD);
552 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000553 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000554 setTargetDAGCombine(ISD::XOR);
555 setTargetDAGCombine(ISD::SINT_TO_FP);
556 setTargetDAGCombine(ISD::UINT_TO_FP);
557
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000558 setTargetDAGCombine(ISD::FP_TO_SINT);
559 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000560 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000561
Tim Northover3b0846e2014-05-24 12:50:23 +0000562 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
563
564 setTargetDAGCombine(ISD::ANY_EXTEND);
565 setTargetDAGCombine(ISD::ZERO_EXTEND);
566 setTargetDAGCombine(ISD::SIGN_EXTEND);
567 setTargetDAGCombine(ISD::BITCAST);
568 setTargetDAGCombine(ISD::CONCAT_VECTORS);
569 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000570 if (Subtarget->supportsAddressTopByteIgnored())
571 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000572
573 setTargetDAGCombine(ISD::MUL);
574
575 setTargetDAGCombine(ISD::SELECT);
576 setTargetDAGCombine(ISD::VSELECT);
577
578 setTargetDAGCombine(ISD::INTRINSIC_VOID);
579 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
581
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000582 setTargetDAGCombine(ISD::GlobalAddress);
583
Evandro Menezesf8425342018-05-29 15:58:50 +0000584 // In case of strict alignment, avoid an excessive number of byte wide stores.
585 MaxStoresPerMemsetOptSize = 8;
586 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
587 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000588
Evandro Menezesf8425342018-05-29 15:58:50 +0000589 MaxGluedStoresPerMemcpy = 4;
590 MaxStoresPerMemcpyOptSize = 4;
591 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
592 ? MaxStoresPerMemcpyOptSize : 16;
593
594 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000595
596 setStackPointerRegisterToSaveRestore(AArch64::SP);
597
598 setSchedulingPreference(Sched::Hybrid);
599
Quentin Colombet6843ac42015-03-31 20:52:32 +0000600 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000601
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000602 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000603 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000604 // Set preferred alignments.
605 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
606 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000607
Evandro Menezese45de8a2016-09-26 15:32:33 +0000608 // Only change the limit for entries in a jump table if specified by
609 // the subtarget, but not at the command line.
610 unsigned MaxJT = STI.getMaximumJumpTableSize();
611 if (MaxJT && getMaximumJumpTableSize() == 0)
612 setMaximumJumpTableSize(MaxJT);
613
Tim Northover3b0846e2014-05-24 12:50:23 +0000614 setHasExtractBitsInsn(true);
615
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000616 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
617
Tim Northover3b0846e2014-05-24 12:50:23 +0000618 if (Subtarget->hasNEON()) {
619 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
620 // silliness like this:
621 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
622 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
623 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
624 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
625 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
626 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
627 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
628 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
629 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
630 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
631 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
632 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
633 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
634 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
635 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
636 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
637 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
638 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
639 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
640 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
641 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
642 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
643 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
644 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
645 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
646
647 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
648 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
649 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
650 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
651 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
652
653 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
654
655 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
656 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000657 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
658 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
659 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
660 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000661 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
662 // -> v8f16 conversions.
Craig Toppera4f99972018-01-01 19:21:35 +0000663 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
664 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
665 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
666 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000667 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
668 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
669 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
670 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
671 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000672 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
673 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
674 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
675 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000676
Craig Topperc5551bf2016-04-26 05:26:51 +0000677 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
678 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
679
Craig Topper3b4842b2016-04-28 01:58:21 +0000680 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
681 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
682 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
683 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
684 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
685 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
686 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
687 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
688
Tim Northover3b0846e2014-05-24 12:50:23 +0000689 // AArch64 doesn't have MUL.2d:
690 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000691 // Custom handling for some quad-vector types to detect MULL.
692 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
693 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
694 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
695
Amara Emersonc9916d72017-05-16 21:29:22 +0000696 // Vector reductions
697 for (MVT VT : MVT::integer_valuetypes()) {
698 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
699 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
700 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
701 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
702 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
703 }
704 for (MVT VT : MVT::fp_valuetypes()) {
705 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
706 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
707 }
708
Tim Northover3b0846e2014-05-24 12:50:23 +0000709 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
710 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
711 // Likewise, narrowing and extending vector loads/stores aren't handled
712 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000713 for (MVT VT : MVT::vector_valuetypes()) {
714 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000715
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000716 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
717 setOperationAction(ISD::MULHS, VT, Custom);
718 setOperationAction(ISD::MULHU, VT, Custom);
719 } else {
720 setOperationAction(ISD::MULHS, VT, Expand);
721 setOperationAction(ISD::MULHU, VT, Expand);
722 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000723 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000724 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000725
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000726 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000727
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000728 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000729 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000730 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
731 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
732 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
733 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000734 }
735
736 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000737 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000738 setOperationAction(ISD::FFLOOR, Ty, Legal);
739 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
740 setOperationAction(ISD::FCEIL, Ty, Legal);
741 setOperationAction(ISD::FRINT, Ty, Legal);
742 setOperationAction(ISD::FTRUNC, Ty, Legal);
743 setOperationAction(ISD::FROUND, Ty, Legal);
744 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000745
746 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000747 }
James Molloyf089ab72014-08-06 10:42:18 +0000748
Matthias Braun651cff42016-06-02 18:03:53 +0000749 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000750}
751
Craig Topper18e69f42016-04-15 06:20:21 +0000752void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000753 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000754
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000755 if (VT.isFloatingPoint()) {
756 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
757 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
758 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 }
760
761 // Mark vector float intrinsics as expand.
762 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000763 setOperationAction(ISD::FSIN, VT, Expand);
764 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000765 setOperationAction(ISD::FPOW, VT, Expand);
766 setOperationAction(ISD::FLOG, VT, Expand);
767 setOperationAction(ISD::FLOG2, VT, Expand);
768 setOperationAction(ISD::FLOG10, VT, Expand);
769 setOperationAction(ISD::FEXP, VT, Expand);
770 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000771
772 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000773 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000774 }
775
Craig Topper18e69f42016-04-15 06:20:21 +0000776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
778 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
779 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
780 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
781 setOperationAction(ISD::SRA, VT, Custom);
782 setOperationAction(ISD::SRL, VT, Custom);
783 setOperationAction(ISD::SHL, VT, Custom);
784 setOperationAction(ISD::AND, VT, Custom);
785 setOperationAction(ISD::OR, VT, Custom);
786 setOperationAction(ISD::SETCC, VT, Custom);
787 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000788
Craig Topper18e69f42016-04-15 06:20:21 +0000789 setOperationAction(ISD::SELECT, VT, Expand);
790 setOperationAction(ISD::SELECT_CC, VT, Expand);
791 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000792 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000793 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000794
795 // CNT supports only B element sizes.
796 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000797 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000798
Craig Topper18e69f42016-04-15 06:20:21 +0000799 setOperationAction(ISD::UDIV, VT, Expand);
800 setOperationAction(ISD::SDIV, VT, Expand);
801 setOperationAction(ISD::UREM, VT, Expand);
802 setOperationAction(ISD::SREM, VT, Expand);
803 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000804
Craig Topper18e69f42016-04-15 06:20:21 +0000805 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
806 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000807
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000808 if (!VT.isFloatingPoint())
809 setOperationAction(ISD::ABS, VT, Legal);
810
Hal Finkelcd8664c2015-12-11 23:11:52 +0000811 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000812 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000813 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000814 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000815
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000816 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
817 if (VT.isFloatingPoint() &&
818 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
James Molloyb7b2a1e2015-08-11 12:06:37 +0000819 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
820 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000821 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000822
Tim Northover3b0846e2014-05-24 12:50:23 +0000823 if (Subtarget->isLittleEndian()) {
824 for (unsigned im = (unsigned)ISD::PRE_INC;
825 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000826 setIndexedLoadAction(im, VT, Legal);
827 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000828 }
829 }
830}
831
832void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
833 addRegisterClass(VT, &AArch64::FPR64RegClass);
834 addTypeForNEON(VT, MVT::v2i32);
835}
836
837void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
838 addRegisterClass(VT, &AArch64::FPR128RegClass);
839 addTypeForNEON(VT, MVT::v4i32);
840}
841
Mehdi Amini44ede332015-07-09 02:09:04 +0000842EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
843 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000844 if (!VT.isVector())
845 return MVT::i32;
846 return VT.changeVectorElementTypeToInteger();
847}
848
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000849static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
850 const APInt &Demanded,
851 TargetLowering::TargetLoweringOpt &TLO,
852 unsigned NewOpc) {
853 uint64_t OldImm = Imm, NewImm, Enc;
854 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
855
856 // Return if the immediate is already all zeros, all ones, a bimm32 or a
857 // bimm64.
858 if (Imm == 0 || Imm == Mask ||
859 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
860 return false;
861
862 unsigned EltSize = Size;
863 uint64_t DemandedBits = Demanded.getZExtValue();
864
865 // Clear bits that are not demanded.
866 Imm &= DemandedBits;
867
868 while (true) {
869 // The goal here is to set the non-demanded bits in a way that minimizes
870 // the number of switching between 0 and 1. In order to achieve this goal,
871 // we set the non-demanded bits to the value of the preceding demanded bits.
872 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
873 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
874 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
875 // The final result is 0b11000011.
876 uint64_t NonDemandedBits = ~DemandedBits;
877 uint64_t InvertedImm = ~Imm & DemandedBits;
878 uint64_t RotatedImm =
879 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
880 NonDemandedBits;
881 uint64_t Sum = RotatedImm + NonDemandedBits;
882 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
883 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
884 NewImm = (Imm | Ones) & Mask;
885
886 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
887 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
888 // we halve the element size and continue the search.
889 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
890 break;
891
892 // We cannot shrink the element size any further if it is 2-bits.
893 if (EltSize == 2)
894 return false;
895
896 EltSize /= 2;
897 Mask >>= EltSize;
898 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
899
900 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
901 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
902 return false;
903
904 // Merge the upper and lower halves of Imm and DemandedBits.
905 Imm |= Hi;
906 DemandedBits |= DemandedBitsHi;
907 }
908
909 ++NumOptimizedImms;
910
911 // Replicate the element across the register width.
912 while (EltSize < Size) {
913 NewImm |= NewImm << EltSize;
914 EltSize *= 2;
915 }
916
917 (void)OldImm;
918 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
919 "demanded bits should never be altered");
920 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
921
922 // Create the new constant immediate node.
923 EVT VT = Op.getValueType();
924 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000925 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000926
927 // If the new constant immediate is all-zeros or all-ones, let the target
928 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000929 if (NewImm == 0 || NewImm == OrigMask) {
930 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
931 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000932 // Otherwise, create a machine node so that target independent DAG combine
933 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000934 } else {
935 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
936 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
937 New = SDValue(
938 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
939 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000940
941 return TLO.CombineTo(Op, New);
942}
943
944bool AArch64TargetLowering::targetShrinkDemandedConstant(
945 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
946 // Delay this optimization to as late as possible.
947 if (!TLO.LegalOps)
948 return false;
949
950 if (!EnableOptimizeLogicalImm)
951 return false;
952
953 EVT VT = Op.getValueType();
954 if (VT.isVector())
955 return false;
956
957 unsigned Size = VT.getSizeInBits();
958 assert((Size == 32 || Size == 64) &&
959 "i32 or i64 is expected after legalization.");
960
961 // Exit early if we demand all bits.
962 if (Demanded.countPopulation() == Size)
963 return false;
964
965 unsigned NewOpc;
966 switch (Op.getOpcode()) {
967 default:
968 return false;
969 case ISD::AND:
970 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
971 break;
972 case ISD::OR:
973 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
974 break;
975 case ISD::XOR:
976 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
977 break;
978 }
979 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
980 if (!C)
981 return false;
982 uint64_t Imm = C->getZExtValue();
983 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
984}
985
Tim Northover3b0846e2014-05-24 12:50:23 +0000986/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000987/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000988void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000989 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000990 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000991 switch (Op.getOpcode()) {
992 default:
993 break;
994 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000995 KnownBits Known2;
996 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
997 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
998 Known.Zero &= Known2.Zero;
999 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001000 break;
1001 }
1002 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001003 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001004 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1005 switch (IntID) {
1006 default: return;
1007 case Intrinsic::aarch64_ldaxr:
1008 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001009 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001010 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001011 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001012 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001013 return;
1014 }
1015 }
1016 break;
1017 }
1018 case ISD::INTRINSIC_WO_CHAIN:
1019 case ISD::INTRINSIC_VOID: {
1020 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1021 switch (IntNo) {
1022 default:
1023 break;
1024 case Intrinsic::aarch64_neon_umaxv:
1025 case Intrinsic::aarch64_neon_uminv: {
1026 // Figure out the datatype of the vector operand. The UMINV instruction
1027 // will zero extend the result, so we can mark as known zero all the
1028 // bits larger than the element datatype. 32-bit or larget doesn't need
1029 // this as those are legal types and will be handled by isel directly.
1030 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001031 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001032 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1033 assert(BitWidth >= 8 && "Unexpected width!");
1034 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001035 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1037 assert(BitWidth >= 16 && "Unexpected width!");
1038 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001039 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001040 }
1041 break;
1042 } break;
1043 }
1044 }
1045 }
1046}
1047
Mehdi Aminieaabc512015-07-09 15:12:23 +00001048MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1049 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001050 return MVT::i64;
1051}
1052
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001053bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1054 unsigned AddrSpace,
1055 unsigned Align,
1056 bool *Fast) const {
1057 if (Subtarget->requiresStrictAlign())
1058 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001059
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001060 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001061 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1062 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001063 // See comments in performSTORECombine() for more details about
1064 // these conditions.
1065
1066 // Code that uses clang vector extensions can mark that it
1067 // wants unaligned accesses to be treated as fast by
1068 // underspecifying alignment to be 1 or 2.
1069 Align <= 2 ||
1070
1071 // Disregard v2i64. Memcpy lowering produces those and splitting
1072 // them regresses performance on micro-benchmarks and olden/bh.
1073 VT == MVT::v2i64;
1074 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001075 return true;
1076}
1077
Tim Northover3b0846e2014-05-24 12:50:23 +00001078FastISel *
1079AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1080 const TargetLibraryInfo *libInfo) const {
1081 return AArch64::createFastISel(funcInfo, libInfo);
1082}
1083
1084const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001085 switch ((AArch64ISD::NodeType)Opcode) {
1086 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001087 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1088 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001089 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001090 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1091 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1092 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1093 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1094 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1095 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1096 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1097 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1098 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1099 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001100 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001101 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1102 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1103 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1104 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1105 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1106 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1107 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001108 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1109 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1110 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001111 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001112 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1113 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1114 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1115 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1116 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1117 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1118 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1119 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1120 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1121 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1122 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1123 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1124 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1125 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1126 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1127 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1128 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1129 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1130 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1131 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1132 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1133 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1134 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1135 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1136 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1137 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1138 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1139 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1140 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1141 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1142 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1143 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1144 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1145 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1146 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1147 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1148 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1149 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1150 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1151 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1152 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1153 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1154 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1155 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1156 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1157 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1158 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1159 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001160 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1161 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1162 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1163 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1164 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1165 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001166 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1167 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1168 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1169 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1170 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1171 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1172 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001173 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001174 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1175 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001176 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001177 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1178 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1179 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1180 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1181 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1182 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1183 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1184 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1185 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1186 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1187 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1188 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1189 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1190 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1191 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1192 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1193 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1194 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1195 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1196 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1197 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1198 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1199 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1200 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1201 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1202 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1203 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1204 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1205 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001206 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1207 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001208 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001209 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1210 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1211 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001212 }
Matthias Braund04893f2015-05-07 21:33:59 +00001213 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001214}
1215
1216MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001217AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001218 MachineBasicBlock *MBB) const {
1219 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1220 // phi node:
1221
1222 // OrigBB:
1223 // [... previous instrs leading to comparison ...]
1224 // b.ne TrueBB
1225 // b EndBB
1226 // TrueBB:
1227 // ; Fallthrough
1228 // EndBB:
1229 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1230
Tim Northover3b0846e2014-05-24 12:50:23 +00001231 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001232 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001233 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001234 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001235 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001236
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001237 unsigned DestReg = MI.getOperand(0).getReg();
1238 unsigned IfTrueReg = MI.getOperand(1).getReg();
1239 unsigned IfFalseReg = MI.getOperand(2).getReg();
1240 unsigned CondCode = MI.getOperand(3).getImm();
1241 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001242
1243 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245 MF->insert(It, TrueBB);
1246 MF->insert(It, EndBB);
1247
1248 // Transfer rest of current basic-block to EndBB
1249 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1250 MBB->end());
1251 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1252
1253 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1254 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1255 MBB->addSuccessor(TrueBB);
1256 MBB->addSuccessor(EndBB);
1257
1258 // TrueBB falls through to the end.
1259 TrueBB->addSuccessor(EndBB);
1260
1261 if (!NZCVKilled) {
1262 TrueBB->addLiveIn(AArch64::NZCV);
1263 EndBB->addLiveIn(AArch64::NZCV);
1264 }
1265
1266 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1267 .addReg(IfTrueReg)
1268 .addMBB(TrueBB)
1269 .addReg(IfFalseReg)
1270 .addMBB(MBB);
1271
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001272 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001273 return EndBB;
1274}
1275
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001276MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1277 MachineInstr &MI, MachineBasicBlock *BB) const {
1278 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001279 default:
1280#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001281 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001282#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001283 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001284
1285 case AArch64::F128CSEL:
1286 return EmitF128CSEL(MI, BB);
1287
1288 case TargetOpcode::STACKMAP:
1289 case TargetOpcode::PATCHPOINT:
1290 return emitPatchPoint(MI, BB);
1291 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001292}
1293
1294//===----------------------------------------------------------------------===//
1295// AArch64 Lowering private implementation.
1296//===----------------------------------------------------------------------===//
1297
1298//===----------------------------------------------------------------------===//
1299// Lowering Code
1300//===----------------------------------------------------------------------===//
1301
1302/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1303/// CC
1304static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1305 switch (CC) {
1306 default:
1307 llvm_unreachable("Unknown condition code!");
1308 case ISD::SETNE:
1309 return AArch64CC::NE;
1310 case ISD::SETEQ:
1311 return AArch64CC::EQ;
1312 case ISD::SETGT:
1313 return AArch64CC::GT;
1314 case ISD::SETGE:
1315 return AArch64CC::GE;
1316 case ISD::SETLT:
1317 return AArch64CC::LT;
1318 case ISD::SETLE:
1319 return AArch64CC::LE;
1320 case ISD::SETUGT:
1321 return AArch64CC::HI;
1322 case ISD::SETUGE:
1323 return AArch64CC::HS;
1324 case ISD::SETULT:
1325 return AArch64CC::LO;
1326 case ISD::SETULE:
1327 return AArch64CC::LS;
1328 }
1329}
1330
1331/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1332static void changeFPCCToAArch64CC(ISD::CondCode CC,
1333 AArch64CC::CondCode &CondCode,
1334 AArch64CC::CondCode &CondCode2) {
1335 CondCode2 = AArch64CC::AL;
1336 switch (CC) {
1337 default:
1338 llvm_unreachable("Unknown FP condition!");
1339 case ISD::SETEQ:
1340 case ISD::SETOEQ:
1341 CondCode = AArch64CC::EQ;
1342 break;
1343 case ISD::SETGT:
1344 case ISD::SETOGT:
1345 CondCode = AArch64CC::GT;
1346 break;
1347 case ISD::SETGE:
1348 case ISD::SETOGE:
1349 CondCode = AArch64CC::GE;
1350 break;
1351 case ISD::SETOLT:
1352 CondCode = AArch64CC::MI;
1353 break;
1354 case ISD::SETOLE:
1355 CondCode = AArch64CC::LS;
1356 break;
1357 case ISD::SETONE:
1358 CondCode = AArch64CC::MI;
1359 CondCode2 = AArch64CC::GT;
1360 break;
1361 case ISD::SETO:
1362 CondCode = AArch64CC::VC;
1363 break;
1364 case ISD::SETUO:
1365 CondCode = AArch64CC::VS;
1366 break;
1367 case ISD::SETUEQ:
1368 CondCode = AArch64CC::EQ;
1369 CondCode2 = AArch64CC::VS;
1370 break;
1371 case ISD::SETUGT:
1372 CondCode = AArch64CC::HI;
1373 break;
1374 case ISD::SETUGE:
1375 CondCode = AArch64CC::PL;
1376 break;
1377 case ISD::SETLT:
1378 case ISD::SETULT:
1379 CondCode = AArch64CC::LT;
1380 break;
1381 case ISD::SETLE:
1382 case ISD::SETULE:
1383 CondCode = AArch64CC::LE;
1384 break;
1385 case ISD::SETNE:
1386 case ISD::SETUNE:
1387 CondCode = AArch64CC::NE;
1388 break;
1389 }
1390}
1391
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001392/// Convert a DAG fp condition code to an AArch64 CC.
1393/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1394/// should be AND'ed instead of OR'ed.
1395static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1396 AArch64CC::CondCode &CondCode,
1397 AArch64CC::CondCode &CondCode2) {
1398 CondCode2 = AArch64CC::AL;
1399 switch (CC) {
1400 default:
1401 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1402 assert(CondCode2 == AArch64CC::AL);
1403 break;
1404 case ISD::SETONE:
1405 // (a one b)
1406 // == ((a olt b) || (a ogt b))
1407 // == ((a ord b) && (a une b))
1408 CondCode = AArch64CC::VC;
1409 CondCode2 = AArch64CC::NE;
1410 break;
1411 case ISD::SETUEQ:
1412 // (a ueq b)
1413 // == ((a uno b) || (a oeq b))
1414 // == ((a ule b) && (a uge b))
1415 CondCode = AArch64CC::PL;
1416 CondCode2 = AArch64CC::LE;
1417 break;
1418 }
1419}
1420
Tim Northover3b0846e2014-05-24 12:50:23 +00001421/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1422/// CC usable with the vector instructions. Fewer operations are available
1423/// without a real NZCV register, so we have to use less efficient combinations
1424/// to get the same effect.
1425static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1426 AArch64CC::CondCode &CondCode,
1427 AArch64CC::CondCode &CondCode2,
1428 bool &Invert) {
1429 Invert = false;
1430 switch (CC) {
1431 default:
1432 // Mostly the scalar mappings work fine.
1433 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1434 break;
1435 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001436 Invert = true;
1437 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001438 case ISD::SETO:
1439 CondCode = AArch64CC::MI;
1440 CondCode2 = AArch64CC::GE;
1441 break;
1442 case ISD::SETUEQ:
1443 case ISD::SETULT:
1444 case ISD::SETULE:
1445 case ISD::SETUGT:
1446 case ISD::SETUGE:
1447 // All of the compare-mask comparisons are ordered, but we can switch
1448 // between the two by a double inversion. E.g. ULE == !OGT.
1449 Invert = true;
1450 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1451 break;
1452 }
1453}
1454
1455static bool isLegalArithImmed(uint64_t C) {
1456 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001457 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001458 LLVM_DEBUG(dbgs() << "Is imm " << C
1459 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001460 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001461}
1462
1463static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001464 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001465 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001466 const bool FullFP16 =
1467 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001468
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001469 if (VT.isFloatingPoint()) {
1470 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001471 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001472 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1473 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001474 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001475 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001476 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001477 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001478
1479 // The CMP instruction is just an alias for SUBS, and representing it as
1480 // SUBS means that it's possible to get CSE with subtract operations.
1481 // A later phase can perform the optimization of setting the destination
1482 // register to WZR/XZR if it ends up being unused.
1483 unsigned Opcode = AArch64ISD::SUBS;
1484
Artyom Skrobov314ee042015-11-25 19:41:11 +00001485 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001486 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1487 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1488 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1489 // can be set differently by this operation. It comes down to whether
1490 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1491 // everything is fine. If not then the optimization is wrong. Thus general
1492 // comparisons are only valid if op2 != 0.
1493
1494 // So, finally, the only LLVM-native comparisons that don't mention C and V
1495 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1496 // the absence of information about op2.
1497 Opcode = AArch64ISD::ADDS;
1498 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001499 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001500 !isUnsignedIntSetCC(CC)) {
1501 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1502 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1503 // of the signed comparisons.
1504 Opcode = AArch64ISD::ANDS;
1505 RHS = LHS.getOperand(1);
1506 LHS = LHS.getOperand(0);
1507 }
1508
Matthias Braunaf7d7702015-07-16 20:02:37 +00001509 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001510 .getValue(1);
1511}
1512
Matthias Braunaf7d7702015-07-16 20:02:37 +00001513/// \defgroup AArch64CCMP CMP;CCMP matching
1514///
1515/// These functions deal with the formation of CMP;CCMP;... sequences.
1516/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1517/// a comparison. They set the NZCV flags to a predefined value if their
1518/// predicate is false. This allows to express arbitrary conjunctions, for
1519/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1520/// expressed as:
1521/// cmp A
1522/// ccmp B, inv(CB), CA
1523/// check for CB flags
1524///
1525/// In general we can create code for arbitrary "... (and (and A B) C)"
1526/// sequences. We can also implement some "or" expressions, because "(or A B)"
1527/// is equivalent to "not (and (not A) (not B))" and we can implement some
1528/// negation operations:
1529/// We can negate the results of a single comparison by inverting the flags
1530/// used when the predicate fails and inverting the flags tested in the next
1531/// instruction; We can also negate the results of the whole previous
1532/// conditional compare sequence by inverting the flags tested in the next
1533/// instruction. However there is no way to negate the result of a partial
1534/// sequence.
1535///
1536/// Therefore on encountering an "or" expression we can negate the subtree on
1537/// one side and have to be able to push the negate to the leafs of the subtree
1538/// on the other side (see also the comments in code). As complete example:
1539/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1540/// (and (setCC (cmp C)) (setCD (cmp D)))"
1541/// is transformed to
1542/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1543/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1544/// and implemented as:
1545/// cmp C
1546/// ccmp D, inv(CD), CC
1547/// ccmp A, CA, inv(CD)
1548/// ccmp B, CB, inv(CA)
1549/// check for CB flags
1550/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1551/// by conditional compare sequences.
1552/// @{
1553
Geoff Berrye41c2df2015-07-20 22:03:52 +00001554/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001555static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1556 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001557 AArch64CC::CondCode Predicate,
1558 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001559 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001560 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001561 const bool FullFP16 =
1562 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1563
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001564 if (LHS.getValueType().isFloatingPoint()) {
1565 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001566 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001567 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1568 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1569 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001570 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001571 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001572 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001573 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001574 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1575 Opcode = AArch64ISD::CCMN;
1576 RHS = RHS.getOperand(1);
1577 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001578 }
1579 if (Opcode == 0)
1580 Opcode = AArch64ISD::CCMP;
1581
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001582 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1583 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1584 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001585 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1586 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1587}
1588
1589/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1590/// CanPushNegate is set to true if we can push a negate operation through
1591/// the tree in a was that we are left with AND operations and negate operations
1592/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1593/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1594/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001595static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001596 unsigned Depth = 0) {
1597 if (!Val.hasOneUse())
1598 return false;
1599 unsigned Opcode = Val->getOpcode();
1600 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001601 if (Val->getOperand(0).getValueType() == MVT::f128)
1602 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001603 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001604 return true;
1605 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001606 // Protect against exponential runtime and stack overflow.
1607 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001608 return false;
1609 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1610 SDValue O0 = Val->getOperand(0);
1611 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001612 bool CanNegateL;
1613 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001614 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001615 bool CanNegateR;
1616 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001617 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001618
1619 if (Opcode == ISD::OR) {
1620 // For an OR expression we need to be able to negate at least one side or
1621 // we cannot do the transformation at all.
1622 if (!CanNegateL && !CanNegateR)
1623 return false;
1624 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1625 // can negate the x and y subtrees.
1626 CanNegate = CanNegateL && CanNegateR;
1627 } else {
1628 // If the operands are OR expressions then we finally need to negate their
1629 // outputs, we can only do that for the operand with emitted last by
1630 // negating OutCC, not for both operands.
1631 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1632 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1633 if (NeedsNegOutL && NeedsNegOutR)
1634 return false;
1635 // We cannot negate an AND operation (it would become an OR),
1636 CanNegate = false;
1637 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001638 return true;
1639 }
1640 return false;
1641}
1642
1643/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1644/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1645/// Tries to transform the given i1 producing node @p Val to a series compare
1646/// and conditional compare operations. @returns an NZCV flags producing node
1647/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1648/// transformation was not possible.
1649/// On recursive invocations @p PushNegate may be set to true to have negation
1650/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1651/// for the comparisons in the current subtree; @p Depth limits the search
1652/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001653static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1654 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001655 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001656 // We're at a tree leaf, produce a conditional comparison operation.
1657 unsigned Opcode = Val->getOpcode();
1658 if (Opcode == ISD::SETCC) {
1659 SDValue LHS = Val->getOperand(0);
1660 SDValue RHS = Val->getOperand(1);
1661 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1662 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001663 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001664 CC = getSetCCInverse(CC, isInteger);
1665 SDLoc DL(Val);
1666 // Determine OutCC and handle FP special case.
1667 if (isInteger) {
1668 OutCC = changeIntCCToAArch64CC(CC);
1669 } else {
1670 assert(LHS.getValueType().isFloatingPoint());
1671 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001672 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1673 // Some floating point conditions can't be tested with a single condition
1674 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001675 if (ExtraCC != AArch64CC::AL) {
1676 SDValue ExtraCmp;
1677 if (!CCOp.getNode())
1678 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001679 else
1680 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001681 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001682 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001683 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001684 }
1685 }
1686
1687 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001688 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001689 return emitComparison(LHS, RHS, CC, DL, DAG);
1690 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001691 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001692 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001693 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001694 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1695 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001696
1697 // Check if both sides can be transformed.
1698 SDValue LHS = Val->getOperand(0);
1699 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001700
Matthias Braunfdef49b2016-01-23 04:05:22 +00001701 // In case of an OR we need to negate our operands and the result.
1702 // (A v B) <=> not(not(A) ^ not(B))
1703 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001704 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001705 // predicate flags giving us a free negation for one side. The other side
1706 // must be negatable by itself.
1707 if (NegateOpsAndResult) {
1708 // See which side we can negate.
1709 bool CanNegateL;
1710 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1711 assert(isValidL && "Valid conjunction/disjunction tree");
1712 (void)isValidL;
1713
1714#ifndef NDEBUG
1715 bool CanNegateR;
1716 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1717 assert(isValidR && "Valid conjunction/disjunction tree");
1718 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1719#endif
1720
1721 // Order the side which we cannot negate to RHS so we can emit it first.
1722 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001723 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001724 } else {
1725 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001726 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001727 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001728 // Order the side where we need to negate the output flags to RHS so it
1729 // gets emitted first.
1730 if (NeedsNegOutL)
1731 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001732 }
1733
1734 // Emit RHS. If we want to negate the tree we only need to push a negate
1735 // through if we are already in a PushNegate case, otherwise we can negate
1736 // the "flags to test" afterwards.
1737 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001738 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001739 CCOp, Predicate);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001740 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001741 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001742 // Emit LHS. We may need to negate it.
1743 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1744 NegateOpsAndResult, CmpR,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001745 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001746 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001747 // (or absorb the Negate parameter).
1748 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001749 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1750 return CmpL;
1751}
1752
Matthias Braunfdef49b2016-01-23 04:05:22 +00001753/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1754/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1755/// \see emitConjunctionDisjunctionTreeRec().
1756static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001757 AArch64CC::CondCode &OutCC) {
Matthias Braunfdef49b2016-01-23 04:05:22 +00001758 bool CanNegate;
1759 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1760 return SDValue();
1761
1762 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001763 AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001764}
1765
Matthias Braunaf7d7702015-07-16 20:02:37 +00001766/// @}
1767
Tim Northover3b0846e2014-05-24 12:50:23 +00001768static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001769 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001770 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001771 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1772 EVT VT = RHS.getValueType();
1773 uint64_t C = RHSC->getZExtValue();
1774 if (!isLegalArithImmed(C)) {
1775 // Constant does not fit, try adjusting it by one?
1776 switch (CC) {
1777 default:
1778 break;
1779 case ISD::SETLT:
1780 case ISD::SETGE:
1781 if ((VT == MVT::i32 && C != 0x80000000 &&
1782 isLegalArithImmed((uint32_t)(C - 1))) ||
1783 (VT == MVT::i64 && C != 0x80000000ULL &&
1784 isLegalArithImmed(C - 1ULL))) {
1785 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1786 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001787 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001788 }
1789 break;
1790 case ISD::SETULT:
1791 case ISD::SETUGE:
1792 if ((VT == MVT::i32 && C != 0 &&
1793 isLegalArithImmed((uint32_t)(C - 1))) ||
1794 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1795 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1796 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001797 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001798 }
1799 break;
1800 case ISD::SETLE:
1801 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001802 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001803 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001804 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001805 isLegalArithImmed(C + 1ULL))) {
1806 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1807 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001808 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001809 }
1810 break;
1811 case ISD::SETULE:
1812 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001813 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001814 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001815 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001816 isLegalArithImmed(C + 1ULL))) {
1817 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1818 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001819 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001820 }
1821 break;
1822 }
1823 }
1824 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001825 SDValue Cmp;
1826 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001827 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001828 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1829
1830 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1831 // For the i8 operand, the largest immediate is 255, so this can be easily
1832 // encoded in the compare instruction. For the i16 operand, however, the
1833 // largest immediate cannot be encoded in the compare.
1834 // Therefore, use a sign extending load and cmn to avoid materializing the
1835 // -1 constant. For example,
1836 // movz w1, #65535
1837 // ldrh w0, [x0, #0]
1838 // cmp w0, w1
1839 // >
1840 // ldrsh w0, [x0, #0]
1841 // cmn w0, #1
1842 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1843 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001844 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001845 // transformation is profitable.
1846 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1847 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1848 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1849 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1850 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1851 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1852 SDValue SExt =
1853 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1854 DAG.getValueType(MVT::i16));
1855 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1856 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001857 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001858 AArch64CC = changeIntCCToAArch64CC(CC);
1859 }
1860 }
1861
1862 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001863 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001864 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1865 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001866 }
1867 }
1868 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001869
1870 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001871 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001872 AArch64CC = changeIntCCToAArch64CC(CC);
1873 }
1874 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001875 return Cmp;
1876}
1877
1878static std::pair<SDValue, SDValue>
1879getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1880 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1881 "Unsupported value type");
1882 SDValue Value, Overflow;
1883 SDLoc DL(Op);
1884 SDValue LHS = Op.getOperand(0);
1885 SDValue RHS = Op.getOperand(1);
1886 unsigned Opc = 0;
1887 switch (Op.getOpcode()) {
1888 default:
1889 llvm_unreachable("Unknown overflow instruction!");
1890 case ISD::SADDO:
1891 Opc = AArch64ISD::ADDS;
1892 CC = AArch64CC::VS;
1893 break;
1894 case ISD::UADDO:
1895 Opc = AArch64ISD::ADDS;
1896 CC = AArch64CC::HS;
1897 break;
1898 case ISD::SSUBO:
1899 Opc = AArch64ISD::SUBS;
1900 CC = AArch64CC::VS;
1901 break;
1902 case ISD::USUBO:
1903 Opc = AArch64ISD::SUBS;
1904 CC = AArch64CC::LO;
1905 break;
1906 // Multiply needs a little bit extra work.
1907 case ISD::SMULO:
1908 case ISD::UMULO: {
1909 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001910 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001911 if (Op.getValueType() == MVT::i32) {
1912 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1913 // For a 32 bit multiply with overflow check we want the instruction
1914 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1915 // need to generate the following pattern:
1916 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1917 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1918 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1919 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1920 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001921 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001922 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1923 // operation. We need to clear out the upper 32 bits, because we used a
1924 // widening multiply that wrote all 64 bits. In the end this should be a
1925 // noop.
1926 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1927 if (IsSigned) {
1928 // The signed overflow check requires more than just a simple check for
1929 // any bit set in the upper 32 bits of the result. These bits could be
1930 // just the sign bits of a negative number. To perform the overflow
1931 // check we have to arithmetic shift right the 32nd bit of the result by
1932 // 31 bits. Then we compare the result to the upper 32 bits.
1933 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001934 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001935 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1936 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001937 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001938 // It is important that LowerBits is last, otherwise the arithmetic
1939 // shift will not be folded into the compare (SUBS).
1940 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1941 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1942 .getValue(1);
1943 } else {
1944 // The overflow check for unsigned multiply is easy. We only need to
1945 // check if any of the upper 32 bits are set. This can be done with a
1946 // CMP (shifted register). For that we need to generate the following
1947 // pattern:
1948 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1949 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001950 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001951 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1952 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001953 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1954 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001955 UpperBits).getValue(1);
1956 }
1957 break;
1958 }
1959 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1960 // For the 64 bit multiply
1961 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1962 if (IsSigned) {
1963 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1964 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001965 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001966 // It is important that LowerBits is last, otherwise the arithmetic
1967 // shift will not be folded into the compare (SUBS).
1968 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1969 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1970 .getValue(1);
1971 } else {
1972 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1973 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1974 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001975 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1976 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001977 UpperBits).getValue(1);
1978 }
1979 break;
1980 }
1981 } // switch (...)
1982
1983 if (Opc) {
1984 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1985
1986 // Emit the AArch64 operation with overflow check.
1987 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1988 Overflow = Value.getValue(1);
1989 }
1990 return std::make_pair(Value, Overflow);
1991}
1992
1993SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1994 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001995 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001996 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001997}
1998
Amara Emerson24ca39c2017-10-09 15:15:09 +00001999// Returns true if the given Op is the overflow flag result of an overflow
2000// intrinsic operation.
2001static bool isOverflowIntrOpRes(SDValue Op) {
2002 unsigned Opc = Op.getOpcode();
2003 return (Op.getResNo() == 1 &&
2004 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2005 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2006}
2007
Tim Northover3b0846e2014-05-24 12:50:23 +00002008static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2009 SDValue Sel = Op.getOperand(0);
2010 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002011 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002012
Amara Emerson24ca39c2017-10-09 15:15:09 +00002013 // If the operand is an overflow checking operation, invert the condition
2014 // code and kill the Not operation. I.e., transform:
2015 // (xor (overflow_op_bool, 1))
2016 // -->
2017 // (csel 1, 0, invert(cc), overflow_op_bool)
2018 // ... which later gets transformed to just a cset instruction with an
2019 // inverted condition code, rather than a cset + eor sequence.
2020 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2021 // Only lower legal XALUO ops.
2022 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2023 return SDValue();
2024
2025 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2026 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2027 AArch64CC::CondCode CC;
2028 SDValue Value, Overflow;
2029 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2030 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2031 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2032 CCVal, Overflow);
2033 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002034 // If neither operand is a SELECT_CC, give up.
2035 if (Sel.getOpcode() != ISD::SELECT_CC)
2036 std::swap(Sel, Other);
2037 if (Sel.getOpcode() != ISD::SELECT_CC)
2038 return Op;
2039
2040 // The folding we want to perform is:
2041 // (xor x, (select_cc a, b, cc, 0, -1) )
2042 // -->
2043 // (csel x, (xor x, -1), cc ...)
2044 //
2045 // The latter will get matched to a CSINV instruction.
2046
2047 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2048 SDValue LHS = Sel.getOperand(0);
2049 SDValue RHS = Sel.getOperand(1);
2050 SDValue TVal = Sel.getOperand(2);
2051 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002052
2053 // FIXME: This could be generalized to non-integer comparisons.
2054 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2055 return Op;
2056
2057 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2058 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2059
Eric Christopher572e03a2015-06-19 01:53:21 +00002060 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002061 if (!CFVal || !CTVal)
2062 return Op;
2063
2064 // We can commute the SELECT_CC by inverting the condition. This
2065 // might be needed to make this fit into a CSINV pattern.
2066 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2067 std::swap(TVal, FVal);
2068 std::swap(CTVal, CFVal);
2069 CC = ISD::getSetCCInverse(CC, true);
2070 }
2071
2072 // If the constants line up, perform the transform!
2073 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2074 SDValue CCVal;
2075 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2076
2077 FVal = Other;
2078 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002079 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002080
2081 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2082 CCVal, Cmp);
2083 }
2084
2085 return Op;
2086}
2087
2088static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2089 EVT VT = Op.getValueType();
2090
2091 // Let legalize expand this if it isn't a legal type yet.
2092 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2093 return SDValue();
2094
2095 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2096
2097 unsigned Opc;
2098 bool ExtraOp = false;
2099 switch (Op.getOpcode()) {
2100 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002101 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002102 case ISD::ADDC:
2103 Opc = AArch64ISD::ADDS;
2104 break;
2105 case ISD::SUBC:
2106 Opc = AArch64ISD::SUBS;
2107 break;
2108 case ISD::ADDE:
2109 Opc = AArch64ISD::ADCS;
2110 ExtraOp = true;
2111 break;
2112 case ISD::SUBE:
2113 Opc = AArch64ISD::SBCS;
2114 ExtraOp = true;
2115 break;
2116 }
2117
2118 if (!ExtraOp)
2119 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2120 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2121 Op.getOperand(2));
2122}
2123
2124static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2125 // Let legalize expand this if it isn't a legal type yet.
2126 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2127 return SDValue();
2128
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002129 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002130 AArch64CC::CondCode CC;
2131 // The actual operation that sets the overflow or carry flag.
2132 SDValue Value, Overflow;
2133 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2134
2135 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002136 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2137 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002138
2139 // We use an inverted condition, because the conditional select is inverted
2140 // too. This will allow it to be selected to a single instruction:
2141 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002142 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2143 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002144 CCVal, Overflow);
2145
2146 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002147 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002148}
2149
2150// Prefetch operands are:
2151// 1: Address to prefetch
2152// 2: bool isWrite
2153// 3: int locality (0 = no locality ... 3 = extreme locality)
2154// 4: bool isDataCache
2155static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2156 SDLoc DL(Op);
2157 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2158 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002159 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002160
2161 bool IsStream = !Locality;
2162 // When the locality number is set
2163 if (Locality) {
2164 // The front-end should have filtered out the out-of-range values
2165 assert(Locality <= 3 && "Prefetch locality out-of-range");
2166 // The locality degree is the opposite of the cache speed.
2167 // Put the number the other way around.
2168 // The encoding starts at 0 for level 1
2169 Locality = 3 - Locality;
2170 }
2171
2172 // built the mask value encoding the expected behavior.
2173 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002174 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002175 (Locality << 1) | // Cache level bits
2176 (unsigned)IsStream; // Stream bit
2177 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002178 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002179}
2180
2181SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2182 SelectionDAG &DAG) const {
2183 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2184
2185 RTLIB::Libcall LC;
2186 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2187
2188 return LowerF128Call(Op, DAG, LC);
2189}
2190
2191SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2192 SelectionDAG &DAG) const {
2193 if (Op.getOperand(0).getValueType() != MVT::f128) {
2194 // It's legal except when f128 is involved
2195 return Op;
2196 }
2197
2198 RTLIB::Libcall LC;
2199 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2200
2201 // FP_ROUND node has a second operand indicating whether it is known to be
2202 // precise. That doesn't take part in the LibCall so we can't directly use
2203 // LowerF128Call.
2204 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002205 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2206 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002207}
2208
2209static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2210 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2211 // Any additional optimization in this function should be recorded
2212 // in the cost tables.
2213 EVT InVT = Op.getOperand(0).getValueType();
2214 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002215 unsigned NumElts = InVT.getVectorNumElements();
2216
2217 // f16 vectors are promoted to f32 before a conversion.
2218 if (InVT.getVectorElementType() == MVT::f16) {
2219 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2220 SDLoc dl(Op);
2221 return DAG.getNode(
2222 Op.getOpcode(), dl, Op.getValueType(),
2223 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2224 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002225
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002226 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002227 SDLoc dl(Op);
2228 SDValue Cv =
2229 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2230 Op.getOperand(0));
2231 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002232 }
2233
2234 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002235 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002236 MVT ExtVT =
2237 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2238 VT.getVectorNumElements());
2239 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002240 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2241 }
2242
2243 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002244 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002245}
2246
2247SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2248 SelectionDAG &DAG) const {
2249 if (Op.getOperand(0).getValueType().isVector())
2250 return LowerVectorFP_TO_INT(Op, DAG);
2251
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002252 // f16 conversions are promoted to f32 when full fp16 is not supported.
2253 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2254 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002255 SDLoc dl(Op);
2256 return DAG.getNode(
2257 Op.getOpcode(), dl, Op.getValueType(),
2258 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2259 }
2260
Tim Northover3b0846e2014-05-24 12:50:23 +00002261 if (Op.getOperand(0).getValueType() != MVT::f128) {
2262 // It's legal except when f128 is involved
2263 return Op;
2264 }
2265
2266 RTLIB::Libcall LC;
2267 if (Op.getOpcode() == ISD::FP_TO_SINT)
2268 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2269 else
2270 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2271
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002272 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002273 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002274}
2275
2276static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2277 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2278 // Any additional optimization in this function should be recorded
2279 // in the cost tables.
2280 EVT VT = Op.getValueType();
2281 SDLoc dl(Op);
2282 SDValue In = Op.getOperand(0);
2283 EVT InVT = In.getValueType();
2284
Tim Northoveref0d7602014-06-15 09:27:06 +00002285 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2286 MVT CastVT =
2287 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2288 InVT.getVectorNumElements());
2289 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002290 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002291 }
2292
Tim Northoveref0d7602014-06-15 09:27:06 +00002293 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2294 unsigned CastOpc =
2295 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2296 EVT CastVT = VT.changeVectorElementTypeToInteger();
2297 In = DAG.getNode(CastOpc, dl, CastVT, In);
2298 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002299 }
2300
Tim Northoveref0d7602014-06-15 09:27:06 +00002301 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002302}
2303
2304SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2305 SelectionDAG &DAG) const {
2306 if (Op.getValueType().isVector())
2307 return LowerVectorINT_TO_FP(Op, DAG);
2308
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002309 // f16 conversions are promoted to f32 when full fp16 is not supported.
2310 if (Op.getValueType() == MVT::f16 &&
2311 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002312 SDLoc dl(Op);
2313 return DAG.getNode(
2314 ISD::FP_ROUND, dl, MVT::f16,
2315 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002316 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002317 }
2318
Tim Northover3b0846e2014-05-24 12:50:23 +00002319 // i128 conversions are libcalls.
2320 if (Op.getOperand(0).getValueType() == MVT::i128)
2321 return SDValue();
2322
2323 // Other conversions are legal, unless it's to the completely software-based
2324 // fp128.
2325 if (Op.getValueType() != MVT::f128)
2326 return Op;
2327
2328 RTLIB::Libcall LC;
2329 if (Op.getOpcode() == ISD::SINT_TO_FP)
2330 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2331 else
2332 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2333
2334 return LowerF128Call(Op, DAG, LC);
2335}
2336
2337SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2338 SelectionDAG &DAG) const {
2339 // For iOS, we want to call an alternative entry point: __sincos_stret,
2340 // which returns the values in two S / D registers.
2341 SDLoc dl(Op);
2342 SDValue Arg = Op.getOperand(0);
2343 EVT ArgVT = Arg.getValueType();
2344 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2345
2346 ArgListTy Args;
2347 ArgListEntry Entry;
2348
2349 Entry.Node = Arg;
2350 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002351 Entry.IsSExt = false;
2352 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002353 Args.push_back(Entry);
2354
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002355 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2356 : RTLIB::SINCOS_STRET_F32;
2357 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002358 SDValue Callee =
2359 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002360
Serge Gueltone38003f2017-05-09 19:31:13 +00002361 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002362 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002363 CLI.setDebugLoc(dl)
2364 .setChain(DAG.getEntryNode())
2365 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002366
2367 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2368 return CallResult.first;
2369}
2370
Tim Northoverf8bfe212014-07-18 13:07:05 +00002371static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2372 if (Op.getValueType() != MVT::f16)
2373 return SDValue();
2374
2375 assert(Op.getOperand(0).getValueType() == MVT::i16);
2376 SDLoc DL(Op);
2377
2378 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2379 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2380 return SDValue(
2381 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002382 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002383 0);
2384}
2385
Chad Rosierd9d0f862014-10-08 02:31:24 +00002386static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2387 if (OrigVT.getSizeInBits() >= 64)
2388 return OrigVT;
2389
2390 assert(OrigVT.isSimple() && "Expecting a simple value type");
2391
2392 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2393 switch (OrigSimpleTy) {
2394 default: llvm_unreachable("Unexpected Vector Type");
2395 case MVT::v2i8:
2396 case MVT::v2i16:
2397 return MVT::v2i32;
2398 case MVT::v4i8:
2399 return MVT::v4i16;
2400 }
2401}
2402
2403static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2404 const EVT &OrigTy,
2405 const EVT &ExtTy,
2406 unsigned ExtOpcode) {
2407 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2408 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2409 // 64-bits we need to insert a new extension so that it will be 64-bits.
2410 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2411 if (OrigTy.getSizeInBits() >= 64)
2412 return N;
2413
2414 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2415 EVT NewVT = getExtensionTo64Bits(OrigTy);
2416
2417 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2418}
2419
2420static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2421 bool isSigned) {
2422 EVT VT = N->getValueType(0);
2423
2424 if (N->getOpcode() != ISD::BUILD_VECTOR)
2425 return false;
2426
Pete Cooper3af9a252015-06-26 18:17:36 +00002427 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002428 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002429 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002430 unsigned HalfSize = EltSize / 2;
2431 if (isSigned) {
2432 if (!isIntN(HalfSize, C->getSExtValue()))
2433 return false;
2434 } else {
2435 if (!isUIntN(HalfSize, C->getZExtValue()))
2436 return false;
2437 }
2438 continue;
2439 }
2440 return false;
2441 }
2442
2443 return true;
2444}
2445
2446static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2447 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2448 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2449 N->getOperand(0)->getValueType(0),
2450 N->getValueType(0),
2451 N->getOpcode());
2452
2453 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2454 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002455 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002456 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002457 unsigned NumElts = VT.getVectorNumElements();
2458 MVT TruncVT = MVT::getIntegerVT(EltSize);
2459 SmallVector<SDValue, 8> Ops;
2460 for (unsigned i = 0; i != NumElts; ++i) {
2461 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2462 const APInt &CInt = C->getAPIntValue();
2463 // Element types smaller than 32 bits are not legal, so use i32 elements.
2464 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002465 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002466 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002467 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002468}
2469
2470static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002471 return N->getOpcode() == ISD::SIGN_EXTEND ||
2472 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002473}
2474
2475static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002476 return N->getOpcode() == ISD::ZERO_EXTEND ||
2477 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002478}
2479
2480static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2481 unsigned Opcode = N->getOpcode();
2482 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2483 SDNode *N0 = N->getOperand(0).getNode();
2484 SDNode *N1 = N->getOperand(1).getNode();
2485 return N0->hasOneUse() && N1->hasOneUse() &&
2486 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2487 }
2488 return false;
2489}
2490
2491static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2492 unsigned Opcode = N->getOpcode();
2493 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2494 SDNode *N0 = N->getOperand(0).getNode();
2495 SDNode *N1 = N->getOperand(1).getNode();
2496 return N0->hasOneUse() && N1->hasOneUse() &&
2497 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2498 }
2499 return false;
2500}
2501
Tim Northover70666e72018-06-20 12:09:01 +00002502SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2503 SelectionDAG &DAG) const {
2504 // The rounding mode is in bits 23:22 of the FPSCR.
2505 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2506 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2507 // so that the shift + and get folded into a bitfield extract.
2508 SDLoc dl(Op);
2509
2510 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2511 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2512 MVT::i64));
2513 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2514 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2515 DAG.getConstant(1U << 22, dl, MVT::i32));
2516 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2517 DAG.getConstant(22, dl, MVT::i32));
2518 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2519 DAG.getConstant(3, dl, MVT::i32));
2520}
2521
Chad Rosierd9d0f862014-10-08 02:31:24 +00002522static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2523 // Multiplications are only custom-lowered for 128-bit vectors so that
2524 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2525 EVT VT = Op.getValueType();
2526 assert(VT.is128BitVector() && VT.isInteger() &&
2527 "unexpected type for custom-lowering ISD::MUL");
2528 SDNode *N0 = Op.getOperand(0).getNode();
2529 SDNode *N1 = Op.getOperand(1).getNode();
2530 unsigned NewOpc = 0;
2531 bool isMLA = false;
2532 bool isN0SExt = isSignExtended(N0, DAG);
2533 bool isN1SExt = isSignExtended(N1, DAG);
2534 if (isN0SExt && isN1SExt)
2535 NewOpc = AArch64ISD::SMULL;
2536 else {
2537 bool isN0ZExt = isZeroExtended(N0, DAG);
2538 bool isN1ZExt = isZeroExtended(N1, DAG);
2539 if (isN0ZExt && isN1ZExt)
2540 NewOpc = AArch64ISD::UMULL;
2541 else if (isN1SExt || isN1ZExt) {
2542 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2543 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2544 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2545 NewOpc = AArch64ISD::SMULL;
2546 isMLA = true;
2547 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2548 NewOpc = AArch64ISD::UMULL;
2549 isMLA = true;
2550 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2551 std::swap(N0, N1);
2552 NewOpc = AArch64ISD::UMULL;
2553 isMLA = true;
2554 }
2555 }
2556
2557 if (!NewOpc) {
2558 if (VT == MVT::v2i64)
2559 // Fall through to expand this. It is not legal.
2560 return SDValue();
2561 else
2562 // Other vector multiplications are legal.
2563 return Op;
2564 }
2565 }
2566
2567 // Legalize to a S/UMULL instruction
2568 SDLoc DL(Op);
2569 SDValue Op0;
2570 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2571 if (!isMLA) {
2572 Op0 = skipExtensionForVectorMULL(N0, DAG);
2573 assert(Op0.getValueType().is64BitVector() &&
2574 Op1.getValueType().is64BitVector() &&
2575 "unexpected types for extended operands to VMULL");
2576 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2577 }
2578 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2579 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2580 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2581 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2582 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2583 EVT Op1VT = Op1.getValueType();
2584 return DAG.getNode(N0->getOpcode(), DL, VT,
2585 DAG.getNode(NewOpc, DL, VT,
2586 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2587 DAG.getNode(NewOpc, DL, VT,
2588 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2589}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002590
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +00002591// Lower vector multiply high (ISD::MULHS and ISD::MULHU).
2592static SDValue LowerMULH(SDValue Op, SelectionDAG &DAG) {
2593 // Multiplications are only custom-lowered for 128-bit vectors so that
2594 // {S,U}MULL{2} can be detected. Otherwise v2i64 multiplications are not
2595 // legal.
2596 EVT VT = Op.getValueType();
2597 assert(VT.is128BitVector() && VT.isInteger() &&
2598 "unexpected type for custom-lowering ISD::MULH{U,S}");
2599
2600 SDValue V0 = Op.getOperand(0);
2601 SDValue V1 = Op.getOperand(1);
2602
2603 SDLoc DL(Op);
2604
2605 EVT ExtractVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
2606
2607 // We turn (V0 mulhs/mulhu V1) to:
2608 //
2609 // (uzp2 (smull (extract_subvector (ExtractVT V128:V0, (i64 0)),
2610 // (extract_subvector (ExtractVT V128:V1, (i64 0))))),
2611 // (smull (extract_subvector (ExtractVT V128:V0, (i64 VMull2Idx)),
2612 // (extract_subvector (ExtractVT V128:V2, (i64 VMull2Idx))))))
2613 //
2614 // Where ExtractVT is a subvector with half number of elements, and
2615 // VMullIdx2 is the index of the middle element (the high part).
2616 //
2617 // The vector hight part extract and multiply will be matched against
2618 // {S,U}MULL{v16i8_v8i16,v8i16_v4i32,v4i32_v2i64} which in turn will
2619 // issue a {s}mull2 instruction.
2620 //
2621 // This basically multiply the lower subvector with '{s,u}mull', the high
2622 // subvector with '{s,u}mull2', and shuffle both results high part in
2623 // resulting vector.
2624 unsigned Mull2VectorIdx = VT.getVectorNumElements () / 2;
2625 SDValue VMullIdx = DAG.getConstant(0, DL, MVT::i64);
2626 SDValue VMull2Idx = DAG.getConstant(Mull2VectorIdx, DL, MVT::i64);
2627
2628 SDValue VMullV0 =
2629 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMullIdx);
2630 SDValue VMullV1 =
2631 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMullIdx);
2632
2633 SDValue VMull2V0 =
2634 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMull2Idx);
2635 SDValue VMull2V1 =
2636 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMull2Idx);
2637
2638 unsigned MullOpc = Op.getOpcode() == ISD::MULHS ? AArch64ISD::SMULL
2639 : AArch64ISD::UMULL;
2640
2641 EVT MullVT = ExtractVT.widenIntegerVectorElementType(*DAG.getContext());
2642 SDValue Mull = DAG.getNode(MullOpc, DL, MullVT, VMullV0, VMullV1);
2643 SDValue Mull2 = DAG.getNode(MullOpc, DL, MullVT, VMull2V0, VMull2V1);
2644
2645 Mull = DAG.getNode(ISD::BITCAST, DL, VT, Mull);
2646 Mull2 = DAG.getNode(ISD::BITCAST, DL, VT, Mull2);
2647
2648 return DAG.getNode(AArch64ISD::UZP2, DL, VT, Mull, Mull2);
2649}
2650
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002651SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2652 SelectionDAG &DAG) const {
2653 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2654 SDLoc dl(Op);
2655 switch (IntNo) {
2656 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002657 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002658 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2659 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2660 }
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +00002661 case Intrinsic::aarch64_neon_abs:
2662 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2663 Op.getOperand(1));
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002664 case Intrinsic::aarch64_neon_smax:
2665 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2666 Op.getOperand(1), Op.getOperand(2));
2667 case Intrinsic::aarch64_neon_umax:
2668 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2669 Op.getOperand(1), Op.getOperand(2));
2670 case Intrinsic::aarch64_neon_smin:
2671 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2672 Op.getOperand(1), Op.getOperand(2));
2673 case Intrinsic::aarch64_neon_umin:
2674 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2675 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002676 }
2677}
2678
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002679// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2680static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2681 EVT VT, EVT MemVT,
2682 SelectionDAG &DAG) {
2683 assert(VT.isVector() && "VT should be a vector type");
2684 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2685
2686 SDValue Value = ST->getValue();
2687
2688 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2689 // the word lane which represent the v4i8 subvector. It optimizes the store
2690 // to:
2691 //
2692 // xtn v0.8b, v0.8h
2693 // str s0, [x0]
2694
2695 SDValue Undef = DAG.getUNDEF(MVT::i16);
2696 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2697 {Undef, Undef, Undef, Undef});
2698
2699 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2700 Value, UndefVec);
2701 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2702
2703 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2704 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2705 Trunc, DAG.getConstant(0, DL, MVT::i64));
2706
2707 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2708 ST->getBasePtr(), ST->getMemOperand());
2709}
2710
2711// Custom lowering for any store, vector or scalar and/or default or with
2712// a truncate operations. Currently only custom lower truncate operation
2713// from vector v4i16 to v4i8.
2714SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2715 SelectionDAG &DAG) const {
2716 SDLoc Dl(Op);
2717 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2718 assert (StoreNode && "Can only custom lower store nodes");
2719
2720 SDValue Value = StoreNode->getValue();
2721
2722 EVT VT = Value.getValueType();
2723 EVT MemVT = StoreNode->getMemoryVT();
2724
2725 assert (VT.isVector() && "Can only custom lower vector store types");
2726
2727 unsigned AS = StoreNode->getAddressSpace();
2728 unsigned Align = StoreNode->getAlignment();
2729 if (Align < MemVT.getStoreSize() &&
2730 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2731 return scalarizeVectorStore(StoreNode, DAG);
2732 }
2733
2734 if (StoreNode->isTruncatingStore()) {
2735 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2736 }
2737
2738 return SDValue();
2739}
2740
Tim Northover3b0846e2014-05-24 12:50:23 +00002741SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2742 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002743 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2744 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002745
Tim Northover3b0846e2014-05-24 12:50:23 +00002746 switch (Op.getOpcode()) {
2747 default:
2748 llvm_unreachable("unimplemented operand");
2749 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002750 case ISD::BITCAST:
2751 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002752 case ISD::GlobalAddress:
2753 return LowerGlobalAddress(Op, DAG);
2754 case ISD::GlobalTLSAddress:
2755 return LowerGlobalTLSAddress(Op, DAG);
2756 case ISD::SETCC:
2757 return LowerSETCC(Op, DAG);
2758 case ISD::BR_CC:
2759 return LowerBR_CC(Op, DAG);
2760 case ISD::SELECT:
2761 return LowerSELECT(Op, DAG);
2762 case ISD::SELECT_CC:
2763 return LowerSELECT_CC(Op, DAG);
2764 case ISD::JumpTable:
2765 return LowerJumpTable(Op, DAG);
2766 case ISD::ConstantPool:
2767 return LowerConstantPool(Op, DAG);
2768 case ISD::BlockAddress:
2769 return LowerBlockAddress(Op, DAG);
2770 case ISD::VASTART:
2771 return LowerVASTART(Op, DAG);
2772 case ISD::VACOPY:
2773 return LowerVACOPY(Op, DAG);
2774 case ISD::VAARG:
2775 return LowerVAARG(Op, DAG);
2776 case ISD::ADDC:
2777 case ISD::ADDE:
2778 case ISD::SUBC:
2779 case ISD::SUBE:
2780 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2781 case ISD::SADDO:
2782 case ISD::UADDO:
2783 case ISD::SSUBO:
2784 case ISD::USUBO:
2785 case ISD::SMULO:
2786 case ISD::UMULO:
2787 return LowerXALUO(Op, DAG);
2788 case ISD::FADD:
2789 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2790 case ISD::FSUB:
2791 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2792 case ISD::FMUL:
2793 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2794 case ISD::FDIV:
2795 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2796 case ISD::FP_ROUND:
2797 return LowerFP_ROUND(Op, DAG);
2798 case ISD::FP_EXTEND:
2799 return LowerFP_EXTEND(Op, DAG);
2800 case ISD::FRAMEADDR:
2801 return LowerFRAMEADDR(Op, DAG);
2802 case ISD::RETURNADDR:
2803 return LowerRETURNADDR(Op, DAG);
2804 case ISD::INSERT_VECTOR_ELT:
2805 return LowerINSERT_VECTOR_ELT(Op, DAG);
2806 case ISD::EXTRACT_VECTOR_ELT:
2807 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2808 case ISD::BUILD_VECTOR:
2809 return LowerBUILD_VECTOR(Op, DAG);
2810 case ISD::VECTOR_SHUFFLE:
2811 return LowerVECTOR_SHUFFLE(Op, DAG);
2812 case ISD::EXTRACT_SUBVECTOR:
2813 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2814 case ISD::SRA:
2815 case ISD::SRL:
2816 case ISD::SHL:
2817 return LowerVectorSRA_SRL_SHL(Op, DAG);
2818 case ISD::SHL_PARTS:
2819 return LowerShiftLeftParts(Op, DAG);
2820 case ISD::SRL_PARTS:
2821 case ISD::SRA_PARTS:
2822 return LowerShiftRightParts(Op, DAG);
2823 case ISD::CTPOP:
2824 return LowerCTPOP(Op, DAG);
2825 case ISD::FCOPYSIGN:
2826 return LowerFCOPYSIGN(Op, DAG);
2827 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002828 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002829 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002830 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002831 case ISD::XOR:
2832 return LowerXOR(Op, DAG);
2833 case ISD::PREFETCH:
2834 return LowerPREFETCH(Op, DAG);
2835 case ISD::SINT_TO_FP:
2836 case ISD::UINT_TO_FP:
2837 return LowerINT_TO_FP(Op, DAG);
2838 case ISD::FP_TO_SINT:
2839 case ISD::FP_TO_UINT:
2840 return LowerFP_TO_INT(Op, DAG);
2841 case ISD::FSINCOS:
2842 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002843 case ISD::FLT_ROUNDS_:
2844 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002845 case ISD::MUL:
2846 return LowerMUL(Op, DAG);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +00002847 case ISD::MULHS:
2848 case ISD::MULHU:
2849 return LowerMULH(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002850 case ISD::INTRINSIC_WO_CHAIN:
2851 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002852 case ISD::STORE:
2853 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002854 case ISD::VECREDUCE_ADD:
2855 case ISD::VECREDUCE_SMAX:
2856 case ISD::VECREDUCE_SMIN:
2857 case ISD::VECREDUCE_UMAX:
2858 case ISD::VECREDUCE_UMIN:
2859 case ISD::VECREDUCE_FMAX:
2860 case ISD::VECREDUCE_FMIN:
2861 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002862 case ISD::ATOMIC_LOAD_SUB:
2863 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002864 case ISD::ATOMIC_LOAD_AND:
2865 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002866 case ISD::DYNAMIC_STACKALLOC:
2867 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002868 }
2869}
2870
Tim Northover3b0846e2014-05-24 12:50:23 +00002871//===----------------------------------------------------------------------===//
2872// Calling Convention Implementation
2873//===----------------------------------------------------------------------===//
2874
2875#include "AArch64GenCallingConv.inc"
2876
Robin Morisset039781e2014-08-29 21:53:01 +00002877/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002878CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2879 bool IsVarArg) const {
2880 switch (CC) {
2881 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002882 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002883 case CallingConv::WebKit_JS:
2884 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002885 case CallingConv::GHC:
2886 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002887 case CallingConv::C:
2888 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002889 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002890 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002891 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002892 if (Subtarget->isTargetWindows() && IsVarArg)
2893 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002894 if (!Subtarget->isTargetDarwin())
2895 return CC_AArch64_AAPCS;
2896 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002897 case CallingConv::Win64:
2898 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00002899 case CallingConv::AArch64_VectorCall:
2900 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002901 }
2902}
2903
Tim Northover406024a2016-08-10 21:44:01 +00002904CCAssignFn *
2905AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2906 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2907 : RetCC_AArch64_AAPCS;
2908}
2909
Tim Northover3b0846e2014-05-24 12:50:23 +00002910SDValue AArch64TargetLowering::LowerFormalArguments(
2911 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002912 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2913 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002914 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002915 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00002916 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002917
2918 // Assign locations to all of the incoming arguments.
2919 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002920 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2921 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002922
2923 // At this point, Ins[].VT may already be promoted to i32. To correctly
2924 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2925 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2926 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2927 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2928 // LocVT.
2929 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00002930 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00002931 unsigned CurArgIdx = 0;
2932 for (unsigned i = 0; i != NumArgs; ++i) {
2933 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002934 if (Ins[i].isOrigArg()) {
2935 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2936 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002937
Andrew Trick05938a52015-02-16 18:10:47 +00002938 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002939 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2940 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002941 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2942 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2943 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2944 ValVT = MVT::i8;
2945 else if (ActualMVT == MVT::i16)
2946 ValVT = MVT::i16;
2947 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002948 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2949 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002950 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002951 assert(!Res && "Call operand has unhandled type");
2952 (void)Res;
2953 }
2954 assert(ArgLocs.size() == Ins.size());
2955 SmallVector<SDValue, 16> ArgValues;
2956 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2957 CCValAssign &VA = ArgLocs[i];
2958
2959 if (Ins[i].Flags.isByVal()) {
2960 // Byval is used for HFAs in the PCS, but the system should work in a
2961 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002962 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002963 int Size = Ins[i].Flags.getByValSize();
2964 unsigned NumRegs = (Size + 7) / 8;
2965
2966 // FIXME: This works on big-endian for composite byvals, which are the common
2967 // case. It should also work for fundamental types too.
2968 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002969 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002970 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002971 InVals.push_back(FrameIdxN);
2972
2973 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002974 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002975
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002976 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002977 // Arguments stored in registers.
2978 EVT RegVT = VA.getLocVT();
2979
2980 SDValue ArgValue;
2981 const TargetRegisterClass *RC;
2982
2983 if (RegVT == MVT::i32)
2984 RC = &AArch64::GPR32RegClass;
2985 else if (RegVT == MVT::i64)
2986 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002987 else if (RegVT == MVT::f16)
2988 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002989 else if (RegVT == MVT::f32)
2990 RC = &AArch64::FPR32RegClass;
2991 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2992 RC = &AArch64::FPR64RegClass;
2993 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2994 RC = &AArch64::FPR128RegClass;
2995 else
2996 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2997
2998 // Transform the arguments in physical registers into virtual ones.
2999 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3000 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3001
3002 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3003 // to 64 bits. Insert an assert[sz]ext to capture this, then
3004 // truncate to the right size.
3005 switch (VA.getLocInfo()) {
3006 default:
3007 llvm_unreachable("Unknown loc info!");
3008 case CCValAssign::Full:
3009 break;
3010 case CCValAssign::BCvt:
3011 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3012 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003013 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003014 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003015 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003016 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3017 // nodes after our lowering.
3018 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003019 break;
3020 }
3021
3022 InVals.push_back(ArgValue);
3023
3024 } else { // VA.isRegLoc()
3025 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3026 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003027 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003028
3029 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003030 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3031 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003032 BEAlign = 8 - ArgSize;
3033
Matthias Braun941a7052016-07-28 18:40:00 +00003034 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003035
3036 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003037 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003038 SDValue ArgValue;
3039
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003040 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003041 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003042 MVT MemVT = VA.getValVT();
3043
Tim Northover47e003c2014-05-26 17:21:53 +00003044 switch (VA.getLocInfo()) {
3045 default:
3046 break;
Tim Northover6890add2014-06-03 13:54:53 +00003047 case CCValAssign::BCvt:
3048 MemVT = VA.getLocVT();
3049 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003050 case CCValAssign::SExt:
3051 ExtType = ISD::SEXTLOAD;
3052 break;
3053 case CCValAssign::ZExt:
3054 ExtType = ISD::ZEXTLOAD;
3055 break;
3056 case CCValAssign::AExt:
3057 ExtType = ISD::EXTLOAD;
3058 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003059 }
3060
Alex Lorenze40c8a22015-08-11 23:09:45 +00003061 ArgValue = DAG.getExtLoad(
3062 ExtType, DL, VA.getLocVT(), Chain, FIN,
3063 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003064 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003065
Tim Northover3b0846e2014-05-24 12:50:23 +00003066 InVals.push_back(ArgValue);
3067 }
3068 }
3069
3070 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003071 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003072 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003073 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003074 // The AAPCS variadic function ABI is identical to the non-variadic
3075 // one. As a result there may be more arguments in registers and we should
3076 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003077 // Win64 variadic functions also pass arguments in registers, but all float
3078 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003079 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3080 }
3081
Tim Northover3b0846e2014-05-24 12:50:23 +00003082 // This will point to the next argument passed via stack.
3083 unsigned StackOffset = CCInfo.getNextStackOffset();
3084 // We currently pass all varargs at 8-byte alignment.
3085 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003086 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00003087 }
3088
Tim Northover3b0846e2014-05-24 12:50:23 +00003089 unsigned StackArgSize = CCInfo.getNextStackOffset();
3090 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3091 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3092 // This is a non-standard ABI so by fiat I say we're allowed to make full
3093 // use of the stack area to be popped, which must be aligned to 16 bytes in
3094 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003095 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003096
3097 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3098 // a multiple of 16.
3099 FuncInfo->setArgumentStackToRestore(StackArgSize);
3100
3101 // This realignment carries over to the available bytes below. Our own
3102 // callers will guarantee the space is free by giving an aligned value to
3103 // CALLSEQ_START.
3104 }
3105 // Even if we're not expected to free up the space, it's useful to know how
3106 // much is there while considering tail calls (because we can reuse it).
3107 FuncInfo->setBytesInStackArgArea(StackArgSize);
3108
3109 return Chain;
3110}
3111
3112void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003113 SelectionDAG &DAG,
3114 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003115 SDValue &Chain) const {
3116 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003117 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003118 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003119 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003120 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003121
3122 SmallVector<SDValue, 8> MemOps;
3123
3124 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3125 AArch64::X3, AArch64::X4, AArch64::X5,
3126 AArch64::X6, AArch64::X7 };
3127 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003128 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003129
3130 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3131 int GPRIdx = 0;
3132 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003133 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003134 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003135 if (GPRSaveSize & 15)
3136 // The extra size here, if triggered, will always be 8.
3137 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3138 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003139 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003140
Mehdi Amini44ede332015-07-09 02:09:04 +00003141 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003142
3143 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3144 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3145 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003146 SDValue Store = DAG.getStore(
3147 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003148 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003149 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3150 GPRIdx,
3151 (i - FirstVariadicGPR) * 8)
3152 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003153 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003154 FIN =
3155 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003156 }
3157 }
3158 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3159 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3160
Martin Storsjo2f24e932017-07-17 20:05:19 +00003161 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003162 static const MCPhysReg FPRArgRegs[] = {
3163 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3164 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3165 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003166 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003167
3168 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3169 int FPRIdx = 0;
3170 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003171 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003172
Mehdi Amini44ede332015-07-09 02:09:04 +00003173 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003174
3175 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3176 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3177 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3178
Alex Lorenze40c8a22015-08-11 23:09:45 +00003179 SDValue Store = DAG.getStore(
3180 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003181 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003182 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003183 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3184 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003185 }
3186 }
3187 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3188 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3189 }
3190
3191 if (!MemOps.empty()) {
3192 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3193 }
3194}
3195
3196/// LowerCallResult - Lower the result values of a call into the
3197/// appropriate copies out of appropriate physical registers.
3198SDValue AArch64TargetLowering::LowerCallResult(
3199 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003200 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3201 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003202 SDValue ThisVal) const {
3203 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3204 ? RetCC_AArch64_WebKit_JS
3205 : RetCC_AArch64_AAPCS;
3206 // Assign locations to each value returned by this call.
3207 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003208 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3209 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003210 CCInfo.AnalyzeCallResult(Ins, RetCC);
3211
3212 // Copy all of the result registers out of their specified physreg.
3213 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3214 CCValAssign VA = RVLocs[i];
3215
3216 // Pass 'this' value directly from the argument to return value, to avoid
3217 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003218 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003219 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3220 "unexpected return calling convention register assignment");
3221 InVals.push_back(ThisVal);
3222 continue;
3223 }
3224
3225 SDValue Val =
3226 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3227 Chain = Val.getValue(1);
3228 InFlag = Val.getValue(2);
3229
3230 switch (VA.getLocInfo()) {
3231 default:
3232 llvm_unreachable("Unknown loc info!");
3233 case CCValAssign::Full:
3234 break;
3235 case CCValAssign::BCvt:
3236 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3237 break;
3238 }
3239
3240 InVals.push_back(Val);
3241 }
3242
3243 return Chain;
3244}
3245
Matthias Braun1af14142016-09-13 19:27:38 +00003246/// Return true if the calling convention is one that we can guarantee TCO for.
3247static bool canGuaranteeTCO(CallingConv::ID CC) {
3248 return CC == CallingConv::Fast;
3249}
3250
3251/// Return true if we might ever do TCO for calls with this calling convention.
3252static bool mayTailCallThisCC(CallingConv::ID CC) {
3253 switch (CC) {
3254 case CallingConv::C:
3255 case CallingConv::PreserveMost:
3256 case CallingConv::Swift:
3257 return true;
3258 default:
3259 return canGuaranteeTCO(CC);
3260 }
3261}
3262
Tim Northover3b0846e2014-05-24 12:50:23 +00003263bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3264 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003265 const SmallVectorImpl<ISD::OutputArg> &Outs,
3266 const SmallVectorImpl<SDValue> &OutVals,
3267 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003268 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003269 return false;
3270
Matthias Braun8d414362016-03-30 22:46:04 +00003271 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003272 const Function &CallerF = MF.getFunction();
3273 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003274 bool CCMatch = CallerCC == CalleeCC;
3275
3276 // Byval parameters hand the function a pointer directly into the stack area
3277 // we want to reuse during a tail call. Working around this *is* possible (see
3278 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003279 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3280 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003281 i != e; ++i)
3282 if (i->hasByValAttr())
3283 return false;
3284
Matthias Braun1af14142016-09-13 19:27:38 +00003285 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3286 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003287
Oliver Stannard12993dd2014-08-18 12:42:15 +00003288 // Externally-defined functions with weak linkage should not be
3289 // tail-called on AArch64 when the OS does not support dynamic
3290 // pre-emption of symbols, as the AAELF spec requires normal calls
3291 // to undefined weak functions to be replaced with a NOP or jump to the
3292 // next instruction. The behaviour of branch instructions in this
3293 // situation (as used for tail calls) is implementation-defined, so we
3294 // cannot rely on the linker replacing the tail call with a return.
3295 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3296 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003297 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003298 if (GV->hasExternalWeakLinkage() &&
3299 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003300 return false;
3301 }
3302
Tim Northover3b0846e2014-05-24 12:50:23 +00003303 // Now we search for cases where we can use a tail call without changing the
3304 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3305 // concept.
3306
3307 // I want anyone implementing a new calling convention to think long and hard
3308 // about this assert.
3309 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3310 "Unexpected variadic calling convention");
3311
Matthias Braun8d414362016-03-30 22:46:04 +00003312 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003313 if (isVarArg && !Outs.empty()) {
3314 // At least two cases here: if caller is fastcc then we can't have any
3315 // memory arguments (we'd be expected to clean up the stack afterwards). If
3316 // caller is C then we could potentially use its argument area.
3317
3318 // FIXME: for now we take the most conservative of these in both cases:
3319 // disallow all variadic memory operands.
3320 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003321 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003322
3323 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003324 for (const CCValAssign &ArgLoc : ArgLocs)
3325 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003326 return false;
3327 }
3328
Matthias Braun8d414362016-03-30 22:46:04 +00003329 // Check that the call results are passed in the same way.
3330 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3331 CCAssignFnForCall(CalleeCC, isVarArg),
3332 CCAssignFnForCall(CallerCC, isVarArg)))
3333 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003334 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003335 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3336 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003337 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003338 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3339 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003340 return false;
3341 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003342
3343 // Nothing more to check if the callee is taking no arguments
3344 if (Outs.empty())
3345 return true;
3346
3347 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003348 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003349
3350 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3351
3352 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3353
Matthias Braun74a0bd32016-04-13 21:43:16 +00003354 // If the stack arguments for this call do not fit into our own save area then
3355 // the call cannot be made tail.
3356 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3357 return false;
3358
Matthias Braun46b0f032016-04-14 01:10:42 +00003359 const MachineRegisterInfo &MRI = MF.getRegInfo();
3360 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3361 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003362
3363 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003364}
3365
3366SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3367 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003368 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003369 int ClobberedFI) const {
3370 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003371 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3372 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003373
3374 // Include the original chain at the beginning of the list. When this is
3375 // used by target LowerCall hooks, this helps legalize find the
3376 // CALLSEQ_BEGIN node.
3377 ArgChains.push_back(Chain);
3378
3379 // Add a chain value for each stack argument corresponding
3380 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3381 UE = DAG.getEntryNode().getNode()->use_end();
3382 U != UE; ++U)
3383 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3384 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3385 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003386 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003387 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003388 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003389
3390 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3391 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3392 ArgChains.push_back(SDValue(L, 1));
3393 }
3394
3395 // Build a tokenfactor for all the chains.
3396 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3397}
3398
3399bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3400 bool TailCallOpt) const {
3401 return CallCC == CallingConv::Fast && TailCallOpt;
3402}
3403
Tim Northover3b0846e2014-05-24 12:50:23 +00003404/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3405/// and add input and output parameter nodes.
3406SDValue
3407AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3408 SmallVectorImpl<SDValue> &InVals) const {
3409 SelectionDAG &DAG = CLI.DAG;
3410 SDLoc &DL = CLI.DL;
3411 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3412 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3413 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3414 SDValue Chain = CLI.Chain;
3415 SDValue Callee = CLI.Callee;
3416 bool &IsTailCall = CLI.IsTailCall;
3417 CallingConv::ID CallConv = CLI.CallConv;
3418 bool IsVarArg = CLI.IsVarArg;
3419
3420 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003421 bool IsThisReturn = false;
3422
3423 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3424 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3425 bool IsSibCall = false;
3426
3427 if (IsTailCall) {
3428 // Check if it's really possible to do a tail call.
3429 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003430 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003431 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003432 report_fatal_error("failed to perform tail call elimination on a call "
3433 "site marked musttail");
3434
3435 // A sibling call is one where we're under the usual C ABI and not planning
3436 // to change that but can still do a tail call:
3437 if (!TailCallOpt && IsTailCall)
3438 IsSibCall = true;
3439
3440 if (IsTailCall)
3441 ++NumTailCalls;
3442 }
3443
3444 // Analyze operands of the call, assigning locations to each operand.
3445 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003446 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3447 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003448
3449 if (IsVarArg) {
3450 // Handle fixed and variable vector arguments differently.
3451 // Variable vector arguments always go into memory.
3452 unsigned NumArgs = Outs.size();
3453
3454 for (unsigned i = 0; i != NumArgs; ++i) {
3455 MVT ArgVT = Outs[i].VT;
3456 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3457 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3458 /*IsVarArg=*/ !Outs[i].IsFixed);
3459 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3460 assert(!Res && "Call operand has unhandled type");
3461 (void)Res;
3462 }
3463 } else {
3464 // At this point, Outs[].VT may already be promoted to i32. To correctly
3465 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3466 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3467 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3468 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3469 // LocVT.
3470 unsigned NumArgs = Outs.size();
3471 for (unsigned i = 0; i != NumArgs; ++i) {
3472 MVT ValVT = Outs[i].VT;
3473 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003474 EVT ActualVT = getValueType(DAG.getDataLayout(),
3475 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003476 /*AllowUnknown*/ true);
3477 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3478 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3479 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003480 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003481 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003482 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003483 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003484
3485 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003486 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003487 assert(!Res && "Call operand has unhandled type");
3488 (void)Res;
3489 }
3490 }
3491
3492 // Get a count of how many bytes are to be pushed on the stack.
3493 unsigned NumBytes = CCInfo.getNextStackOffset();
3494
3495 if (IsSibCall) {
3496 // Since we're not changing the ABI to make this a tail call, the memory
3497 // operands are already available in the caller's incoming argument space.
3498 NumBytes = 0;
3499 }
3500
3501 // FPDiff is the byte offset of the call's argument area from the callee's.
3502 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3503 // by this amount for a tail call. In a sibling call it must be 0 because the
3504 // caller will deallocate the entire stack and the callee still expects its
3505 // arguments to begin at SP+0. Completely unused for non-tail calls.
3506 int FPDiff = 0;
3507
3508 if (IsTailCall && !IsSibCall) {
3509 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3510
3511 // Since callee will pop argument stack as a tail call, we must keep the
3512 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003513 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003514
3515 // FPDiff will be negative if this tail call requires more space than we
3516 // would automatically have in our incoming argument space. Positive if we
3517 // can actually shrink the stack.
3518 FPDiff = NumReusableBytes - NumBytes;
3519
3520 // The stack pointer must be 16-byte aligned at all times it's used for a
3521 // memory operation, which in practice means at *all* times and in
3522 // particular across call boundaries. Therefore our own arguments started at
3523 // a 16-byte aligned SP and the delta applied for the tail call should
3524 // satisfy the same constraint.
3525 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3526 }
3527
3528 // Adjust the stack pointer for the new arguments...
3529 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003530 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003531 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003532
Mehdi Amini44ede332015-07-09 02:09:04 +00003533 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3534 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003535
3536 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3537 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003538 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003539
3540 // Walk the register/memloc assignments, inserting copies/loads.
3541 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3542 ++i, ++realArgIdx) {
3543 CCValAssign &VA = ArgLocs[i];
3544 SDValue Arg = OutVals[realArgIdx];
3545 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3546
3547 // Promote the value if needed.
3548 switch (VA.getLocInfo()) {
3549 default:
3550 llvm_unreachable("Unknown loc info!");
3551 case CCValAssign::Full:
3552 break;
3553 case CCValAssign::SExt:
3554 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3555 break;
3556 case CCValAssign::ZExt:
3557 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3558 break;
3559 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003560 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3561 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3562 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3563 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3564 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003565 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3566 break;
3567 case CCValAssign::BCvt:
3568 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3569 break;
3570 case CCValAssign::FPExt:
3571 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3572 break;
3573 }
3574
3575 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003576 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3577 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003578 assert(VA.getLocVT() == MVT::i64 &&
3579 "unexpected calling convention register assignment");
3580 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3581 "unexpected use of 'returned'");
3582 IsThisReturn = true;
3583 }
3584 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3585 } else {
3586 assert(VA.isMemLoc());
3587
3588 SDValue DstAddr;
3589 MachinePointerInfo DstInfo;
3590
3591 // FIXME: This works on big-endian for composite byvals, which are the
3592 // common case. It should also work for fundamental types too.
3593 uint32_t BEAlign = 0;
3594 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003595 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003596 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003597 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3598 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003599 if (OpSize < 8)
3600 BEAlign = 8 - OpSize;
3601 }
3602 unsigned LocMemOffset = VA.getLocMemOffset();
3603 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003604 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003605 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003606
3607 if (IsTailCall) {
3608 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003609 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003610
Mehdi Amini44ede332015-07-09 02:09:04 +00003611 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003612 DstInfo =
3613 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003614
3615 // Make sure any stack arguments overlapping with where we're storing
3616 // are loaded before this eventual operation. Otherwise they'll be
3617 // clobbered.
3618 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3619 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003620 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003621
Mehdi Amini44ede332015-07-09 02:09:04 +00003622 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003623 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3624 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003625 }
3626
3627 if (Outs[i].Flags.isByVal()) {
3628 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003629 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003630 SDValue Cpy = DAG.getMemcpy(
3631 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003632 /*isVol = */ false, /*AlwaysInline = */ false,
3633 /*isTailCall = */ false,
3634 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003635
3636 MemOpChains.push_back(Cpy);
3637 } else {
3638 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3639 // promoted to a legal register type i32, we should truncate Arg back to
3640 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003641 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3642 VA.getValVT() == MVT::i16)
3643 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003644
Justin Lebar9c375812016-07-15 18:27:10 +00003645 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003646 MemOpChains.push_back(Store);
3647 }
3648 }
3649 }
3650
3651 if (!MemOpChains.empty())
3652 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3653
3654 // Build a sequence of copy-to-reg nodes chained together with token chain
3655 // and flag operands which copy the outgoing args into the appropriate regs.
3656 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003657 for (auto &RegToPass : RegsToPass) {
3658 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3659 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003660 InFlag = Chain.getValue(1);
3661 }
3662
3663 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3664 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3665 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003666 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3667 auto GV = G->getGlobal();
3668 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3669 AArch64II::MO_GOT) {
3670 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3671 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003672 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3673 assert(Subtarget->isTargetWindows() &&
3674 "Windows is the only supported COFF target");
3675 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003676 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003677 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003678 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3679 }
3680 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3681 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3682 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003683 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003684 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3685 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003686 } else {
3687 const char *Sym = S->getSymbol();
3688 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003689 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003690 }
3691
3692 // We don't usually want to end the call-sequence here because we would tidy
3693 // the frame up *after* the call, however in the ABI-changing tail-call case
3694 // we've carefully laid out the parameters so that when sp is reset they'll be
3695 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003696 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003697 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3698 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003699 InFlag = Chain.getValue(1);
3700 }
3701
3702 std::vector<SDValue> Ops;
3703 Ops.push_back(Chain);
3704 Ops.push_back(Callee);
3705
3706 if (IsTailCall) {
3707 // Each tail call may have to adjust the stack by a different amount, so
3708 // this information must travel along with the operation for eventual
3709 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003710 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003711 }
3712
3713 // Add argument registers to the end of the list so that they are known live
3714 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003715 for (auto &RegToPass : RegsToPass)
3716 Ops.push_back(DAG.getRegister(RegToPass.first,
3717 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003718
3719 // Add a register mask operand representing the call-preserved registers.
3720 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003721 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003722 if (IsThisReturn) {
3723 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003724 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003725 if (!Mask) {
3726 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003727 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003728 }
3729 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003730 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003731
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003732 if (TRI->isAnyArgRegReserved(MF))
3733 TRI->emitReservedArgRegCallError(MF);
3734
Tim Northover3b0846e2014-05-24 12:50:23 +00003735 assert(Mask && "Missing call preserved mask for calling convention");
3736 Ops.push_back(DAG.getRegisterMask(Mask));
3737
3738 if (InFlag.getNode())
3739 Ops.push_back(InFlag);
3740
3741 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3742
3743 // If we're doing a tall call, use a TC_RETURN here rather than an
3744 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003745 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003746 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003747 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003748 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003749
3750 // Returns a chain and a flag for retval copy to use.
3751 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3752 InFlag = Chain.getValue(1);
3753
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003754 uint64_t CalleePopBytes =
3755 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003756
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003757 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3758 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3759 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003760 if (!Ins.empty())
3761 InFlag = Chain.getValue(1);
3762
3763 // Handle result values, copying them out of physregs into vregs that we
3764 // return.
3765 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3766 InVals, IsThisReturn,
3767 IsThisReturn ? OutVals[0] : SDValue());
3768}
3769
3770bool AArch64TargetLowering::CanLowerReturn(
3771 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3772 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3773 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3774 ? RetCC_AArch64_WebKit_JS
3775 : RetCC_AArch64_AAPCS;
3776 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003777 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003778 return CCInfo.CheckReturn(Outs, RetCC);
3779}
3780
3781SDValue
3782AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3783 bool isVarArg,
3784 const SmallVectorImpl<ISD::OutputArg> &Outs,
3785 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003786 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003787 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3788 ? RetCC_AArch64_WebKit_JS
3789 : RetCC_AArch64_AAPCS;
3790 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003791 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3792 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003793 CCInfo.AnalyzeReturn(Outs, RetCC);
3794
3795 // Copy the result values into the output registers.
3796 SDValue Flag;
3797 SmallVector<SDValue, 4> RetOps(1, Chain);
3798 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3799 ++i, ++realRVLocIdx) {
3800 CCValAssign &VA = RVLocs[i];
3801 assert(VA.isRegLoc() && "Can only return in registers!");
3802 SDValue Arg = OutVals[realRVLocIdx];
3803
3804 switch (VA.getLocInfo()) {
3805 default:
3806 llvm_unreachable("Unknown loc info!");
3807 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003808 if (Outs[i].ArgVT == MVT::i1) {
3809 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3810 // value. This is strictly redundant on Darwin (which uses "zeroext
3811 // i1"), but will be optimised out before ISel.
3812 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3813 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3814 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003815 break;
3816 case CCValAssign::BCvt:
3817 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3818 break;
3819 }
3820
3821 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3822 Flag = Chain.getValue(1);
3823 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3824 }
Manman Rencbe4f942015-12-16 21:04:19 +00003825 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3826 const MCPhysReg *I =
3827 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3828 if (I) {
3829 for (; *I; ++I) {
3830 if (AArch64::GPR64RegClass.contains(*I))
3831 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3832 else if (AArch64::FPR64RegClass.contains(*I))
3833 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3834 else
3835 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3836 }
3837 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003838
3839 RetOps[0] = Chain; // Update chain.
3840
3841 // Add the flag if we have it.
3842 if (Flag.getNode())
3843 RetOps.push_back(Flag);
3844
3845 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3846}
3847
3848//===----------------------------------------------------------------------===//
3849// Other Lowering Code
3850//===----------------------------------------------------------------------===//
3851
Joel Jonesa7c4a522017-04-21 17:31:03 +00003852SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3853 SelectionDAG &DAG,
3854 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003855 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3856 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003857}
3858
3859SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3860 SelectionDAG &DAG,
3861 unsigned Flag) const {
3862 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3863}
3864
3865SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3866 SelectionDAG &DAG,
3867 unsigned Flag) const {
3868 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3869 N->getOffset(), Flag);
3870}
3871
3872SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3873 SelectionDAG &DAG,
3874 unsigned Flag) const {
3875 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3876}
3877
3878// (loadGOT sym)
3879template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003880SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3881 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003882 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003883 SDLoc DL(N);
3884 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003885 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003886 // FIXME: Once remat is capable of dealing with instructions with register
3887 // operands, expand this into two nodes instead of using a wrapper node.
3888 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3889}
3890
3891// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3892template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003893SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3894 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003895 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003896 SDLoc DL(N);
3897 EVT Ty = getPointerTy(DAG.getDataLayout());
3898 const unsigned char MO_NC = AArch64II::MO_NC;
3899 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003900 AArch64ISD::WrapperLarge, DL, Ty,
3901 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3902 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3903 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3904 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00003905}
3906
3907// (addlow (adrp %hi(sym)) %lo(sym))
3908template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003909SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3910 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003911 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003912 SDLoc DL(N);
3913 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003914 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003915 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003916 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003917 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3918 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3919}
3920
David Green9dd1d452018-08-22 11:31:39 +00003921// (adr sym)
3922template <class NodeTy>
3923SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
3924 unsigned Flags) const {
3925 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
3926 SDLoc DL(N);
3927 EVT Ty = getPointerTy(DAG.getDataLayout());
3928 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
3929 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
3930}
3931
Tim Northover3b0846e2014-05-24 12:50:23 +00003932SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3933 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003934 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003935 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003936 unsigned char OpFlags =
3937 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00003938
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003939 if (OpFlags != AArch64II::MO_NO_FLAG)
3940 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3941 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00003942
David Green9dd1d452018-08-22 11:31:39 +00003943 // This also catches the large code model case for Darwin, and tiny code
3944 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00003945 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00003946 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003947 }
3948
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003949 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00003950 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00003951 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00003952 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00003953 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003954 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00003955 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003956 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003957 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3958 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00003959 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003960 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3961 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3962 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00003963}
3964
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003965/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00003966/// and calls to compute the variable's address (for Darwin, currently) and
3967/// return an SDValue containing the final node.
3968
3969/// Darwin only has one TLS scheme which must be capable of dealing with the
3970/// fully general situation, in the worst case. This means:
3971/// + "extern __thread" declaration.
3972/// + Defined in a possibly unknown dynamic library.
3973///
3974/// The general system is that each __thread variable has a [3 x i64] descriptor
3975/// which contains information used by the runtime to calculate the address. The
3976/// only part of this the compiler needs to know about is the first xword, which
3977/// contains a function pointer that must be called with the address of the
3978/// entire descriptor in "x0".
3979///
3980/// Since this descriptor may be in a different unit, in general even the
3981/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3982/// is:
3983/// adrp x0, _var@TLVPPAGE
3984/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3985/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3986/// ; the function pointer
3987/// blr x1 ; Uses descriptor address in x0
3988/// ; Address of _var is now in x0.
3989///
3990/// If the address of _var's descriptor *is* known to the linker, then it can
3991/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3992/// a slight efficiency gain.
3993SDValue
3994AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3995 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00003996 assert(Subtarget->isTargetDarwin() &&
3997 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00003998
3999 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004000 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004001 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4002
4003 SDValue TLVPAddr =
4004 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4005 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4006
4007 // The first entry in the descriptor is a function pointer that we must call
4008 // to obtain the address of the variable.
4009 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004010 SDValue FuncTLVGet = DAG.getLoad(
4011 MVT::i64, DL, Chain, DescAddr,
4012 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4013 /* Alignment = */ 8,
4014 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4015 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004016 Chain = FuncTLVGet.getValue(1);
4017
Matthias Braun941a7052016-07-28 18:40:00 +00004018 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4019 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004020
4021 // TLS calls preserve all registers except those that absolutely must be
4022 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4023 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00004024 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00004025 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00004026
4027 // Finally, we can make the call. This is just a degenerate version of a
4028 // normal AArch64 call node: x0 takes the address of the descriptor, and
4029 // returns the address of the variable in this thread.
4030 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4031 Chain =
4032 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4033 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4034 DAG.getRegisterMask(Mask), Chain.getValue(1));
4035 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4036}
4037
4038/// When accessing thread-local variables under either the general-dynamic or
4039/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4040/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004041/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004042///
Kristof Beylsaea84612015-03-04 09:12:08 +00004043/// The sequence is:
4044/// adrp x0, :tlsdesc:var
4045/// ldr x1, [x0, #:tlsdesc_lo12:var]
4046/// add x0, x0, #:tlsdesc_lo12:var
4047/// .tlsdesccall var
4048/// blr x1
4049/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004050///
Kristof Beylsaea84612015-03-04 09:12:08 +00004051/// The above sequence must be produced unscheduled, to enable the linker to
4052/// optimize/relax this sequence.
4053/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4054/// above sequence, and expanded really late in the compilation flow, to ensure
4055/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004056SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4057 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004058 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004059 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004060
Kristof Beylsaea84612015-03-04 09:12:08 +00004061 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004062 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004063
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004064 Chain =
4065 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004066 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004067
4068 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4069}
4070
4071SDValue
4072AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4073 SelectionDAG &DAG) const {
4074 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004075 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4076 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004077 // Different choices can be made for the maximum size of the TLS area for a
4078 // module. For the small address model, the default TLS size is 16MiB and the
4079 // maximum TLS size is 4GiB.
4080 // FIXME: add -mtls-size command line option and make it control the 16MiB
4081 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004082 // FIXME: add tiny codemodel support. We currently generate the same code as
4083 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004084 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4085
4086 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004087
Kristof Beylsaea84612015-03-04 09:12:08 +00004088 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4089 if (Model == TLSModel::LocalDynamic)
4090 Model = TLSModel::GeneralDynamic;
4091 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004092
4093 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004094 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004095 SDLoc DL(Op);
4096 const GlobalValue *GV = GA->getGlobal();
4097
4098 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4099
4100 if (Model == TLSModel::LocalExec) {
4101 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004102 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004103 SDValue LoVar = DAG.getTargetGlobalAddress(
4104 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004105 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004106
Kristof Beylsaea84612015-03-04 09:12:08 +00004107 SDValue TPWithOff_lo =
4108 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004109 HiVar,
4110 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004111 0);
4112 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004113 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4114 LoVar,
4115 DAG.getTargetConstant(0, DL, MVT::i32)),
4116 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004117 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004118 } else if (Model == TLSModel::InitialExec) {
4119 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4120 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4121 } else if (Model == TLSModel::LocalDynamic) {
4122 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4123 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4124 // the beginning of the module's TLS region, followed by a DTPREL offset
4125 // calculation.
4126
4127 // These accesses will need deduplicating if there's more than one.
4128 AArch64FunctionInfo *MFI =
4129 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4130 MFI->incNumLocalDynamicTLSAccesses();
4131
Tim Northover3b0846e2014-05-24 12:50:23 +00004132 // The call needs a relocation too for linker relaxation. It doesn't make
4133 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4134 // the address.
4135 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4136 AArch64II::MO_TLS);
4137
4138 // Now we can calculate the offset from TPIDR_EL0 to this module's
4139 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004140 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004141
4142 // Now use :dtprel_whatever: operations to calculate this variable's offset
4143 // in its thread-storage area.
4144 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004145 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004146 SDValue LoVar = DAG.getTargetGlobalAddress(
4147 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004148 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4149
Kristof Beylsaea84612015-03-04 09:12:08 +00004150 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004151 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004152 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004153 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4154 DAG.getTargetConstant(0, DL, MVT::i32)),
4155 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004156 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004157 // The call needs a relocation too for linker relaxation. It doesn't make
4158 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4159 // the address.
4160 SDValue SymAddr =
4161 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4162
4163 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004164 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004165 } else
4166 llvm_unreachable("Unsupported ELF TLS access model");
4167
4168 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4169}
4170
Martin Storsjocc240962018-03-10 19:05:21 +00004171SDValue
4172AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4173 SelectionDAG &DAG) const {
4174 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4175
4176 SDValue Chain = DAG.getEntryNode();
4177 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4178 SDLoc DL(Op);
4179
4180 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4181
4182 // Load the ThreadLocalStoragePointer from the TEB
4183 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4184 SDValue TLSArray =
4185 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4186 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4187 Chain = TLSArray.getValue(1);
4188
4189 // Load the TLS index from the C runtime;
4190 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4191 // This also does the same as LOADgot, but using a generic i32 load,
4192 // while LOADgot only loads i64.
4193 SDValue TLSIndexHi =
4194 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4195 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4196 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4197 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4198 SDValue TLSIndex =
4199 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4200 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4201 Chain = TLSIndex.getValue(1);
4202
4203 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4204 // offset into the TLSArray.
4205 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4206 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4207 DAG.getConstant(3, DL, PtrVT));
4208 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4209 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4210 MachinePointerInfo());
4211 Chain = TLS.getValue(1);
4212
4213 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4214 const GlobalValue *GV = GA->getGlobal();
4215 SDValue TGAHi = DAG.getTargetGlobalAddress(
4216 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4217 SDValue TGALo = DAG.getTargetGlobalAddress(
4218 GV, DL, PtrVT, 0,
4219 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4220
4221 // Add the offset from the start of the .tls section (section base).
4222 SDValue Addr =
4223 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4224 DAG.getTargetConstant(0, DL, MVT::i32)),
4225 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004226 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004227 return Addr;
4228}
4229
Tim Northover3b0846e2014-05-24 12:50:23 +00004230SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4231 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004232 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004233 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004234 return LowerToTLSEmulatedModel(GA, DAG);
4235
Tim Northover3b0846e2014-05-24 12:50:23 +00004236 if (Subtarget->isTargetDarwin())
4237 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004238 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004239 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004240 if (Subtarget->isTargetWindows())
4241 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004242
4243 llvm_unreachable("Unexpected platform trying to use TLS");
4244}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004245
Tim Northover3b0846e2014-05-24 12:50:23 +00004246SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4247 SDValue Chain = Op.getOperand(0);
4248 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4249 SDValue LHS = Op.getOperand(2);
4250 SDValue RHS = Op.getOperand(3);
4251 SDValue Dest = Op.getOperand(4);
4252 SDLoc dl(Op);
4253
4254 // Handle f128 first, since lowering it will result in comparing the return
4255 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4256 // is expecting to deal with.
4257 if (LHS.getValueType() == MVT::f128) {
4258 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4259
4260 // If softenSetCCOperands returned a scalar, we need to compare the result
4261 // against zero to select between true and false values.
4262 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004263 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004264 CC = ISD::SETNE;
4265 }
4266 }
4267
4268 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4269 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004270 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4271 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004272 // Only lower legal XALUO ops.
4273 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4274 return SDValue();
4275
4276 // The actual operation with overflow check.
4277 AArch64CC::CondCode OFCC;
4278 SDValue Value, Overflow;
4279 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4280
4281 if (CC == ISD::SETNE)
4282 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004283 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004284
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004285 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4286 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004287 }
4288
4289 if (LHS.getValueType().isInteger()) {
4290 assert((LHS.getValueType() == RHS.getValueType()) &&
4291 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4292
4293 // If the RHS of the comparison is zero, we can potentially fold this
4294 // to a specialized branch.
4295 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4296 if (RHSC && RHSC->getZExtValue() == 0) {
4297 if (CC == ISD::SETEQ) {
4298 // See if we can use a TBZ to fold in an AND as well.
4299 // TBZ has a smaller branch displacement than CBZ. If the offset is
4300 // out of bounds, a late MI-layer pass rewrites branches.
4301 // 403.gcc is an example that hits this case.
4302 if (LHS.getOpcode() == ISD::AND &&
4303 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4304 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4305 SDValue Test = LHS.getOperand(0);
4306 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004307 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004308 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4309 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004310 }
4311
4312 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4313 } else if (CC == ISD::SETNE) {
4314 // See if we can use a TBZ to fold in an AND as well.
4315 // TBZ has a smaller branch displacement than CBZ. If the offset is
4316 // out of bounds, a late MI-layer pass rewrites branches.
4317 // 403.gcc is an example that hits this case.
4318 if (LHS.getOpcode() == ISD::AND &&
4319 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4320 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4321 SDValue Test = LHS.getOperand(0);
4322 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004323 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004324 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4325 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004326 }
4327
4328 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004329 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4330 // Don't combine AND since emitComparison converts the AND to an ANDS
4331 // (a.k.a. TST) and the test in the test bit and branch instruction
4332 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004333 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004334 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004335 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004336 }
4337 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004338 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4339 LHS.getOpcode() != ISD::AND) {
4340 // Don't combine AND since emitComparison converts the AND to an ANDS
4341 // (a.k.a. TST) and the test in the test bit and branch instruction
4342 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004343 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004344 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004345 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004346 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004347
4348 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004349 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004350 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4351 Cmp);
4352 }
4353
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004354 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4355 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004356
4357 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4358 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004359 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004360 AArch64CC::CondCode CC1, CC2;
4361 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004362 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004363 SDValue BR1 =
4364 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4365 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004366 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004367 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4368 Cmp);
4369 }
4370
4371 return BR1;
4372}
4373
4374SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4375 SelectionDAG &DAG) const {
4376 EVT VT = Op.getValueType();
4377 SDLoc DL(Op);
4378
4379 SDValue In1 = Op.getOperand(0);
4380 SDValue In2 = Op.getOperand(1);
4381 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004382
4383 if (SrcVT.bitsLT(VT))
4384 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4385 else if (SrcVT.bitsGT(VT))
4386 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004387
4388 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004389 uint64_t EltMask;
4390 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004391
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004392 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004393 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004394 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004395 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004396 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004397 DAG.getUNDEF(VecVT), In2);
4398 } else {
4399 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4400 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4401 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004402 };
4403
4404 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4405 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4406 EltMask = 0x80000000ULL;
4407 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004408 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004409 VecVT = MVT::v2i64;
4410
Eric Christopher572e03a2015-06-19 01:53:21 +00004411 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004412 // immediate moves cannot materialize that in a single instruction for
4413 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004414 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004415
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004416 setVecVal(AArch64::dsub);
4417 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4418 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4419 EltMask = 0x8000ULL;
4420 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004421 } else {
4422 llvm_unreachable("Invalid type for copysign!");
4423 }
4424
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004425 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004426
4427 // If we couldn't materialize the mask above, then the mask vector will be
4428 // the zero vector, and we need to negate it here.
4429 if (VT == MVT::f64 || VT == MVT::v2f64) {
4430 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4431 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4432 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4433 }
4434
4435 SDValue Sel =
4436 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4437
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004438 if (VT == MVT::f16)
4439 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004440 if (VT == MVT::f32)
4441 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4442 else if (VT == MVT::f64)
4443 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4444 else
4445 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4446}
4447
4448SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004449 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004450 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004451 return SDValue();
4452
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004453 if (!Subtarget->hasNEON())
4454 return SDValue();
4455
Tim Northover3b0846e2014-05-24 12:50:23 +00004456 // While there is no integer popcount instruction, it can
4457 // be more efficiently lowered to the following sequence that uses
4458 // AdvSIMD registers/instructions as long as the copies to/from
4459 // the AdvSIMD registers are cheap.
4460 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4461 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4462 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4463 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4464 SDValue Val = Op.getOperand(0);
4465 SDLoc DL(Op);
4466 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004467
Hao Liue0335d72015-01-30 02:13:53 +00004468 if (VT == MVT::i32)
4469 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4470 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004471
Hao Liue0335d72015-01-30 02:13:53 +00004472 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004473 SDValue UaddLV = DAG.getNode(
4474 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004475 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004476
4477 if (VT == MVT::i64)
4478 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4479 return UaddLV;
4480}
4481
4482SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4483
4484 if (Op.getValueType().isVector())
4485 return LowerVSETCC(Op, DAG);
4486
4487 SDValue LHS = Op.getOperand(0);
4488 SDValue RHS = Op.getOperand(1);
4489 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4490 SDLoc dl(Op);
4491
4492 // We chose ZeroOrOneBooleanContents, so use zero and one.
4493 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004494 SDValue TVal = DAG.getConstant(1, dl, VT);
4495 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004496
4497 // Handle f128 first, since one possible outcome is a normal integer
4498 // comparison which gets picked up by the next if statement.
4499 if (LHS.getValueType() == MVT::f128) {
4500 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4501
4502 // If softenSetCCOperands returned a scalar, use it.
4503 if (!RHS.getNode()) {
4504 assert(LHS.getValueType() == Op.getValueType() &&
4505 "Unexpected setcc expansion!");
4506 return LHS;
4507 }
4508 }
4509
4510 if (LHS.getValueType().isInteger()) {
4511 SDValue CCVal;
4512 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004513 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004514
4515 // Note that we inverted the condition above, so we reverse the order of
4516 // the true and false operands here. This will allow the setcc to be
4517 // matched to a single CSINC instruction.
4518 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4519 }
4520
4521 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004522 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4523 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004524
4525 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4526 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004527 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004528
4529 AArch64CC::CondCode CC1, CC2;
4530 changeFPCCToAArch64CC(CC, CC1, CC2);
4531 if (CC2 == AArch64CC::AL) {
4532 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004533 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004534
4535 // Note that we inverted the condition above, so we reverse the order of
4536 // the true and false operands here. This will allow the setcc to be
4537 // matched to a single CSINC instruction.
4538 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4539 } else {
4540 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4541 // totally clean. Some of them require two CSELs to implement. As is in
4542 // this case, we emit the first CSEL and then emit a second using the output
4543 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4544
4545 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004546 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004547 SDValue CS1 =
4548 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4549
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004550 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004551 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4552 }
4553}
4554
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004555SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4556 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004557 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004558 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004559 // Handle f128 first, because it will result in a comparison of some RTLIB
4560 // call result against zero.
4561 if (LHS.getValueType() == MVT::f128) {
4562 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4563
4564 // If softenSetCCOperands returned a scalar, we need to compare the result
4565 // against zero to select between true and false values.
4566 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004567 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004568 CC = ISD::SETNE;
4569 }
4570 }
4571
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004572 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004573 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004574 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4575 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4576 }
4577
4578 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004579 if (LHS.getValueType().isInteger()) {
4580 assert((LHS.getValueType() == RHS.getValueType()) &&
4581 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4582
4583 unsigned Opcode = AArch64ISD::CSEL;
4584
4585 // If both the TVal and the FVal are constants, see if we can swap them in
4586 // order to for a CSINV or CSINC out of them.
4587 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4588 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4589
4590 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4591 std::swap(TVal, FVal);
4592 std::swap(CTVal, CFVal);
4593 CC = ISD::getSetCCInverse(CC, true);
4594 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4595 std::swap(TVal, FVal);
4596 std::swap(CTVal, CFVal);
4597 CC = ISD::getSetCCInverse(CC, true);
4598 } else if (TVal.getOpcode() == ISD::XOR) {
4599 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4600 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004601 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004602 std::swap(TVal, FVal);
4603 std::swap(CTVal, CFVal);
4604 CC = ISD::getSetCCInverse(CC, true);
4605 }
4606 } else if (TVal.getOpcode() == ISD::SUB) {
4607 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4608 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004609 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004610 std::swap(TVal, FVal);
4611 std::swap(CTVal, CFVal);
4612 CC = ISD::getSetCCInverse(CC, true);
4613 }
4614 } else if (CTVal && CFVal) {
4615 const int64_t TrueVal = CTVal->getSExtValue();
4616 const int64_t FalseVal = CFVal->getSExtValue();
4617 bool Swap = false;
4618
4619 // If both TVal and FVal are constants, see if FVal is the
4620 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4621 // instead of a CSEL in that case.
4622 if (TrueVal == ~FalseVal) {
4623 Opcode = AArch64ISD::CSINV;
4624 } else if (TrueVal == -FalseVal) {
4625 Opcode = AArch64ISD::CSNEG;
4626 } else if (TVal.getValueType() == MVT::i32) {
4627 // If our operands are only 32-bit wide, make sure we use 32-bit
4628 // arithmetic for the check whether we can use CSINC. This ensures that
4629 // the addition in the check will wrap around properly in case there is
4630 // an overflow (which would not be the case if we do the check with
4631 // 64-bit arithmetic).
4632 const uint32_t TrueVal32 = CTVal->getZExtValue();
4633 const uint32_t FalseVal32 = CFVal->getZExtValue();
4634
4635 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4636 Opcode = AArch64ISD::CSINC;
4637
4638 if (TrueVal32 > FalseVal32) {
4639 Swap = true;
4640 }
4641 }
4642 // 64-bit check whether we can use CSINC.
4643 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4644 Opcode = AArch64ISD::CSINC;
4645
4646 if (TrueVal > FalseVal) {
4647 Swap = true;
4648 }
4649 }
4650
4651 // Swap TVal and FVal if necessary.
4652 if (Swap) {
4653 std::swap(TVal, FVal);
4654 std::swap(CTVal, CFVal);
4655 CC = ISD::getSetCCInverse(CC, true);
4656 }
4657
4658 if (Opcode != AArch64ISD::CSEL) {
4659 // Drop FVal since we can get its value by simply inverting/negating
4660 // TVal.
4661 FVal = TVal;
4662 }
4663 }
4664
Chad Rosier58f505b2016-08-26 18:05:50 +00004665 // Avoid materializing a constant when possible by reusing a known value in
4666 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004667 // is one, zero or negative one in the case of a CSEL. We can always
4668 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4669 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004670 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4671 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4672 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4673 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4674 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4675 // "a != C ? x : a" to avoid materializing C.
4676 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4677 TVal = LHS;
4678 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4679 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004680 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4681 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4682 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4683 // avoid materializing C.
4684 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4685 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4686 Opcode = AArch64ISD::CSINV;
4687 TVal = LHS;
4688 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4689 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004690 }
4691
Tim Northover3b0846e2014-05-24 12:50:23 +00004692 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004693 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004694 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004695 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4696 }
4697
4698 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004699 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4700 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004701 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004702 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004703 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004704
4705 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4706 // clean. Some of them require two CSELs to implement.
4707 AArch64CC::CondCode CC1, CC2;
4708 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004709
4710 if (DAG.getTarget().Options.UnsafeFPMath) {
4711 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4712 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4713 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4714 if (RHSVal && RHSVal->isZero()) {
4715 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4716 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4717
4718 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004719 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004720 TVal = LHS;
4721 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004722 CFVal && CFVal->isZero() &&
4723 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004724 FVal = LHS;
4725 }
4726 }
4727
4728 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004729 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004730 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4731
4732 // If we need a second CSEL, emit it, using the output of the first as the
4733 // RHS. We're effectively OR'ing the two CC's together.
4734 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004735 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004736 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4737 }
4738
4739 // Otherwise, return the output of the first CSEL.
4740 return CS1;
4741}
4742
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004743SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4744 SelectionDAG &DAG) const {
4745 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4746 SDValue LHS = Op.getOperand(0);
4747 SDValue RHS = Op.getOperand(1);
4748 SDValue TVal = Op.getOperand(2);
4749 SDValue FVal = Op.getOperand(3);
4750 SDLoc DL(Op);
4751 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4752}
4753
4754SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4755 SelectionDAG &DAG) const {
4756 SDValue CCVal = Op->getOperand(0);
4757 SDValue TVal = Op->getOperand(1);
4758 SDValue FVal = Op->getOperand(2);
4759 SDLoc DL(Op);
4760
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004761 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4762 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004763 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004764 // Only lower legal XALUO ops.
4765 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4766 return SDValue();
4767
4768 AArch64CC::CondCode OFCC;
4769 SDValue Value, Overflow;
4770 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004771 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004772
4773 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4774 CCVal, Overflow);
4775 }
4776
4777 // Lower it the same way as we would lower a SELECT_CC node.
4778 ISD::CondCode CC;
4779 SDValue LHS, RHS;
4780 if (CCVal.getOpcode() == ISD::SETCC) {
4781 LHS = CCVal.getOperand(0);
4782 RHS = CCVal.getOperand(1);
4783 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4784 } else {
4785 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004786 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004787 CC = ISD::SETNE;
4788 }
4789 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4790}
4791
Tim Northover3b0846e2014-05-24 12:50:23 +00004792SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4793 SelectionDAG &DAG) const {
4794 // Jump table entries as PC relative offsets. No additional tweaking
4795 // is necessary here. Just get the address of the jump table.
4796 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004797
4798 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4799 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004800 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004801 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4802 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004803 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004804 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004805}
4806
4807SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4808 SelectionDAG &DAG) const {
4809 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004810
4811 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4812 // Use the GOT for the large code model on iOS.
4813 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004814 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004815 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004816 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004817 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4818 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004819 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004820 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004821 }
4822}
4823
4824SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4825 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004826 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004827 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4828 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004829 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004830 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4831 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004832 }
David Green9dd1d452018-08-22 11:31:39 +00004833 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004834}
4835
4836SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4837 SelectionDAG &DAG) const {
4838 AArch64FunctionInfo *FuncInfo =
4839 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4840
4841 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004842 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4843 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004844 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4845 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004846 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004847}
4848
Martin Storsjo68266fa2017-07-13 17:03:12 +00004849SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4850 SelectionDAG &DAG) const {
4851 AArch64FunctionInfo *FuncInfo =
4852 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4853
4854 SDLoc DL(Op);
4855 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4856 ? FuncInfo->getVarArgsGPRIndex()
4857 : FuncInfo->getVarArgsStackIndex(),
4858 getPointerTy(DAG.getDataLayout()));
4859 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4860 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4861 MachinePointerInfo(SV));
4862}
4863
Tim Northover3b0846e2014-05-24 12:50:23 +00004864SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4865 SelectionDAG &DAG) const {
4866 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4867 // Standard, section B.3.
4868 MachineFunction &MF = DAG.getMachineFunction();
4869 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004870 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004871 SDLoc DL(Op);
4872
4873 SDValue Chain = Op.getOperand(0);
4874 SDValue VAList = Op.getOperand(1);
4875 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4876 SmallVector<SDValue, 4> MemOps;
4877
4878 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004879 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004880 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004881 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004882
4883 // void *__gr_top at offset 8
4884 int GPRSize = FuncInfo->getVarArgsGPRSize();
4885 if (GPRSize > 0) {
4886 SDValue GRTop, GRTopAddr;
4887
Mehdi Amini44ede332015-07-09 02:09:04 +00004888 GRTopAddr =
4889 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004890
Mehdi Amini44ede332015-07-09 02:09:04 +00004891 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4892 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4893 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004894
4895 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004896 MachinePointerInfo(SV, 8),
4897 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004898 }
4899
4900 // void *__vr_top at offset 16
4901 int FPRSize = FuncInfo->getVarArgsFPRSize();
4902 if (FPRSize > 0) {
4903 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004904 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4905 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004906
Mehdi Amini44ede332015-07-09 02:09:04 +00004907 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4908 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4909 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004910
4911 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004912 MachinePointerInfo(SV, 16),
4913 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004914 }
4915
4916 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004917 SDValue GROffsAddr =
4918 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004919 MemOps.push_back(DAG.getStore(
4920 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4921 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004922
4923 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004924 SDValue VROffsAddr =
4925 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004926 MemOps.push_back(DAG.getStore(
4927 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4928 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004929
4930 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4931}
4932
4933SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4934 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00004935 MachineFunction &MF = DAG.getMachineFunction();
4936
Matthias Braunf1caa282017-12-15 22:22:58 +00004937 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00004938 return LowerWin64_VASTART(Op, DAG);
4939 else if (Subtarget->isTargetDarwin())
4940 return LowerDarwin_VASTART(Op, DAG);
4941 else
4942 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004943}
4944
4945SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4946 SelectionDAG &DAG) const {
4947 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4948 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004949 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00004950 unsigned VaListSize =
4951 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00004952 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4953 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4954
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004955 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4956 Op.getOperand(2),
4957 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004958 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004959 MachinePointerInfo(SrcSV));
4960}
4961
4962SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4963 assert(Subtarget->isTargetDarwin() &&
4964 "automatic va_arg instruction only works on Darwin");
4965
4966 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4967 EVT VT = Op.getValueType();
4968 SDLoc DL(Op);
4969 SDValue Chain = Op.getOperand(0);
4970 SDValue Addr = Op.getOperand(1);
4971 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004972 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004973
Justin Lebar9c375812016-07-15 18:27:10 +00004974 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004975 Chain = VAList.getValue(1);
4976
4977 if (Align > 8) {
4978 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004979 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4980 DAG.getConstant(Align - 1, DL, PtrVT));
4981 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4982 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004983 }
4984
4985 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004986 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004987
4988 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4989 // up to 64 bits. At the very least, we have to increase the striding of the
4990 // vaargs list to match this, and for FP values we need to introduce
4991 // FP_ROUND nodes as well.
4992 if (VT.isInteger() && !VT.isVector())
4993 ArgSize = 8;
4994 bool NeedFPTrunc = false;
4995 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4996 ArgSize = 8;
4997 NeedFPTrunc = true;
4998 }
4999
5000 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005001 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5002 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005003 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005004 SDValue APStore =
5005 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005006
5007 // Load the actual argument out of the pointer VAList
5008 if (NeedFPTrunc) {
5009 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005010 SDValue WideFP =
5011 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005012 // Round the value down to an f32.
5013 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005014 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005015 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5016 // Merge the rounded value with the chain output of the load.
5017 return DAG.getMergeValues(Ops, DL);
5018 }
5019
Justin Lebar9c375812016-07-15 18:27:10 +00005020 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005021}
5022
5023SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5024 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005025 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5026 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005027
5028 EVT VT = Op.getValueType();
5029 SDLoc DL(Op);
5030 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5031 SDValue FrameAddr =
5032 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5033 while (Depth--)
5034 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005035 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005036 return FrameAddr;
5037}
5038
5039// FIXME? Maybe this could be a TableGen attribute on some registers and
5040// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005041unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5042 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005043 unsigned Reg = StringSwitch<unsigned>(RegName)
5044 .Case("sp", AArch64::SP)
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005045 .Case("x1", AArch64::X1)
5046 .Case("w1", AArch64::W1)
5047 .Case("x2", AArch64::X2)
5048 .Case("w2", AArch64::W2)
5049 .Case("x3", AArch64::X3)
5050 .Case("w3", AArch64::W3)
5051 .Case("x4", AArch64::X4)
5052 .Case("w4", AArch64::W4)
5053 .Case("x5", AArch64::X5)
5054 .Case("w5", AArch64::W5)
5055 .Case("x6", AArch64::X6)
5056 .Case("w6", AArch64::W6)
5057 .Case("x7", AArch64::X7)
5058 .Case("w7", AArch64::W7)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005059 .Case("x18", AArch64::X18)
5060 .Case("w18", AArch64::W18)
Petr Hosek72509082018-06-12 20:00:50 +00005061 .Case("x20", AArch64::X20)
5062 .Case("w20", AArch64::W20)
Tim Northover3b0846e2014-05-24 12:50:23 +00005063 .Default(0);
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005064 if (((Reg == AArch64::X1 || Reg == AArch64::W1) &&
5065 !Subtarget->isXRegisterReserved(1)) ||
5066 ((Reg == AArch64::X2 || Reg == AArch64::W2) &&
5067 !Subtarget->isXRegisterReserved(2)) ||
5068 ((Reg == AArch64::X3 || Reg == AArch64::W3) &&
5069 !Subtarget->isXRegisterReserved(3)) ||
5070 ((Reg == AArch64::X4 || Reg == AArch64::W4) &&
5071 !Subtarget->isXRegisterReserved(4)) ||
5072 ((Reg == AArch64::X5 || Reg == AArch64::W5) &&
5073 !Subtarget->isXRegisterReserved(5)) ||
5074 ((Reg == AArch64::X6 || Reg == AArch64::W6) &&
5075 !Subtarget->isXRegisterReserved(6)) ||
5076 ((Reg == AArch64::X7 || Reg == AArch64::W7) &&
5077 !Subtarget->isXRegisterReserved(7)) ||
5078 ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
5079 !Subtarget->isXRegisterReserved(18)) ||
Petr Hosek72509082018-06-12 20:00:50 +00005080 ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005081 !Subtarget->isXRegisterReserved(20)))
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005082 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00005083 if (Reg)
5084 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005085 report_fatal_error(Twine("Invalid register name \""
5086 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005087}
5088
5089SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5090 SelectionDAG &DAG) const {
5091 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005092 MachineFrameInfo &MFI = MF.getFrameInfo();
5093 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005094
5095 EVT VT = Op.getValueType();
5096 SDLoc DL(Op);
5097 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5098 if (Depth) {
5099 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005100 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005101 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5102 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005103 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005104 }
5105
5106 // Return LR, which contains the return address. Mark it an implicit live-in.
5107 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5108 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5109}
5110
5111/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5112/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5113SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5114 SelectionDAG &DAG) const {
5115 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5116 EVT VT = Op.getValueType();
5117 unsigned VTBits = VT.getSizeInBits();
5118 SDLoc dl(Op);
5119 SDValue ShOpLo = Op.getOperand(0);
5120 SDValue ShOpHi = Op.getOperand(1);
5121 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005122 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5123
5124 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5125
5126 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005127 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005128 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5129
5130 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5131 // is "undef". We wanted 0, so CSEL it directly.
5132 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5133 ISD::SETEQ, dl, DAG);
5134 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5135 HiBitsForLo =
5136 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5137 HiBitsForLo, CCVal, Cmp);
5138
Tim Northover3b0846e2014-05-24 12:50:23 +00005139 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005140 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005141
Tim Northoverf3be9d52015-12-02 00:33:54 +00005142 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5143 SDValue LoForNormalShift =
5144 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005145
Tim Northoverf3be9d52015-12-02 00:33:54 +00005146 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5147 dl, DAG);
5148 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5149 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5150 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5151 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005152
5153 // AArch64 shifts larger than the register width are wrapped rather than
5154 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005155 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5156 SDValue HiForBigShift =
5157 Opc == ISD::SRA
5158 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5159 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5160 : DAG.getConstant(0, dl, VT);
5161 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5162 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005163
5164 SDValue Ops[2] = { Lo, Hi };
5165 return DAG.getMergeValues(Ops, dl);
5166}
5167
5168/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5169/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5170SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005171 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005172 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5173 EVT VT = Op.getValueType();
5174 unsigned VTBits = VT.getSizeInBits();
5175 SDLoc dl(Op);
5176 SDValue ShOpLo = Op.getOperand(0);
5177 SDValue ShOpHi = Op.getOperand(1);
5178 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005179
5180 assert(Op.getOpcode() == ISD::SHL_PARTS);
5181 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005182 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005183 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5184
5185 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5186 // is "undef". We wanted 0, so CSEL it directly.
5187 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5188 ISD::SETEQ, dl, DAG);
5189 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5190 LoBitsForHi =
5191 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5192 LoBitsForHi, CCVal, Cmp);
5193
Tim Northover3b0846e2014-05-24 12:50:23 +00005194 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005195 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005196 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5197 SDValue HiForNormalShift =
5198 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005199
Tim Northoverf3be9d52015-12-02 00:33:54 +00005200 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005201
Tim Northoverf3be9d52015-12-02 00:33:54 +00005202 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5203 dl, DAG);
5204 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5205 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5206 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005207
5208 // AArch64 shifts of larger than register sizes are wrapped rather than
5209 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005210 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5211 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5212 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5213 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005214
5215 SDValue Ops[2] = { Lo, Hi };
5216 return DAG.getMergeValues(Ops, dl);
5217}
5218
5219bool AArch64TargetLowering::isOffsetFoldingLegal(
5220 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005221 // Offsets are folded in the DAG combine rather than here so that we can
5222 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005223 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005224}
5225
5226bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
5227 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
5228 // FIXME: We should be able to handle f128 as well with a clever lowering.
Sjoerd Meijer5ea465d2018-02-08 08:39:05 +00005229 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
5230 (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
JF Bastienda339002018-09-05 23:38:11 +00005231 LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString() << " imm value: 0\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005232 return true;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005233 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005234
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005235 bool IsLegal = false;
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00005236 SmallString<128> ImmStrVal;
5237 Imm.toString(ImmStrVal);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005238
JF Bastienda339002018-09-05 23:38:11 +00005239 if (VT == MVT::f64)
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005240 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
JF Bastienda339002018-09-05 23:38:11 +00005241 else if (VT == MVT::f32)
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005242 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
JF Bastienda339002018-09-05 23:38:11 +00005243 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005244 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005245
5246 if (IsLegal) {
JF Bastienda339002018-09-05 23:38:11 +00005247 LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString()
5248 << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005249 return true;
5250 }
5251
JF Bastienda339002018-09-05 23:38:11 +00005252 LLVM_DEBUG(dbgs() << "Illegal " << VT.getEVTString()
5253 << " imm value: " << ImmStrVal << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005254 return false;
5255}
5256
5257//===----------------------------------------------------------------------===//
5258// AArch64 Optimization Hooks
5259//===----------------------------------------------------------------------===//
5260
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005261static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5262 SDValue Operand, SelectionDAG &DAG,
5263 int &ExtraSteps) {
5264 EVT VT = Operand.getValueType();
5265 if (ST->hasNEON() &&
5266 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5267 VT == MVT::f32 || VT == MVT::v1f32 ||
5268 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5269 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5270 // For the reciprocal estimates, convergence is quadratic, so the number
5271 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5272 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5273 // the result for float (23 mantissa bits) is 2 and for double (52
5274 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005275 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005276
5277 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5278 }
5279
5280 return SDValue();
5281}
5282
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005283SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5284 SelectionDAG &DAG, int Enabled,
5285 int &ExtraSteps,
5286 bool &UseOneConst,
5287 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005288 if (Enabled == ReciprocalEstimate::Enabled ||
5289 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5290 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5291 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005292 SDLoc DL(Operand);
5293 EVT VT = Operand.getValueType();
5294
5295 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005296 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005297
5298 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5299 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5300 for (int i = ExtraSteps; i > 0; --i) {
5301 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005302 Flags);
5303 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5304 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005305 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005306 if (!Reciprocal) {
5307 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5308 VT);
5309 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5310 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5311
Amara Emersond28f0cd42017-05-01 15:17:51 +00005312 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005313 // Correct the result if the operand is 0.0.
5314 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5315 VT, Eq, Operand, Estimate);
5316 }
5317
5318 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005319 return Estimate;
5320 }
5321
5322 return SDValue();
5323}
5324
5325SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5326 SelectionDAG &DAG, int Enabled,
5327 int &ExtraSteps) const {
5328 if (Enabled == ReciprocalEstimate::Enabled)
5329 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005330 DAG, ExtraSteps)) {
5331 SDLoc DL(Operand);
5332 EVT VT = Operand.getValueType();
5333
5334 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005335 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005336
5337 // Newton reciprocal iteration: E * (2 - X * E)
5338 // AArch64 reciprocal iteration instruction: (2 - M * N)
5339 for (int i = ExtraSteps; i > 0; --i) {
5340 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005341 Estimate, Flags);
5342 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005343 }
5344
5345 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005346 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005347 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005348
5349 return SDValue();
5350}
5351
Tim Northover3b0846e2014-05-24 12:50:23 +00005352//===----------------------------------------------------------------------===//
5353// AArch64 Inline Assembly Support
5354//===----------------------------------------------------------------------===//
5355
5356// Table of Constraints
5357// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005358// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005359//
5360// r - A general register
5361// w - An FP/SIMD register of some size in the range v0-v31
5362// x - An FP/SIMD register of some size in the range v0-v15
5363// I - Constant that can be used with an ADD instruction
5364// J - Constant that can be used with a SUB instruction
5365// K - Constant that can be used with a 32-bit logical instruction
5366// L - Constant that can be used with a 64-bit logical instruction
5367// M - Constant that can be used as a 32-bit MOV immediate
5368// N - Constant that can be used as a 64-bit MOV immediate
5369// Q - A memory reference with base register and no offset
5370// S - A symbolic address
5371// Y - Floating point constant zero
5372// Z - Integer constant zero
5373//
5374// Note that general register operands will be output using their 64-bit x
5375// register name, whatever the size of the variable, unless the asm operand
5376// is prefixed by the %w modifier. Floating-point and SIMD register operands
5377// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5378// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005379const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5380 // At this point, we have to lower this constraint to something else, so we
5381 // lower it to an "r" or "w". However, by doing this we will force the result
5382 // to be in register, while the X constraint is much more permissive.
5383 //
5384 // Although we are correct (we are free to emit anything, without
5385 // constraints), we might break use cases that would expect us to be more
5386 // efficient and emit something else.
5387 if (!Subtarget->hasFPARMv8())
5388 return "r";
5389
5390 if (ConstraintVT.isFloatingPoint())
5391 return "w";
5392
5393 if (ConstraintVT.isVector() &&
5394 (ConstraintVT.getSizeInBits() == 64 ||
5395 ConstraintVT.getSizeInBits() == 128))
5396 return "w";
5397
5398 return "r";
5399}
Tim Northover3b0846e2014-05-24 12:50:23 +00005400
5401/// getConstraintType - Given a constraint letter, return the type of
5402/// constraint it is for this target.
5403AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005404AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005405 if (Constraint.size() == 1) {
5406 switch (Constraint[0]) {
5407 default:
5408 break;
5409 case 'z':
5410 return C_Other;
5411 case 'x':
5412 case 'w':
5413 return C_RegisterClass;
5414 // An address with a single base register. Due to the way we
5415 // currently handle addresses it is the same as 'r'.
5416 case 'Q':
5417 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005418 case 'S': // A symbolic address
5419 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005420 }
5421 }
5422 return TargetLowering::getConstraintType(Constraint);
5423}
5424
5425/// Examine constraint type and operand type and determine a weight value.
5426/// This object must already have been set up with the operand type
5427/// and the current alternative constraint selected.
5428TargetLowering::ConstraintWeight
5429AArch64TargetLowering::getSingleConstraintMatchWeight(
5430 AsmOperandInfo &info, const char *constraint) const {
5431 ConstraintWeight weight = CW_Invalid;
5432 Value *CallOperandVal = info.CallOperandVal;
5433 // If we don't have a value, we can't do a match,
5434 // but allow it at the lowest weight.
5435 if (!CallOperandVal)
5436 return CW_Default;
5437 Type *type = CallOperandVal->getType();
5438 // Look at the constraint type.
5439 switch (*constraint) {
5440 default:
5441 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5442 break;
5443 case 'x':
5444 case 'w':
5445 if (type->isFloatingPointTy() || type->isVectorTy())
5446 weight = CW_Register;
5447 break;
5448 case 'z':
5449 weight = CW_Constant;
5450 break;
5451 }
5452 return weight;
5453}
5454
5455std::pair<unsigned, const TargetRegisterClass *>
5456AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005457 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005458 if (Constraint.size() == 1) {
5459 switch (Constraint[0]) {
5460 case 'r':
5461 if (VT.getSizeInBits() == 64)
5462 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5463 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5464 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005465 if (!Subtarget->hasFPARMv8())
5466 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005467 if (VT.getSizeInBits() == 16)
5468 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005469 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005470 return std::make_pair(0U, &AArch64::FPR32RegClass);
5471 if (VT.getSizeInBits() == 64)
5472 return std::make_pair(0U, &AArch64::FPR64RegClass);
5473 if (VT.getSizeInBits() == 128)
5474 return std::make_pair(0U, &AArch64::FPR128RegClass);
5475 break;
5476 // The instructions that this constraint is designed for can
5477 // only take 128-bit registers so just use that regclass.
5478 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005479 if (!Subtarget->hasFPARMv8())
5480 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005481 if (VT.getSizeInBits() == 128)
5482 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5483 break;
5484 }
5485 }
5486 if (StringRef("{cc}").equals_lower(Constraint))
5487 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5488
5489 // Use the default implementation in TargetLowering to convert the register
5490 // constraint into a member of a register class.
5491 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005492 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005493
5494 // Not found as a standard register?
5495 if (!Res.second) {
5496 unsigned Size = Constraint.size();
5497 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5498 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005499 int RegNo;
5500 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5501 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005502 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005503 // By default we'll emit v0-v31 for this unless there's a modifier where
5504 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005505 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5506 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5507 Res.second = &AArch64::FPR64RegClass;
5508 } else {
5509 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5510 Res.second = &AArch64::FPR128RegClass;
5511 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005512 }
5513 }
5514 }
5515
Eli Friedman071203b2018-08-24 19:12:13 +00005516 if (Res.second && !Subtarget->hasFPARMv8() &&
5517 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5518 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5519 return std::make_pair(0U, nullptr);
5520
Tim Northover3b0846e2014-05-24 12:50:23 +00005521 return Res;
5522}
5523
5524/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5525/// vector. If it is invalid, don't add anything to Ops.
5526void AArch64TargetLowering::LowerAsmOperandForConstraint(
5527 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5528 SelectionDAG &DAG) const {
5529 SDValue Result;
5530
5531 // Currently only support length 1 constraints.
5532 if (Constraint.length() != 1)
5533 return;
5534
5535 char ConstraintLetter = Constraint[0];
5536 switch (ConstraintLetter) {
5537 default:
5538 break;
5539
5540 // This set of constraints deal with valid constants for various instructions.
5541 // Validate and return a target constant for them if we can.
5542 case 'z': {
5543 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005544 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005545 return;
5546
5547 if (Op.getValueType() == MVT::i64)
5548 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5549 else
5550 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5551 break;
5552 }
Peter Smithc8117582018-05-16 09:33:25 +00005553 case 'S': {
5554 // An absolute symbolic address or label reference.
5555 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5556 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5557 GA->getValueType(0));
5558 } else if (const BlockAddressSDNode *BA =
5559 dyn_cast<BlockAddressSDNode>(Op)) {
5560 Result =
5561 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5562 } else if (const ExternalSymbolSDNode *ES =
5563 dyn_cast<ExternalSymbolSDNode>(Op)) {
5564 Result =
5565 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5566 } else
5567 return;
5568 break;
5569 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005570
5571 case 'I':
5572 case 'J':
5573 case 'K':
5574 case 'L':
5575 case 'M':
5576 case 'N':
5577 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5578 if (!C)
5579 return;
5580
5581 // Grab the value and do some validation.
5582 uint64_t CVal = C->getZExtValue();
5583 switch (ConstraintLetter) {
5584 // The I constraint applies only to simple ADD or SUB immediate operands:
5585 // i.e. 0 to 4095 with optional shift by 12
5586 // The J constraint applies only to ADD or SUB immediates that would be
5587 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5588 // instruction [or vice versa], in other words -1 to -4095 with optional
5589 // left shift by 12.
5590 case 'I':
5591 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5592 break;
5593 return;
5594 case 'J': {
5595 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005596 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5597 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005598 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005599 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005600 return;
5601 }
5602 // The K and L constraints apply *only* to logical immediates, including
5603 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5604 // been removed and MOV should be used). So these constraints have to
5605 // distinguish between bit patterns that are valid 32-bit or 64-bit
5606 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5607 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5608 // versa.
5609 case 'K':
5610 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5611 break;
5612 return;
5613 case 'L':
5614 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5615 break;
5616 return;
5617 // The M and N constraints are a superset of K and L respectively, for use
5618 // with the MOV (immediate) alias. As well as the logical immediates they
5619 // also match 32 or 64-bit immediates that can be loaded either using a
5620 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5621 // (M) or 64-bit 0x1234000000000000 (N) etc.
5622 // As a note some of this code is liberally stolen from the asm parser.
5623 case 'M': {
5624 if (!isUInt<32>(CVal))
5625 return;
5626 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5627 break;
5628 if ((CVal & 0xFFFF) == CVal)
5629 break;
5630 if ((CVal & 0xFFFF0000ULL) == CVal)
5631 break;
5632 uint64_t NCVal = ~(uint32_t)CVal;
5633 if ((NCVal & 0xFFFFULL) == NCVal)
5634 break;
5635 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5636 break;
5637 return;
5638 }
5639 case 'N': {
5640 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5641 break;
5642 if ((CVal & 0xFFFFULL) == CVal)
5643 break;
5644 if ((CVal & 0xFFFF0000ULL) == CVal)
5645 break;
5646 if ((CVal & 0xFFFF00000000ULL) == CVal)
5647 break;
5648 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5649 break;
5650 uint64_t NCVal = ~CVal;
5651 if ((NCVal & 0xFFFFULL) == NCVal)
5652 break;
5653 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5654 break;
5655 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5656 break;
5657 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5658 break;
5659 return;
5660 }
5661 default:
5662 return;
5663 }
5664
5665 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005666 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005667 break;
5668 }
5669
5670 if (Result.getNode()) {
5671 Ops.push_back(Result);
5672 return;
5673 }
5674
5675 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5676}
5677
5678//===----------------------------------------------------------------------===//
5679// AArch64 Advanced SIMD Support
5680//===----------------------------------------------------------------------===//
5681
5682/// WidenVector - Given a value in the V64 register class, produce the
5683/// equivalent value in the V128 register class.
5684static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5685 EVT VT = V64Reg.getValueType();
5686 unsigned NarrowSize = VT.getVectorNumElements();
5687 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5688 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5689 SDLoc DL(V64Reg);
5690
5691 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005692 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005693}
5694
5695/// getExtFactor - Determine the adjustment factor for the position when
5696/// generating an "extract from vector registers" instruction.
5697static unsigned getExtFactor(SDValue &V) {
5698 EVT EltType = V.getValueType().getVectorElementType();
5699 return EltType.getSizeInBits() / 8;
5700}
5701
5702/// NarrowVector - Given a value in the V128 register class, produce the
5703/// equivalent value in the V64 register class.
5704static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5705 EVT VT = V128Reg.getValueType();
5706 unsigned WideSize = VT.getVectorNumElements();
5707 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5708 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5709 SDLoc DL(V128Reg);
5710
5711 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5712}
5713
5714// Gather data to see if the operation can be modelled as a
5715// shuffle in combination with VEXTs.
5716SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5717 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005718 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005719 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005720 SDLoc dl(Op);
5721 EVT VT = Op.getValueType();
5722 unsigned NumElts = VT.getVectorNumElements();
5723
Tim Northover7324e842014-07-24 15:39:55 +00005724 struct ShuffleSourceInfo {
5725 SDValue Vec;
5726 unsigned MinElt;
5727 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005728
Tim Northover7324e842014-07-24 15:39:55 +00005729 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5730 // be compatible with the shuffle we intend to construct. As a result
5731 // ShuffleVec will be some sliding window into the original Vec.
5732 SDValue ShuffleVec;
5733
5734 // Code should guarantee that element i in Vec starts at element "WindowBase
5735 // + i * WindowScale in ShuffleVec".
5736 int WindowBase;
5737 int WindowScale;
5738
Tim Northover7324e842014-07-24 15:39:55 +00005739 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005740 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5741 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5742
5743 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005744 };
5745
5746 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5747 // node.
5748 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005749 for (unsigned i = 0; i < NumElts; ++i) {
5750 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005751 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005752 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005753 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5754 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005755 LLVM_DEBUG(
5756 dbgs() << "Reshuffle failed: "
5757 "a shuffle can only come from building a vector from "
5758 "various elements of other vectors, provided their "
5759 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005760 return SDValue();
5761 }
5762
Tim Northover7324e842014-07-24 15:39:55 +00005763 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005764 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005765 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005766 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005767 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005768
Tim Northover7324e842014-07-24 15:39:55 +00005769 // Update the minimum and maximum lane number seen.
5770 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5771 Source->MinElt = std::min(Source->MinElt, EltNo);
5772 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005773 }
5774
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005775 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005776 LLVM_DEBUG(
5777 dbgs() << "Reshuffle failed: currently only do something sane when at "
5778 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005779 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005780 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005781
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005782 // Find out the smallest element size among result and two sources, and use
5783 // it as element size to build the shuffle_vector.
5784 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005785 for (auto &Source : Sources) {
5786 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005787 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5788 SmallestEltTy = SrcEltTy;
5789 }
5790 }
5791 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005792 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005793 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5794 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005795
Tim Northover7324e842014-07-24 15:39:55 +00005796 // If the source vector is too wide or too narrow, we may nevertheless be able
5797 // to construct a compatible shuffle either by concatenating it with UNDEF or
5798 // extracting a suitable range of elements.
5799 for (auto &Src : Sources) {
5800 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005801
Tim Northover7324e842014-07-24 15:39:55 +00005802 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005803 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005804
5805 // This stage of the search produces a source with the same element type as
5806 // the original, but with a total width matching the BUILD_VECTOR output.
5807 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005808 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5809 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005810
5811 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5812 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005813 // We can pad out the smaller vector for free, so if it's part of a
5814 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005815 Src.ShuffleVec =
5816 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5817 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005818 continue;
5819 }
5820
Tim Northover7324e842014-07-24 15:39:55 +00005821 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005822
James Molloyf497d552014-10-17 17:06:31 +00005823 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005824 LLVM_DEBUG(
5825 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005826 return SDValue();
5827 }
5828
James Molloyf497d552014-10-17 17:06:31 +00005829 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005830 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005831 Src.ShuffleVec =
5832 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005833 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005834 Src.WindowBase = -NumSrcElts;
5835 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005836 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005837 Src.ShuffleVec =
5838 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005839 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005840 } else {
5841 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005842 SDValue VEXTSrc1 =
5843 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005844 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005845 SDValue VEXTSrc2 =
5846 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005847 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005848 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5849
5850 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005851 VEXTSrc2,
5852 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005853 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005854 }
5855 }
5856
Tim Northover7324e842014-07-24 15:39:55 +00005857 // Another possible incompatibility occurs from the vector element types. We
5858 // can fix this by bitcasting the source vectors to the same type we intend
5859 // for the shuffle.
5860 for (auto &Src : Sources) {
5861 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5862 if (SrcEltTy == SmallestEltTy)
5863 continue;
5864 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5865 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5866 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5867 Src.WindowBase *= Src.WindowScale;
5868 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005869
Tim Northover7324e842014-07-24 15:39:55 +00005870 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005871 LLVM_DEBUG(for (auto Src
5872 : Sources)
5873 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00005874
5875 // The stars all align, our next step is to produce the mask for the shuffle.
5876 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005877 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005878 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005879 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005880 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005881 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005882
David Majnemer0d955d02016-08-11 22:21:41 +00005883 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005884 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5885
5886 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5887 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5888 // segment.
5889 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005890 int BitsDefined =
5891 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005892 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5893
5894 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5895 // starting at the appropriate offset.
5896 int *LaneMask = &Mask[i * ResMultiplier];
5897
5898 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5899 ExtractBase += NumElts * (Src - Sources.begin());
5900 for (int j = 0; j < LanesDefined; ++j)
5901 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005902 }
5903
5904 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005905 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005906 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00005907 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005908 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005909
Tim Northover7324e842014-07-24 15:39:55 +00005910 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5911 for (unsigned i = 0; i < Sources.size(); ++i)
5912 ShuffleOps[i] = Sources[i].ShuffleVec;
5913
5914 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005915 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005916 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5917
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005918 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
5919 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005920
5921 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00005922}
5923
5924// check if an EXT instruction can handle the shuffle mask when the
5925// vector sources of the shuffle are the same.
5926static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5927 unsigned NumElts = VT.getVectorNumElements();
5928
5929 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5930 if (M[0] < 0)
5931 return false;
5932
5933 Imm = M[0];
5934
5935 // If this is a VEXT shuffle, the immediate value is the index of the first
5936 // element. The other shuffle indices must be the successive elements after
5937 // the first one.
5938 unsigned ExpectedElt = Imm;
5939 for (unsigned i = 1; i < NumElts; ++i) {
5940 // Increment the expected index. If it wraps around, just follow it
5941 // back to index zero and keep going.
5942 ++ExpectedElt;
5943 if (ExpectedElt == NumElts)
5944 ExpectedElt = 0;
5945
5946 if (M[i] < 0)
5947 continue; // ignore UNDEF indices
5948 if (ExpectedElt != static_cast<unsigned>(M[i]))
5949 return false;
5950 }
5951
5952 return true;
5953}
5954
5955// check if an EXT instruction can handle the shuffle mask when the
5956// vector sources of the shuffle are different.
5957static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5958 unsigned &Imm) {
5959 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005960 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005961
5962 // Benefit form APInt to handle overflow when calculating expected element.
5963 unsigned NumElts = VT.getVectorNumElements();
5964 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5965 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5966 // The following shuffle indices must be the successive elements after the
5967 // first real element.
5968 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5969 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5970 if (FirstWrongElt != M.end())
5971 return false;
5972
5973 // The index of an EXT is the first element if it is not UNDEF.
5974 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005975 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005976 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5977 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5978 // ExpectedElt is the last mask index plus 1.
5979 Imm = ExpectedElt.getZExtValue();
5980
5981 // There are two difference cases requiring to reverse input vectors.
5982 // For example, for vector <4 x i32> we have the following cases,
5983 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5984 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5985 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5986 // to reverse two input vectors.
5987 if (Imm < NumElts)
5988 ReverseEXT = true;
5989 else
5990 Imm -= NumElts;
5991
5992 return true;
5993}
5994
5995/// isREVMask - Check if a vector shuffle corresponds to a REV
5996/// instruction with the specified blocksize. (The order of the elements
5997/// within each block of the vector is reversed.)
5998static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5999 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6000 "Only possible block sizes for REV are: 16, 32, 64");
6001
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006002 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006003 if (EltSz == 64)
6004 return false;
6005
6006 unsigned NumElts = VT.getVectorNumElements();
6007 unsigned BlockElts = M[0] + 1;
6008 // If the first shuffle index is UNDEF, be optimistic.
6009 if (M[0] < 0)
6010 BlockElts = BlockSize / EltSz;
6011
6012 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6013 return false;
6014
6015 for (unsigned i = 0; i < NumElts; ++i) {
6016 if (M[i] < 0)
6017 continue; // ignore UNDEF indices
6018 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6019 return false;
6020 }
6021
6022 return true;
6023}
6024
6025static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6026 unsigned NumElts = VT.getVectorNumElements();
6027 WhichResult = (M[0] == 0 ? 0 : 1);
6028 unsigned Idx = WhichResult * NumElts / 2;
6029 for (unsigned i = 0; i != NumElts; i += 2) {
6030 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6031 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6032 return false;
6033 Idx += 1;
6034 }
6035
6036 return true;
6037}
6038
6039static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6040 unsigned NumElts = VT.getVectorNumElements();
6041 WhichResult = (M[0] == 0 ? 0 : 1);
6042 for (unsigned i = 0; i != NumElts; ++i) {
6043 if (M[i] < 0)
6044 continue; // ignore UNDEF indices
6045 if ((unsigned)M[i] != 2 * i + WhichResult)
6046 return false;
6047 }
6048
6049 return true;
6050}
6051
6052static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6053 unsigned NumElts = VT.getVectorNumElements();
6054 WhichResult = (M[0] == 0 ? 0 : 1);
6055 for (unsigned i = 0; i < NumElts; i += 2) {
6056 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6057 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6058 return false;
6059 }
6060 return true;
6061}
6062
6063/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6064/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6065/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6066static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6067 unsigned NumElts = VT.getVectorNumElements();
6068 WhichResult = (M[0] == 0 ? 0 : 1);
6069 unsigned Idx = WhichResult * NumElts / 2;
6070 for (unsigned i = 0; i != NumElts; i += 2) {
6071 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6072 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6073 return false;
6074 Idx += 1;
6075 }
6076
6077 return true;
6078}
6079
6080/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6081/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6082/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6083static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6084 unsigned Half = VT.getVectorNumElements() / 2;
6085 WhichResult = (M[0] == 0 ? 0 : 1);
6086 for (unsigned j = 0; j != 2; ++j) {
6087 unsigned Idx = WhichResult;
6088 for (unsigned i = 0; i != Half; ++i) {
6089 int MIdx = M[i + j * Half];
6090 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6091 return false;
6092 Idx += 2;
6093 }
6094 }
6095
6096 return true;
6097}
6098
6099/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6100/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6101/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6102static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6103 unsigned NumElts = VT.getVectorNumElements();
6104 WhichResult = (M[0] == 0 ? 0 : 1);
6105 for (unsigned i = 0; i < NumElts; i += 2) {
6106 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6107 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6108 return false;
6109 }
6110 return true;
6111}
6112
6113static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6114 bool &DstIsLeft, int &Anomaly) {
6115 if (M.size() != static_cast<size_t>(NumInputElements))
6116 return false;
6117
6118 int NumLHSMatch = 0, NumRHSMatch = 0;
6119 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6120
6121 for (int i = 0; i < NumInputElements; ++i) {
6122 if (M[i] == -1) {
6123 ++NumLHSMatch;
6124 ++NumRHSMatch;
6125 continue;
6126 }
6127
6128 if (M[i] == i)
6129 ++NumLHSMatch;
6130 else
6131 LastLHSMismatch = i;
6132
6133 if (M[i] == i + NumInputElements)
6134 ++NumRHSMatch;
6135 else
6136 LastRHSMismatch = i;
6137 }
6138
6139 if (NumLHSMatch == NumInputElements - 1) {
6140 DstIsLeft = true;
6141 Anomaly = LastLHSMismatch;
6142 return true;
6143 } else if (NumRHSMatch == NumInputElements - 1) {
6144 DstIsLeft = false;
6145 Anomaly = LastRHSMismatch;
6146 return true;
6147 }
6148
6149 return false;
6150}
6151
6152static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6153 if (VT.getSizeInBits() != 128)
6154 return false;
6155
6156 unsigned NumElts = VT.getVectorNumElements();
6157
6158 for (int I = 0, E = NumElts / 2; I != E; I++) {
6159 if (Mask[I] != I)
6160 return false;
6161 }
6162
6163 int Offset = NumElts / 2;
6164 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6165 if (Mask[I] != I + SplitLHS * Offset)
6166 return false;
6167 }
6168
6169 return true;
6170}
6171
6172static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6173 SDLoc DL(Op);
6174 EVT VT = Op.getValueType();
6175 SDValue V0 = Op.getOperand(0);
6176 SDValue V1 = Op.getOperand(1);
6177 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6178
6179 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6180 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6181 return SDValue();
6182
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006183 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006184
6185 if (!isConcatMask(Mask, VT, SplitV0))
6186 return SDValue();
6187
6188 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6189 VT.getVectorNumElements() / 2);
6190 if (SplitV0) {
6191 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006192 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006193 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006194 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006195 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006196 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006197 }
6198 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6199}
6200
6201/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6202/// the specified operations to build the shuffle.
6203static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6204 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006205 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006206 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6207 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6208 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6209
6210 enum {
6211 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6212 OP_VREV,
6213 OP_VDUP0,
6214 OP_VDUP1,
6215 OP_VDUP2,
6216 OP_VDUP3,
6217 OP_VEXT1,
6218 OP_VEXT2,
6219 OP_VEXT3,
6220 OP_VUZPL, // VUZP, left result
6221 OP_VUZPR, // VUZP, right result
6222 OP_VZIPL, // VZIP, left result
6223 OP_VZIPR, // VZIP, right result
6224 OP_VTRNL, // VTRN, left result
6225 OP_VTRNR // VTRN, right result
6226 };
6227
6228 if (OpNum == OP_COPY) {
6229 if (LHSID == (1 * 9 + 2) * 9 + 3)
6230 return LHS;
6231 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6232 return RHS;
6233 }
6234
6235 SDValue OpLHS, OpRHS;
6236 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6237 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6238 EVT VT = OpLHS.getValueType();
6239
6240 switch (OpNum) {
6241 default:
6242 llvm_unreachable("Unknown shuffle opcode!");
6243 case OP_VREV:
6244 // VREV divides the vector in half and swaps within the half.
6245 if (VT.getVectorElementType() == MVT::i32 ||
6246 VT.getVectorElementType() == MVT::f32)
6247 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6248 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006249 if (VT.getVectorElementType() == MVT::i16 ||
6250 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006251 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6252 // vrev <4 x i8> -> REV16
6253 assert(VT.getVectorElementType() == MVT::i8);
6254 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6255 case OP_VDUP0:
6256 case OP_VDUP1:
6257 case OP_VDUP2:
6258 case OP_VDUP3: {
6259 EVT EltTy = VT.getVectorElementType();
6260 unsigned Opcode;
6261 if (EltTy == MVT::i8)
6262 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006263 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006264 Opcode = AArch64ISD::DUPLANE16;
6265 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6266 Opcode = AArch64ISD::DUPLANE32;
6267 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6268 Opcode = AArch64ISD::DUPLANE64;
6269 else
6270 llvm_unreachable("Invalid vector element type?");
6271
6272 if (VT.getSizeInBits() == 64)
6273 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006274 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006275 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6276 }
6277 case OP_VEXT1:
6278 case OP_VEXT2:
6279 case OP_VEXT3: {
6280 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6281 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006282 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006283 }
6284 case OP_VUZPL:
6285 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6286 OpRHS);
6287 case OP_VUZPR:
6288 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6289 OpRHS);
6290 case OP_VZIPL:
6291 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6292 OpRHS);
6293 case OP_VZIPR:
6294 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6295 OpRHS);
6296 case OP_VTRNL:
6297 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6298 OpRHS);
6299 case OP_VTRNR:
6300 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6301 OpRHS);
6302 }
6303}
6304
6305static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6306 SelectionDAG &DAG) {
6307 // Check to see if we can use the TBL instruction.
6308 SDValue V1 = Op.getOperand(0);
6309 SDValue V2 = Op.getOperand(1);
6310 SDLoc DL(Op);
6311
6312 EVT EltVT = Op.getValueType().getVectorElementType();
6313 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6314
6315 SmallVector<SDValue, 8> TBLMask;
6316 for (int Val : ShuffleMask) {
6317 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6318 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006319 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006320 }
6321 }
6322
6323 MVT IndexVT = MVT::v8i8;
6324 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006325 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006326 IndexVT = MVT::v16i8;
6327 IndexLen = 16;
6328 }
6329
6330 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6331 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6332
6333 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006334 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006335 if (IndexLen == 8)
6336 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6337 Shuffle = DAG.getNode(
6338 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006339 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006340 DAG.getBuildVector(IndexVT, DL,
6341 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006342 } else {
6343 if (IndexLen == 8) {
6344 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6345 Shuffle = DAG.getNode(
6346 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006347 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006348 DAG.getBuildVector(IndexVT, DL,
6349 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006350 } else {
6351 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6352 // cannot currently represent the register constraints on the input
6353 // table registers.
6354 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006355 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6356 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006357 Shuffle = DAG.getNode(
6358 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006359 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6360 V2Cst, DAG.getBuildVector(IndexVT, DL,
6361 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006362 }
6363 }
6364 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6365}
6366
6367static unsigned getDUPLANEOp(EVT EltType) {
6368 if (EltType == MVT::i8)
6369 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006370 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006371 return AArch64ISD::DUPLANE16;
6372 if (EltType == MVT::i32 || EltType == MVT::f32)
6373 return AArch64ISD::DUPLANE32;
6374 if (EltType == MVT::i64 || EltType == MVT::f64)
6375 return AArch64ISD::DUPLANE64;
6376
6377 llvm_unreachable("Invalid vector element type?");
6378}
6379
6380SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6381 SelectionDAG &DAG) const {
6382 SDLoc dl(Op);
6383 EVT VT = Op.getValueType();
6384
6385 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6386
6387 // Convert shuffles that are directly supported on NEON to target-specific
6388 // DAG nodes, instead of keeping them as shuffles and matching them again
6389 // during code selection. This is more efficient and avoids the possibility
6390 // of inconsistencies between legalization and selection.
6391 ArrayRef<int> ShuffleMask = SVN->getMask();
6392
6393 SDValue V1 = Op.getOperand(0);
6394 SDValue V2 = Op.getOperand(1);
6395
Craig Topperbc56e3b2016-06-30 04:38:51 +00006396 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006397 int Lane = SVN->getSplatIndex();
6398 // If this is undef splat, generate it via "just" vdup, if possible.
6399 if (Lane == -1)
6400 Lane = 0;
6401
6402 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6403 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6404 V1.getOperand(0));
6405 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6406 // constant. If so, we can just reference the lane's definition directly.
6407 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6408 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6409 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6410
6411 // Otherwise, duplicate from the lane of the input vector.
6412 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6413
6414 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6415 // to make a vector of the same size as this SHUFFLE. We can ignore the
6416 // extract entirely, and canonicalise the concat using WidenVector.
6417 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6418 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6419 V1 = V1.getOperand(0);
6420 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6421 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6422 Lane -= Idx * VT.getVectorNumElements() / 2;
6423 V1 = WidenVector(V1.getOperand(Idx), DAG);
6424 } else if (VT.getSizeInBits() == 64)
6425 V1 = WidenVector(V1, DAG);
6426
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006427 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006428 }
6429
6430 if (isREVMask(ShuffleMask, VT, 64))
6431 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6432 if (isREVMask(ShuffleMask, VT, 32))
6433 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6434 if (isREVMask(ShuffleMask, VT, 16))
6435 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6436
6437 bool ReverseEXT = false;
6438 unsigned Imm;
6439 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6440 if (ReverseEXT)
6441 std::swap(V1, V2);
6442 Imm *= getExtFactor(V1);
6443 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006444 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006445 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006446 Imm *= getExtFactor(V1);
6447 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006448 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006449 }
6450
6451 unsigned WhichResult;
6452 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6453 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6454 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6455 }
6456 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6457 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6458 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6459 }
6460 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6461 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6462 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6463 }
6464
6465 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6466 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6467 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6468 }
6469 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6470 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6471 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6472 }
6473 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6474 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6475 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6476 }
6477
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006478 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006479 return Concat;
6480
6481 bool DstIsLeft;
6482 int Anomaly;
6483 int NumInputElements = V1.getValueType().getVectorNumElements();
6484 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6485 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006486 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006487
6488 SDValue SrcVec = V1;
6489 int SrcLane = ShuffleMask[Anomaly];
6490 if (SrcLane >= NumInputElements) {
6491 SrcVec = V2;
6492 SrcLane -= VT.getVectorNumElements();
6493 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006494 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006495
6496 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006497
6498 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006499 ScalarVT = MVT::i32;
6500
6501 return DAG.getNode(
6502 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6503 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6504 DstLaneV);
6505 }
6506
6507 // If the shuffle is not directly supported and it has 4 elements, use
6508 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6509 unsigned NumElts = VT.getVectorNumElements();
6510 if (NumElts == 4) {
6511 unsigned PFIndexes[4];
6512 for (unsigned i = 0; i != 4; ++i) {
6513 if (ShuffleMask[i] < 0)
6514 PFIndexes[i] = 8;
6515 else
6516 PFIndexes[i] = ShuffleMask[i];
6517 }
6518
6519 // Compute the index in the perfect shuffle table.
6520 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6521 PFIndexes[2] * 9 + PFIndexes[3];
6522 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6523 unsigned Cost = (PFEntry >> 30);
6524
6525 if (Cost <= 4)
6526 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6527 }
6528
6529 return GenerateTBL(Op, ShuffleMask, DAG);
6530}
6531
6532static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6533 APInt &UndefBits) {
6534 EVT VT = BVN->getValueType(0);
6535 APInt SplatBits, SplatUndef;
6536 unsigned SplatBitSize;
6537 bool HasAnyUndefs;
6538 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6539 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6540
6541 for (unsigned i = 0; i < NumSplats; ++i) {
6542 CnstBits <<= SplatBitSize;
6543 UndefBits <<= SplatBitSize;
6544 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6545 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6546 }
6547
6548 return true;
6549 }
6550
6551 return false;
6552}
6553
Evandro Menezes72f39832018-02-20 20:31:45 +00006554// Try 64-bit splatted SIMD immediate.
6555static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6556 const APInt &Bits) {
6557 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6558 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6559 EVT VT = Op.getValueType();
6560 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6561
6562 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6563 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6564
6565 SDLoc dl(Op);
6566 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6567 DAG.getConstant(Value, dl, MVT::i32));
6568 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6569 }
6570 }
6571
6572 return SDValue();
6573}
6574
6575// Try 32-bit splatted SIMD immediate.
6576static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6577 const APInt &Bits,
6578 const SDValue *LHS = nullptr) {
6579 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6580 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6581 EVT VT = Op.getValueType();
6582 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6583 bool isAdvSIMDModImm = false;
6584 uint64_t Shift;
6585
6586 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6587 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6588 Shift = 0;
6589 }
6590 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6591 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6592 Shift = 8;
6593 }
6594 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6595 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6596 Shift = 16;
6597 }
6598 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6599 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6600 Shift = 24;
6601 }
6602
6603 if (isAdvSIMDModImm) {
6604 SDLoc dl(Op);
6605 SDValue Mov;
6606
6607 if (LHS)
6608 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6609 DAG.getConstant(Value, dl, MVT::i32),
6610 DAG.getConstant(Shift, dl, MVT::i32));
6611 else
6612 Mov = DAG.getNode(NewOp, dl, MovTy,
6613 DAG.getConstant(Value, dl, MVT::i32),
6614 DAG.getConstant(Shift, dl, MVT::i32));
6615
6616 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6617 }
6618 }
6619
6620 return SDValue();
6621}
6622
6623// Try 16-bit splatted SIMD immediate.
6624static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6625 const APInt &Bits,
6626 const SDValue *LHS = nullptr) {
6627 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6628 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6629 EVT VT = Op.getValueType();
6630 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6631 bool isAdvSIMDModImm = false;
6632 uint64_t Shift;
6633
6634 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6635 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6636 Shift = 0;
6637 }
6638 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6639 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6640 Shift = 8;
6641 }
6642
6643 if (isAdvSIMDModImm) {
6644 SDLoc dl(Op);
6645 SDValue Mov;
6646
6647 if (LHS)
6648 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006649 DAG.getConstant(Value, dl, MVT::i32),
6650 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006651 else
6652 Mov = DAG.getNode(NewOp, dl, MovTy,
6653 DAG.getConstant(Value, dl, MVT::i32),
6654 DAG.getConstant(Shift, dl, MVT::i32));
6655
6656 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6657 }
6658 }
6659
6660 return SDValue();
6661}
6662
6663// Try 32-bit splatted SIMD immediate with shifted ones.
6664static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6665 SelectionDAG &DAG, const APInt &Bits) {
6666 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6667 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6668 EVT VT = Op.getValueType();
6669 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6670 bool isAdvSIMDModImm = false;
6671 uint64_t Shift;
6672
6673 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6674 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6675 Shift = 264;
6676 }
6677 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6678 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6679 Shift = 272;
6680 }
6681
6682 if (isAdvSIMDModImm) {
6683 SDLoc dl(Op);
6684 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6685 DAG.getConstant(Value, dl, MVT::i32),
6686 DAG.getConstant(Shift, dl, MVT::i32));
6687 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6688 }
6689 }
6690
6691 return SDValue();
6692}
6693
6694// Try 8-bit splatted SIMD immediate.
6695static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6696 const APInt &Bits) {
6697 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6698 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6699 EVT VT = Op.getValueType();
6700 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6701
6702 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6703 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6704
6705 SDLoc dl(Op);
6706 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6707 DAG.getConstant(Value, dl, MVT::i32));
6708 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6709 }
6710 }
6711
6712 return SDValue();
6713}
6714
6715// Try FP splatted SIMD immediate.
6716static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6717 const APInt &Bits) {
6718 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6719 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6720 EVT VT = Op.getValueType();
6721 bool isWide = (VT.getSizeInBits() == 128);
6722 MVT MovTy;
6723 bool isAdvSIMDModImm = false;
6724
6725 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6726 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6727 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6728 }
6729 else if (isWide &&
6730 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6731 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6732 MovTy = MVT::v2f64;
6733 }
6734
6735 if (isAdvSIMDModImm) {
6736 SDLoc dl(Op);
6737 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6738 DAG.getConstant(Value, dl, MVT::i32));
6739 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6740 }
6741 }
6742
6743 return SDValue();
6744}
6745
Tim Northover3b0846e2014-05-24 12:50:23 +00006746SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6747 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006748 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006749 EVT VT = Op.getValueType();
6750
Evandro Menezes72f39832018-02-20 20:31:45 +00006751 BuildVectorSDNode *BVN =
6752 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6753 if (!BVN) {
6754 // AND commutes, so try swapping the operands.
6755 LHS = Op.getOperand(1);
6756 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6757 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006758 if (!BVN)
6759 return Op;
6760
Evandro Menezes72f39832018-02-20 20:31:45 +00006761 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006762 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006763 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6764 SDValue NewOp;
6765
Tim Northover3b0846e2014-05-24 12:50:23 +00006766 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006767 DefBits = ~DefBits;
6768 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6769 DefBits, &LHS)) ||
6770 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6771 DefBits, &LHS)))
6772 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006773
6774 UndefBits = ~UndefBits;
6775 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6776 UndefBits, &LHS)) ||
6777 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6778 UndefBits, &LHS)))
6779 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006780 }
6781
Evandro Menezes72f39832018-02-20 20:31:45 +00006782 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006783 return Op;
6784}
6785
6786// Specialized code to quickly find if PotentialBVec is a BuildVector that
6787// consists of only the same constant int value, returned in reference arg
6788// ConstVal
6789static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6790 uint64_t &ConstVal) {
6791 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6792 if (!Bvec)
6793 return false;
6794 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6795 if (!FirstElt)
6796 return false;
6797 EVT VT = Bvec->getValueType(0);
6798 unsigned NumElts = VT.getVectorNumElements();
6799 for (unsigned i = 1; i < NumElts; ++i)
6800 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6801 return false;
6802 ConstVal = FirstElt->getZExtValue();
6803 return true;
6804}
6805
6806static unsigned getIntrinsicID(const SDNode *N) {
6807 unsigned Opcode = N->getOpcode();
6808 switch (Opcode) {
6809 default:
6810 return Intrinsic::not_intrinsic;
6811 case ISD::INTRINSIC_WO_CHAIN: {
6812 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6813 if (IID < Intrinsic::num_intrinsics)
6814 return IID;
6815 return Intrinsic::not_intrinsic;
6816 }
6817 }
6818}
6819
6820// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6821// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6822// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6823// Also, logical shift right -> sri, with the same structure.
6824static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6825 EVT VT = N->getValueType(0);
6826
6827 if (!VT.isVector())
6828 return SDValue();
6829
6830 SDLoc DL(N);
6831
6832 // Is the first op an AND?
6833 const SDValue And = N->getOperand(0);
6834 if (And.getOpcode() != ISD::AND)
6835 return SDValue();
6836
6837 // Is the second op an shl or lshr?
6838 SDValue Shift = N->getOperand(1);
6839 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6840 // or AArch64ISD::VLSHR vector, #shift
6841 unsigned ShiftOpc = Shift.getOpcode();
6842 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6843 return SDValue();
6844 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6845
6846 // Is the shift amount constant?
6847 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6848 if (!C2node)
6849 return SDValue();
6850
6851 // Is the and mask vector all constant?
6852 uint64_t C1;
6853 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6854 return SDValue();
6855
6856 // Is C1 == ~C2, taking into account how much one can shift elements of a
6857 // particular size?
6858 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006859 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006860 if (C2 > ElemSizeInBits)
6861 return SDValue();
6862 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6863 if ((C1 & ElemMask) != (~C2 & ElemMask))
6864 return SDValue();
6865
6866 SDValue X = And.getOperand(0);
6867 SDValue Y = Shift.getOperand(0);
6868
6869 unsigned Intrin =
6870 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6871 SDValue ResultSLI =
6872 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006873 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6874 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006875
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006876 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6877 LLVM_DEBUG(N->dump(&DAG));
6878 LLVM_DEBUG(dbgs() << "into: \n");
6879 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00006880
6881 ++NumShiftInserts;
6882 return ResultSLI;
6883}
6884
6885SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6886 SelectionDAG &DAG) const {
6887 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6888 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006889 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006890 return Res;
6891 }
6892
Tim Northover3b0846e2014-05-24 12:50:23 +00006893 EVT VT = Op.getValueType();
6894
Evandro Menezescd855f72018-03-05 17:02:47 +00006895 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006896 BuildVectorSDNode *BVN =
6897 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006898 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00006899 // OR commutes, so try swapping the operands.
6900 LHS = Op.getOperand(1);
6901 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006902 }
6903 if (!BVN)
6904 return Op;
6905
Evandro Menezes72f39832018-02-20 20:31:45 +00006906 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006907 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006908 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6909 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006910
Evandro Menezes72f39832018-02-20 20:31:45 +00006911 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
6912 DefBits, &LHS)) ||
6913 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
6914 DefBits, &LHS)))
6915 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006916
6917 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
6918 UndefBits, &LHS)) ||
6919 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
6920 UndefBits, &LHS)))
6921 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006922 }
6923
Evandro Menezes72f39832018-02-20 20:31:45 +00006924 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00006925 return Op;
6926}
6927
Kevin Qin4473c192014-07-07 02:45:40 +00006928// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6929// be truncated to fit element width.
6930static SDValue NormalizeBuildVector(SDValue Op,
6931 SelectionDAG &DAG) {
6932 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006933 SDLoc dl(Op);
6934 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006935 EVT EltTy= VT.getVectorElementType();
6936
6937 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6938 return Op;
6939
6940 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006941 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00006942 // For integer vectors, type legalization would have promoted the
6943 // operands already. Otherwise, if Op is a floating-point splat
6944 // (with operands cast to integers), then the only possibilities
6945 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006946 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006947 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006948 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006949 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00006950 } else if (Lane.getNode()->isUndef()) {
6951 Lane = DAG.getUNDEF(MVT::i32);
6952 } else {
6953 assert(Lane.getValueType() == MVT::i32 &&
6954 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00006955 }
6956 Ops.push_back(Lane);
6957 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006958 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006959}
6960
Evandro Menezescd855f72018-03-05 17:02:47 +00006961static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00006962 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00006963
Evandro Menezes72f39832018-02-20 20:31:45 +00006964 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006965 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00006966 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00006967 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00006968 SDValue NewOp;
6969 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
6970 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6971 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
6972 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6973 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
6974 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
6975 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006976
Evandro Menezes72f39832018-02-20 20:31:45 +00006977 DefBits = ~DefBits;
6978 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
6979 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
6980 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
6981 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006982
Evandro Menezes72f39832018-02-20 20:31:45 +00006983 DefBits = UndefBits;
6984 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
6985 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6986 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
6987 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6988 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
6989 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
6990 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006991
Evandro Menezes72f39832018-02-20 20:31:45 +00006992 DefBits = ~UndefBits;
6993 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
6994 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
6995 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
6996 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006997 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006998
Evandro Menezescd855f72018-03-05 17:02:47 +00006999 return SDValue();
7000}
7001
7002SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7003 SelectionDAG &DAG) const {
7004 EVT VT = Op.getValueType();
7005
7006 // Try to build a simple constant vector.
7007 Op = NormalizeBuildVector(Op, DAG);
7008 if (VT.isInteger()) {
7009 // Certain vector constants, used to express things like logical NOT and
7010 // arithmetic NEG, are passed through unmodified. This allows special
7011 // patterns for these operations to match, which will lower these constants
7012 // to whatever is proven necessary.
7013 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7014 if (BVN->isConstant())
7015 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7016 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7017 APInt Val(BitSize,
7018 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7019 if (Val.isNullValue() || Val.isAllOnesValue())
7020 return Op;
7021 }
7022 }
7023
7024 if (SDValue V = ConstantBuildVector(Op, DAG))
7025 return V;
7026
Tim Northover3b0846e2014-05-24 12:50:23 +00007027 // Scan through the operands to find some interesting properties we can
7028 // exploit:
7029 // 1) If only one value is used, we can use a DUP, or
7030 // 2) if only the low element is not undef, we can just insert that, or
7031 // 3) if only one constant value is used (w/ some non-constant lanes),
7032 // we can splat the constant value into the whole vector then fill
7033 // in the non-constant lanes.
7034 // 4) FIXME: If different constant values are used, but we can intelligently
7035 // select the values we'll be overwriting for the non-constant
7036 // lanes such that we can directly materialize the vector
7037 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007038 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007039 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007040 unsigned NumElts = VT.getVectorNumElements();
7041 bool isOnlyLowElement = true;
7042 bool usesOnlyOneValue = true;
7043 bool usesOnlyOneConstantValue = true;
7044 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007045 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007046 unsigned NumConstantLanes = 0;
7047 SDValue Value;
7048 SDValue ConstantValue;
7049 for (unsigned i = 0; i < NumElts; ++i) {
7050 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007051 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7052 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007053 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007054 continue;
7055 if (i > 0)
7056 isOnlyLowElement = false;
7057 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7058 isConstant = false;
7059
7060 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7061 ++NumConstantLanes;
7062 if (!ConstantValue.getNode())
7063 ConstantValue = V;
7064 else if (ConstantValue != V)
7065 usesOnlyOneConstantValue = false;
7066 }
7067
7068 if (!Value.getNode())
7069 Value = V;
7070 else if (V != Value)
7071 usesOnlyOneValue = false;
7072 }
7073
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007074 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007075 LLVM_DEBUG(
7076 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007077 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007078 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007079
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007080 if (isOnlyLowElement) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007081 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7082 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007083 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007084 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007085
Sebastian Popc33af712018-03-01 15:47:39 +00007086 if (AllLanesExtractElt) {
7087 SDNode *Vector = nullptr;
7088 bool Even = false;
7089 bool Odd = false;
7090 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7091 // the Odd pattern <1,3,5,...>.
7092 for (unsigned i = 0; i < NumElts; ++i) {
7093 SDValue V = Op.getOperand(i);
7094 const SDNode *N = V.getNode();
7095 if (!isa<ConstantSDNode>(N->getOperand(1)))
7096 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007097 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007098
7099 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007100 if (!Vector) {
7101 Vector = N0.getNode();
7102 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7103 // BUILD_VECTOR.
7104 if (VT.getVectorElementType() !=
7105 N0.getValueType().getVectorElementType())
7106 break;
7107 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007108 Odd = false;
7109 Even = false;
7110 break;
7111 }
7112
7113 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7114 // indices <1,3,5,...>.
7115 uint64_t Val = N->getConstantOperandVal(1);
7116 if (Val == 2 * i) {
7117 Even = true;
7118 continue;
7119 }
7120 if (Val - 1 == 2 * i) {
7121 Odd = true;
7122 continue;
7123 }
7124
7125 // Something does not match: abort.
7126 Odd = false;
7127 Even = false;
7128 break;
7129 }
7130 if (Even || Odd) {
7131 SDValue LHS =
7132 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7133 DAG.getConstant(0, dl, MVT::i64));
7134 SDValue RHS =
7135 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7136 DAG.getConstant(NumElts, dl, MVT::i64));
7137
7138 if (Even && !Odd)
7139 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7140 RHS);
7141 if (Odd && !Even)
7142 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7143 RHS);
7144 }
7145 }
7146
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007147 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007148 // i32 and try again.
7149 if (usesOnlyOneValue) {
7150 if (!isConstant) {
7151 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007152 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007153 LLVM_DEBUG(
7154 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007155 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007156 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007157
7158 // This is actually a DUPLANExx operation, which keeps everything vectory.
7159
Tim Northover3b0846e2014-05-24 12:50:23 +00007160 SDValue Lane = Value.getOperand(1);
7161 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007162 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007163 LLVM_DEBUG(
7164 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7165 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007166 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007167 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007168
7169 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7170 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7171 }
7172
7173 if (VT.getVectorElementType().isFloatingPoint()) {
7174 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007175 EVT EltTy = VT.getVectorElementType();
7176 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7177 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007178 LLVM_DEBUG(
7179 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7180 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007181 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007182 for (unsigned i = 0; i < NumElts; ++i)
7183 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7184 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007185 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007186 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7187 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007188 Val = LowerBUILD_VECTOR(Val, DAG);
7189 if (Val.getNode())
7190 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7191 }
7192 }
7193
7194 // If there was only one constant value used and for more than one lane,
7195 // start by splatting that value, then replace the non-constant lanes. This
7196 // is better than the default, which will perform a separate initialization
7197 // for each lane.
7198 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007199 // Firstly, try to materialize the splat constant.
7200 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7201 Val = ConstantBuildVector(Vec, DAG);
7202 if (!Val) {
7203 // Otherwise, materialize the constant and splat it.
7204 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7205 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7206 }
7207
Tim Northover3b0846e2014-05-24 12:50:23 +00007208 // Now insert the non-constant lanes.
7209 for (unsigned i = 0; i < NumElts; ++i) {
7210 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007211 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007212 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007213 // Note that type legalization likely mucked about with the VT of the
7214 // source operand, so we may have to convert it here before inserting.
7215 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007216 }
7217 return Val;
7218 }
7219
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007220 // This will generate a load from the constant pool.
7221 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007222 LLVM_DEBUG(
7223 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7224 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007225 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007226 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007227
7228 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7229 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007230 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007231 return shuffle;
7232 }
7233
7234 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7235 // know the default expansion would otherwise fall back on something even
7236 // worse. For a vector with one or two non-undef values, that's
7237 // scalar_to_vector for the elements followed by a shuffle (provided the
7238 // shuffle is valid for the target) and materialization element by element
7239 // on the stack followed by a load for everything else.
7240 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007241 LLVM_DEBUG(
7242 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7243 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007244
Tim Northover3b0846e2014-05-24 12:50:23 +00007245 SDValue Vec = DAG.getUNDEF(VT);
7246 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007247 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007248
7249 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007250 // a) Avoid a RMW dependency on the full vector register, and
7251 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007252 // value is already in an S or D register, and we're forced to emit an
7253 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007254 //
7255 // We also allow types like i8 and i16 which are illegal scalar but legal
7256 // vector element types. After type-legalization the inserted value is
7257 // extended (i32) and it is safe to cast them to the vector type by ignoring
7258 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7259 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007260 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007261 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007262 ++i;
7263 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007264 LLVM_DEBUG(if (i < NumElts) dbgs()
7265 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007266 for (; i < NumElts; ++i) {
7267 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007268 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007269 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007270 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007271 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7272 }
7273 return Vec;
7274 }
7275
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007276 LLVM_DEBUG(
7277 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7278 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007279 return SDValue();
7280}
7281
7282SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7283 SelectionDAG &DAG) const {
7284 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7285
Tim Northovere4b8e132014-07-15 10:00:26 +00007286 // Check for non-constant or out of range lane.
7287 EVT VT = Op.getOperand(0).getValueType();
7288 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7289 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007290 return SDValue();
7291
Tim Northover3b0846e2014-05-24 12:50:23 +00007292
7293 // Insertion/extraction are legal for V128 types.
7294 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007295 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7296 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007297 return Op;
7298
7299 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007300 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007301 return SDValue();
7302
7303 // For V64 types, we perform insertion by expanding the value
7304 // to a V128 type and perform the insertion on that.
7305 SDLoc DL(Op);
7306 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7307 EVT WideTy = WideVec.getValueType();
7308
7309 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7310 Op.getOperand(1), Op.getOperand(2));
7311 // Re-narrow the resultant vector.
7312 return NarrowVector(Node, DAG);
7313}
7314
7315SDValue
7316AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7317 SelectionDAG &DAG) const {
7318 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7319
Tim Northovere4b8e132014-07-15 10:00:26 +00007320 // Check for non-constant or out of range lane.
7321 EVT VT = Op.getOperand(0).getValueType();
7322 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7323 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007324 return SDValue();
7325
Tim Northover3b0846e2014-05-24 12:50:23 +00007326
7327 // Insertion/extraction are legal for V128 types.
7328 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007329 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7330 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007331 return Op;
7332
7333 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007334 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007335 return SDValue();
7336
7337 // For V64 types, we perform extraction by expanding the value
7338 // to a V128 type and perform the extraction on that.
7339 SDLoc DL(Op);
7340 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7341 EVT WideTy = WideVec.getValueType();
7342
7343 EVT ExtrTy = WideTy.getVectorElementType();
7344 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7345 ExtrTy = MVT::i32;
7346
7347 // For extractions, we just return the result directly.
7348 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7349 Op.getOperand(1));
7350}
7351
7352SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7353 SelectionDAG &DAG) const {
7354 EVT VT = Op.getOperand(0).getValueType();
7355 SDLoc dl(Op);
7356 // Just in case...
7357 if (!VT.isVector())
7358 return SDValue();
7359
7360 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7361 if (!Cst)
7362 return SDValue();
7363 unsigned Val = Cst->getZExtValue();
7364
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007365 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007366
7367 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7368 if (Val == 0)
7369 return Op;
7370
Tim Northover3b0846e2014-05-24 12:50:23 +00007371 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7372 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007373 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007374 return Op;
7375
7376 return SDValue();
7377}
7378
Zvi Rackover1b736822017-07-26 08:06:58 +00007379bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007380 if (VT.getVectorNumElements() == 4 &&
7381 (VT.is128BitVector() || VT.is64BitVector())) {
7382 unsigned PFIndexes[4];
7383 for (unsigned i = 0; i != 4; ++i) {
7384 if (M[i] < 0)
7385 PFIndexes[i] = 8;
7386 else
7387 PFIndexes[i] = M[i];
7388 }
7389
7390 // Compute the index in the perfect shuffle table.
7391 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7392 PFIndexes[2] * 9 + PFIndexes[3];
7393 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7394 unsigned Cost = (PFEntry >> 30);
7395
7396 if (Cost <= 4)
7397 return true;
7398 }
7399
7400 bool DummyBool;
7401 int DummyInt;
7402 unsigned DummyUnsigned;
7403
7404 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7405 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7406 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7407 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7408 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7409 isZIPMask(M, VT, DummyUnsigned) ||
7410 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7411 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7412 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7413 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7414 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7415}
7416
7417/// getVShiftImm - Check if this is a valid build_vector for the immediate
7418/// operand of a vector shift operation, where all the elements of the
7419/// build_vector must have the same constant integer value.
7420static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7421 // Ignore bit_converts.
7422 while (Op.getOpcode() == ISD::BITCAST)
7423 Op = Op.getOperand(0);
7424 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7425 APInt SplatBits, SplatUndef;
7426 unsigned SplatBitSize;
7427 bool HasAnyUndefs;
7428 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7429 HasAnyUndefs, ElementBits) ||
7430 SplatBitSize > ElementBits)
7431 return false;
7432 Cnt = SplatBits.getSExtValue();
7433 return true;
7434}
7435
7436/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7437/// operand of a vector shift left operation. That value must be in the range:
7438/// 0 <= Value < ElementBits for a left shift; or
7439/// 0 <= Value <= ElementBits for a long left shift.
7440static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7441 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007442 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007443 if (!getVShiftImm(Op, ElementBits, Cnt))
7444 return false;
7445 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7446}
7447
7448/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007449/// operand of a vector shift right operation. The value must be in the range:
7450/// 1 <= Value <= ElementBits for a right shift; or
7451static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007452 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007453 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007454 if (!getVShiftImm(Op, ElementBits, Cnt))
7455 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007456 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7457}
7458
7459SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7460 SelectionDAG &DAG) const {
7461 EVT VT = Op.getValueType();
7462 SDLoc DL(Op);
7463 int64_t Cnt;
7464
7465 if (!Op.getOperand(1).getValueType().isVector())
7466 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007467 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007468
7469 switch (Op.getOpcode()) {
7470 default:
7471 llvm_unreachable("unexpected shift opcode");
7472
7473 case ISD::SHL:
7474 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007475 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7476 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007477 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007478 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7479 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007480 Op.getOperand(0), Op.getOperand(1));
7481 case ISD::SRA:
7482 case ISD::SRL:
7483 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007484 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007485 unsigned Opc =
7486 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007487 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7488 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007489 }
7490
7491 // Right shift register. Note, there is not a shift right register
7492 // instruction, but the shift left register instruction takes a signed
7493 // value, where negative numbers specify a right shift.
7494 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7495 : Intrinsic::aarch64_neon_ushl;
7496 // negate the shift amount
7497 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7498 SDValue NegShiftLeft =
7499 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007500 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7501 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007502 return NegShiftLeft;
7503 }
7504
7505 return SDValue();
7506}
7507
7508static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7509 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007510 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007511 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007512 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7513 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007514
7515 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7516 APInt CnstBits(VT.getSizeInBits(), 0);
7517 APInt UndefBits(VT.getSizeInBits(), 0);
7518 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7519 bool IsZero = IsCnst && (CnstBits == 0);
7520
7521 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7522 switch (CC) {
7523 default:
7524 return SDValue();
7525 case AArch64CC::NE: {
7526 SDValue Fcmeq;
7527 if (IsZero)
7528 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7529 else
7530 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7531 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7532 }
7533 case AArch64CC::EQ:
7534 if (IsZero)
7535 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7536 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7537 case AArch64CC::GE:
7538 if (IsZero)
7539 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7540 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7541 case AArch64CC::GT:
7542 if (IsZero)
7543 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7544 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7545 case AArch64CC::LS:
7546 if (IsZero)
7547 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7548 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7549 case AArch64CC::LT:
7550 if (!NoNans)
7551 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007552 // If we ignore NaNs then we can use to the MI implementation.
7553 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007554 case AArch64CC::MI:
7555 if (IsZero)
7556 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7557 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7558 }
7559 }
7560
7561 switch (CC) {
7562 default:
7563 return SDValue();
7564 case AArch64CC::NE: {
7565 SDValue Cmeq;
7566 if (IsZero)
7567 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7568 else
7569 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7570 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7571 }
7572 case AArch64CC::EQ:
7573 if (IsZero)
7574 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7575 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7576 case AArch64CC::GE:
7577 if (IsZero)
7578 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7579 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7580 case AArch64CC::GT:
7581 if (IsZero)
7582 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7583 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7584 case AArch64CC::LE:
7585 if (IsZero)
7586 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7587 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7588 case AArch64CC::LS:
7589 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7590 case AArch64CC::LO:
7591 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7592 case AArch64CC::LT:
7593 if (IsZero)
7594 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7595 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7596 case AArch64CC::HI:
7597 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7598 case AArch64CC::HS:
7599 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7600 }
7601}
7602
7603SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7604 SelectionDAG &DAG) const {
7605 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7606 SDValue LHS = Op.getOperand(0);
7607 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007608 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007609 SDLoc dl(Op);
7610
7611 if (LHS.getValueType().getVectorElementType().isInteger()) {
7612 assert(LHS.getValueType() == RHS.getValueType());
7613 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007614 SDValue Cmp =
7615 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7616 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007617 }
7618
Carey Williamsda15b5b2018-01-22 14:16:11 +00007619 const bool FullFP16 =
7620 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7621
7622 // Make v4f16 (only) fcmp operations utilise vector instructions
7623 // v8f16 support will be a litle more complicated
7624 if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7625 if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7626 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7627 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7628 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7629 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7630 CmpVT = MVT::v4i32;
7631 } else
7632 return SDValue();
7633 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007634
Tim Northover3b0846e2014-05-24 12:50:23 +00007635 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7636 LHS.getValueType().getVectorElementType() == MVT::f64);
7637
7638 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7639 // clean. Some of them require two branches to implement.
7640 AArch64CC::CondCode CC1, CC2;
7641 bool ShouldInvert;
7642 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7643
7644 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7645 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007646 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007647 if (!Cmp.getNode())
7648 return SDValue();
7649
7650 if (CC2 != AArch64CC::AL) {
7651 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007652 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007653 if (!Cmp2.getNode())
7654 return SDValue();
7655
Tim Northover45aa89c2015-02-08 00:50:47 +00007656 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007657 }
7658
Tim Northover45aa89c2015-02-08 00:50:47 +00007659 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7660
Tim Northover3b0846e2014-05-24 12:50:23 +00007661 if (ShouldInvert)
7662 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7663
7664 return Cmp;
7665}
7666
Amara Emersonc9916d72017-05-16 21:29:22 +00007667static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7668 SelectionDAG &DAG) {
7669 SDValue VecOp = ScalarOp.getOperand(0);
7670 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7671 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7672 DAG.getConstant(0, DL, MVT::i64));
7673}
7674
7675SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7676 SelectionDAG &DAG) const {
7677 SDLoc dl(Op);
7678 switch (Op.getOpcode()) {
7679 case ISD::VECREDUCE_ADD:
7680 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7681 case ISD::VECREDUCE_SMAX:
7682 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7683 case ISD::VECREDUCE_SMIN:
7684 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7685 case ISD::VECREDUCE_UMAX:
7686 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7687 case ISD::VECREDUCE_UMIN:
7688 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7689 case ISD::VECREDUCE_FMAX: {
7690 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7691 return DAG.getNode(
7692 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7693 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7694 Op.getOperand(0));
7695 }
7696 case ISD::VECREDUCE_FMIN: {
7697 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7698 return DAG.getNode(
7699 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7700 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7701 Op.getOperand(0));
7702 }
7703 default:
7704 llvm_unreachable("Unhandled reduction");
7705 }
7706}
7707
Oliver Stannard42699172018-02-12 14:22:03 +00007708SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7709 SelectionDAG &DAG) const {
7710 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7711 if (!Subtarget.hasLSE())
7712 return SDValue();
7713
7714 // LSE has an atomic load-add instruction, but not a load-sub.
7715 SDLoc dl(Op);
7716 MVT VT = Op.getSimpleValueType();
7717 SDValue RHS = Op.getOperand(2);
7718 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7719 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7720 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7721 Op.getOperand(0), Op.getOperand(1), RHS,
7722 AN->getMemOperand());
7723}
7724
Oliver Stannard02f08c92018-02-12 17:03:11 +00007725SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7726 SelectionDAG &DAG) const {
7727 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7728 if (!Subtarget.hasLSE())
7729 return SDValue();
7730
7731 // LSE has an atomic load-clear instruction, but not a load-and.
7732 SDLoc dl(Op);
7733 MVT VT = Op.getSimpleValueType();
7734 SDValue RHS = Op.getOperand(2);
7735 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7736 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7737 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7738 Op.getOperand(0), Op.getOperand(1), RHS,
7739 AN->getMemOperand());
7740}
7741
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007742SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7743 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7744 SDLoc dl(Op);
7745 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7746 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7747
7748 const uint32_t *Mask =
7749 Subtarget->getRegisterInfo()->getWindowsStackProbePreservedMask();
7750
7751 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7752 DAG.getConstant(4, dl, MVT::i64));
7753 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7754 Chain =
7755 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7756 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7757 DAG.getRegisterMask(Mask), Chain.getValue(1));
7758 // To match the actual intent better, we should read the output from X15 here
7759 // again (instead of potentially spilling it to the stack), but rereading Size
7760 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7761 // here.
7762
7763 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7764 DAG.getConstant(4, dl, MVT::i64));
7765 return Chain;
7766}
7767
7768SDValue
7769AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7770 SelectionDAG &DAG) const {
7771 assert(Subtarget->isTargetWindows() &&
7772 "Only Windows alloca probing supported");
7773 SDLoc dl(Op);
7774 // Get the inputs.
7775 SDNode *Node = Op.getNode();
7776 SDValue Chain = Op.getOperand(0);
7777 SDValue Size = Op.getOperand(1);
7778 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7779 EVT VT = Node->getValueType(0);
7780
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007781 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7782 "no-stack-arg-probe")) {
7783 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7784 Chain = SP.getValue(1);
7785 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7786 if (Align)
7787 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7788 DAG.getConstant(-(uint64_t)Align, dl, VT));
7789 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7790 SDValue Ops[2] = {SP, Chain};
7791 return DAG.getMergeValues(Ops, dl);
7792 }
7793
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007794 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7795
7796 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7797
7798 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7799 Chain = SP.getValue(1);
7800 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00007801 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007802 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7803 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00007804 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007805
7806 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7807 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7808
7809 SDValue Ops[2] = {SP, Chain};
7810 return DAG.getMergeValues(Ops, dl);
7811}
7812
Tim Northover3b0846e2014-05-24 12:50:23 +00007813/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7814/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7815/// specified in the intrinsic calls.
7816bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7817 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00007818 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00007819 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007820 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007821 switch (Intrinsic) {
7822 case Intrinsic::aarch64_neon_ld2:
7823 case Intrinsic::aarch64_neon_ld3:
7824 case Intrinsic::aarch64_neon_ld4:
7825 case Intrinsic::aarch64_neon_ld1x2:
7826 case Intrinsic::aarch64_neon_ld1x3:
7827 case Intrinsic::aarch64_neon_ld1x4:
7828 case Intrinsic::aarch64_neon_ld2lane:
7829 case Intrinsic::aarch64_neon_ld3lane:
7830 case Intrinsic::aarch64_neon_ld4lane:
7831 case Intrinsic::aarch64_neon_ld2r:
7832 case Intrinsic::aarch64_neon_ld3r:
7833 case Intrinsic::aarch64_neon_ld4r: {
7834 Info.opc = ISD::INTRINSIC_W_CHAIN;
7835 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007836 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007837 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7838 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7839 Info.offset = 0;
7840 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00007841 // volatile loads with NEON intrinsics not supported
7842 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00007843 return true;
7844 }
7845 case Intrinsic::aarch64_neon_st2:
7846 case Intrinsic::aarch64_neon_st3:
7847 case Intrinsic::aarch64_neon_st4:
7848 case Intrinsic::aarch64_neon_st1x2:
7849 case Intrinsic::aarch64_neon_st1x3:
7850 case Intrinsic::aarch64_neon_st1x4:
7851 case Intrinsic::aarch64_neon_st2lane:
7852 case Intrinsic::aarch64_neon_st3lane:
7853 case Intrinsic::aarch64_neon_st4lane: {
7854 Info.opc = ISD::INTRINSIC_VOID;
7855 // Conservatively set memVT to the entire set of vectors stored.
7856 unsigned NumElts = 0;
7857 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7858 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7859 if (!ArgTy->isVectorTy())
7860 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007861 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007862 }
7863 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7864 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7865 Info.offset = 0;
7866 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00007867 // volatile stores with NEON intrinsics not supported
7868 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00007869 return true;
7870 }
7871 case Intrinsic::aarch64_ldaxr:
7872 case Intrinsic::aarch64_ldxr: {
7873 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7874 Info.opc = ISD::INTRINSIC_W_CHAIN;
7875 Info.memVT = MVT::getVT(PtrTy->getElementType());
7876 Info.ptrVal = I.getArgOperand(0);
7877 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007878 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00007879 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007880 return true;
7881 }
7882 case Intrinsic::aarch64_stlxr:
7883 case Intrinsic::aarch64_stxr: {
7884 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7885 Info.opc = ISD::INTRINSIC_W_CHAIN;
7886 Info.memVT = MVT::getVT(PtrTy->getElementType());
7887 Info.ptrVal = I.getArgOperand(1);
7888 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007889 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00007890 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007891 return true;
7892 }
7893 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007894 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007895 Info.opc = ISD::INTRINSIC_W_CHAIN;
7896 Info.memVT = MVT::i128;
7897 Info.ptrVal = I.getArgOperand(0);
7898 Info.offset = 0;
7899 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00007900 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007901 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007902 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007903 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007904 Info.opc = ISD::INTRINSIC_W_CHAIN;
7905 Info.memVT = MVT::i128;
7906 Info.ptrVal = I.getArgOperand(2);
7907 Info.offset = 0;
7908 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00007909 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007910 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007911 default:
7912 break;
7913 }
7914
7915 return false;
7916}
7917
John Brawne3b44f92018-03-23 14:47:07 +00007918bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
7919 ISD::LoadExtType ExtTy,
7920 EVT NewVT) const {
7921 // If we're reducing the load width in order to avoid having to use an extra
7922 // instruction to do extension then it's probably a good idea.
7923 if (ExtTy != ISD::NON_EXTLOAD)
7924 return true;
7925 // Don't reduce load width if it would prevent us from combining a shift into
7926 // the offset.
7927 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
7928 assert(Mem);
7929 const SDValue &Base = Mem->getBasePtr();
7930 if (Base.getOpcode() == ISD::ADD &&
7931 Base.getOperand(1).getOpcode() == ISD::SHL &&
7932 Base.getOperand(1).hasOneUse() &&
7933 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
7934 // The shift can be combined if it matches the size of the value being
7935 // loaded (and so reducing the width would make it not match).
7936 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
7937 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
7938 if (ShiftAmount == Log2_32(LoadBytes))
7939 return false;
7940 }
7941 // We have no reason to disallow reducing the load width, so allow it.
7942 return true;
7943}
7944
Tim Northover3b0846e2014-05-24 12:50:23 +00007945// Truncations from 64-bit GPR to 32-bit GPR is free.
7946bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7947 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7948 return false;
7949 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7950 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007951 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007952}
7953bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007954 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007955 return false;
7956 unsigned NumBits1 = VT1.getSizeInBits();
7957 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007958 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007959}
7960
Chad Rosier54390052015-02-23 19:15:16 +00007961/// Check if it is profitable to hoist instruction in then/else to if.
7962/// Not profitable if I and it's user can form a FMA instruction
7963/// because we prefer FMSUB/FMADD.
7964bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7965 if (I->getOpcode() != Instruction::FMul)
7966 return true;
7967
Davide Italiano3e9986f2017-04-18 00:29:54 +00007968 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00007969 return true;
7970
7971 Instruction *User = I->user_back();
7972
7973 if (User &&
7974 !(User->getOpcode() == Instruction::FSub ||
7975 User->getOpcode() == Instruction::FAdd))
7976 return true;
7977
7978 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007979 const DataLayout &DL = I->getModule()->getDataLayout();
7980 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007981
Eric Christopher114fa1c2016-02-29 22:50:49 +00007982 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7983 isOperationLegalOrCustom(ISD::FMA, VT) &&
7984 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7985 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007986}
7987
Tim Northover3b0846e2014-05-24 12:50:23 +00007988// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7989// 64-bit GPR.
7990bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7991 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7992 return false;
7993 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7994 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007995 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007996}
7997bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007998 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007999 return false;
8000 unsigned NumBits1 = VT1.getSizeInBits();
8001 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008002 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008003}
8004
8005bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8006 EVT VT1 = Val.getValueType();
8007 if (isZExtFree(VT1, VT2)) {
8008 return true;
8009 }
8010
8011 if (Val.getOpcode() != ISD::LOAD)
8012 return false;
8013
8014 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008015 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8016 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8017 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008018}
8019
Quentin Colombet6843ac42015-03-31 20:52:32 +00008020bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8021 if (isa<FPExtInst>(Ext))
8022 return false;
8023
Haicheng Wu50692a22017-08-01 21:26:45 +00008024 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008025 if (Ext->getType()->isVectorTy())
8026 return false;
8027
8028 for (const Use &U : Ext->uses()) {
8029 // The extension is free if we can fold it with a left shift in an
8030 // addressing mode or an arithmetic operation: add, sub, and cmp.
8031
8032 // Is there a shift?
8033 const Instruction *Instr = cast<Instruction>(U.getUser());
8034
8035 // Is this a constant shift?
8036 switch (Instr->getOpcode()) {
8037 case Instruction::Shl:
8038 if (!isa<ConstantInt>(Instr->getOperand(1)))
8039 return false;
8040 break;
8041 case Instruction::GetElementPtr: {
8042 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008043 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008044 std::advance(GTI, U.getOperandNo()-1);
8045 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008046 // This extension will end up with a shift because of the scaling factor.
8047 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8048 // Get the shift amount based on the scaling factor:
8049 // log2(sizeof(IdxTy)) - log2(8).
8050 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008051 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008052 // Is the constant foldable in the shift of the addressing mode?
8053 // I.e., shift amount is between 1 and 4 inclusive.
8054 if (ShiftAmt == 0 || ShiftAmt > 4)
8055 return false;
8056 break;
8057 }
8058 case Instruction::Trunc:
8059 // Check if this is a noop.
8060 // trunc(sext ty1 to ty2) to ty1.
8061 if (Instr->getType() == Ext->getOperand(0)->getType())
8062 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008063 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008064 default:
8065 return false;
8066 }
8067
8068 // At this point we can use the bfm family, so this extension is free
8069 // for that use.
8070 }
8071 return true;
8072}
8073
Tim Northover3b0846e2014-05-24 12:50:23 +00008074bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8075 unsigned &RequiredAligment) const {
8076 if (!LoadedType.isSimple() ||
8077 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8078 return false;
8079 // Cyclone supports unaligned accesses.
8080 RequiredAligment = 0;
8081 unsigned NumBits = LoadedType.getSizeInBits();
8082 return NumBits == 32 || NumBits == 64;
8083}
8084
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008085/// A helper function for determining the number of interleaved accesses we
8086/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008087unsigned
8088AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8089 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008090 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8091}
8092
Geoff Berryb1e87142017-07-14 21:44:12 +00008093MachineMemOperand::Flags
8094AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8095 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8096 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8097 return MOStridedAccess;
8098 return MachineMemOperand::MONone;
8099}
8100
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008101bool AArch64TargetLowering::isLegalInterleavedAccessType(
8102 VectorType *VecTy, const DataLayout &DL) const {
8103
8104 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8105 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8106
8107 // Ensure the number of vector elements is greater than 1.
8108 if (VecTy->getNumElements() < 2)
8109 return false;
8110
8111 // Ensure the element type is legal.
8112 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8113 return false;
8114
8115 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8116 // 128 will be split into multiple interleaved accesses.
8117 return VecSize == 64 || VecSize % 128 == 0;
8118}
8119
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008120/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008121///
8122/// E.g. Lower an interleaved load (Factor = 2):
8123/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8124/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8125/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8126///
8127/// Into:
8128/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8129/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8130/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8131bool AArch64TargetLowering::lowerInterleavedLoad(
8132 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8133 ArrayRef<unsigned> Indices, unsigned Factor) const {
8134 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8135 "Invalid interleave factor");
8136 assert(!Shuffles.empty() && "Empty shufflevector input");
8137 assert(Shuffles.size() == Indices.size() &&
8138 "Unmatched number of shufflevectors and indices");
8139
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008140 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008141
8142 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008143
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008144 // Skip if we do not have NEON and skip illegal vector types. We can
8145 // "legalize" wide vector types into multiple interleaved accesses as long as
8146 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008147 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008148 return false;
8149
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008150 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8151
Hao Liu7ec8ee32015-06-26 02:32:07 +00008152 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8153 // load integer vectors first and then convert to pointer vectors.
8154 Type *EltTy = VecTy->getVectorElementType();
8155 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008156 VecTy =
8157 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008158
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008159 IRBuilder<> Builder(LI);
8160
8161 // The base address of the load.
8162 Value *BaseAddr = LI->getPointerOperand();
8163
8164 if (NumLoads > 1) {
8165 // If we're going to generate more than one load, reset the sub-vector type
8166 // to something legal.
8167 VecTy = VectorType::get(VecTy->getVectorElementType(),
8168 VecTy->getVectorNumElements() / NumLoads);
8169
8170 // We will compute the pointer operand of each load from the original base
8171 // address using GEPs. Cast the base address to a pointer to the scalar
8172 // element type.
8173 BaseAddr = Builder.CreateBitCast(
8174 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8175 LI->getPointerAddressSpace()));
8176 }
8177
Hao Liu7ec8ee32015-06-26 02:32:07 +00008178 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8179 Type *Tys[2] = {VecTy, PtrTy};
8180 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8181 Intrinsic::aarch64_neon_ld3,
8182 Intrinsic::aarch64_neon_ld4};
8183 Function *LdNFunc =
8184 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8185
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008186 // Holds sub-vectors extracted from the load intrinsic return values. The
8187 // sub-vectors are associated with the shufflevector instructions they will
8188 // replace.
8189 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008190
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008191 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008192
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008193 // If we're generating more than one load, compute the base address of
8194 // subsequent loads as an offset from the previous.
8195 if (LoadCount > 0)
8196 BaseAddr = Builder.CreateConstGEP1_32(
8197 BaseAddr, VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008198
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008199 CallInst *LdN = Builder.CreateCall(
8200 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008201
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008202 // Extract and store the sub-vectors returned by the load intrinsic.
8203 for (unsigned i = 0; i < Shuffles.size(); i++) {
8204 ShuffleVectorInst *SVI = Shuffles[i];
8205 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008206
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008207 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8208
8209 // Convert the integer vector to pointer vector if the element is pointer.
8210 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008211 SubVec = Builder.CreateIntToPtr(
8212 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8213 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008214 SubVecs[SVI].push_back(SubVec);
8215 }
8216 }
8217
8218 // Replace uses of the shufflevector instructions with the sub-vectors
8219 // returned by the load intrinsic. If a shufflevector instruction is
8220 // associated with more than one sub-vector, those sub-vectors will be
8221 // concatenated into a single wide vector.
8222 for (ShuffleVectorInst *SVI : Shuffles) {
8223 auto &SubVec = SubVecs[SVI];
8224 auto *WideVec =
8225 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8226 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008227 }
8228
8229 return true;
8230}
8231
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008232/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008233///
8234/// E.g. Lower an interleaved store (Factor = 3):
8235/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008236/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008237/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8238///
8239/// Into:
8240/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8241/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8242/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8243/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8244///
8245/// Note that the new shufflevectors will be removed and we'll only generate one
8246/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008247///
8248/// Example for a more general valid mask (Factor 3). Lower:
8249/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8250/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8251/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8252///
8253/// Into:
8254/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8255/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8256/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8257/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008258bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8259 ShuffleVectorInst *SVI,
8260 unsigned Factor) const {
8261 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8262 "Invalid interleave factor");
8263
8264 VectorType *VecTy = SVI->getType();
8265 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8266 "Invalid interleaved store");
8267
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008268 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008269 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008270 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008271
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008272 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008273
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008274 // Skip if we do not have NEON and skip illegal vector types. We can
8275 // "legalize" wide vector types into multiple interleaved accesses as long as
8276 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008277 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008278 return false;
8279
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008280 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8281
Hao Liu7ec8ee32015-06-26 02:32:07 +00008282 Value *Op0 = SVI->getOperand(0);
8283 Value *Op1 = SVI->getOperand(1);
8284 IRBuilder<> Builder(SI);
8285
8286 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8287 // vectors to integer vectors.
8288 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008289 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008290 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008291
8292 // Convert to the corresponding integer vector.
8293 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8294 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8295 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8296
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008297 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008298 }
8299
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008300 // The base address of the store.
8301 Value *BaseAddr = SI->getPointerOperand();
8302
8303 if (NumStores > 1) {
8304 // If we're going to generate more than one store, reset the lane length
8305 // and sub-vector type to something legal.
8306 LaneLen /= NumStores;
8307 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8308
8309 // We will compute the pointer operand of each store from the original base
8310 // address using GEPs. Cast the base address to a pointer to the scalar
8311 // element type.
8312 BaseAddr = Builder.CreateBitCast(
8313 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8314 SI->getPointerAddressSpace()));
8315 }
8316
8317 auto Mask = SVI->getShuffleMask();
8318
Hao Liu7ec8ee32015-06-26 02:32:07 +00008319 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8320 Type *Tys[2] = {SubVecTy, PtrTy};
8321 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8322 Intrinsic::aarch64_neon_st3,
8323 Intrinsic::aarch64_neon_st4};
8324 Function *StNFunc =
8325 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8326
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008327 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008328
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008329 SmallVector<Value *, 5> Ops;
8330
8331 // Split the shufflevector operands into sub vectors for the new stN call.
8332 for (unsigned i = 0; i < Factor; i++) {
8333 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8334 if (Mask[IdxI] >= 0) {
8335 Ops.push_back(Builder.CreateShuffleVector(
8336 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8337 } else {
8338 unsigned StartMask = 0;
8339 for (unsigned j = 1; j < LaneLen; j++) {
8340 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8341 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8342 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8343 break;
8344 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008345 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008346 // Note: Filling undef gaps with random elements is ok, since
8347 // those elements were being written anyway (with undefs).
8348 // In the case of all undefs we're defaulting to using elems from 0
8349 // Note: StartMask cannot be negative, it's checked in
8350 // isReInterleaveMask
8351 Ops.push_back(Builder.CreateShuffleVector(
8352 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008353 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008354 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008355
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008356 // If we generating more than one store, we compute the base address of
8357 // subsequent stores as an offset from the previous.
8358 if (StoreCount > 0)
8359 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
8360
8361 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8362 Builder.CreateCall(StNFunc, Ops);
8363 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008364 return true;
8365}
8366
Tim Northover3b0846e2014-05-24 12:50:23 +00008367static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8368 unsigned AlignCheck) {
8369 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8370 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8371}
8372
8373EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8374 unsigned SrcAlign, bool IsMemset,
8375 bool ZeroMemset,
8376 bool MemcpyStrSrc,
8377 MachineFunction &MF) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008378 const Function &F = MF.getFunction();
JF Bastien29200612018-09-06 16:03:32 +00008379 bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8380 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8381 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8382 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8383 // taken one instruction to materialize the v2i64 zero and one store (with
8384 // restrictive addressing mode). Just do i64 stores.
8385 bool IsSmallMemset = IsMemset && Size < 32;
8386 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8387 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8388 return true;
8389 bool Fast;
8390 return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8391 };
8392
8393 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8394 AlignmentIsAcceptable(MVT::v2i64, 16))
8395 return MVT::v2i64;
8396 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008397 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008398 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008399 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008400 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008401 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008402 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008403}
8404
8405// 12-bit optionally shifted immediates are legal for adds.
8406bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008407 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008408 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8409 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008410 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008411 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008412 // Same encoding for add/sub, just flip the sign.
8413 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008414 bool IsLegal = ((Immed >> 12) == 0 ||
8415 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008416 LLVM_DEBUG(dbgs() << "Is " << Immed
8417 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008418 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008419}
8420
8421// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8422// immediates is the same as for an add or a sub.
8423bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008424 return isLegalAddImmediate(Immed);
8425}
8426
8427/// isLegalAddressingMode - Return true if the addressing mode represented
8428/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008429bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8430 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008431 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008432 // AArch64 has five basic addressing modes:
8433 // reg
8434 // reg + 9-bit signed offset
8435 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8436 // reg1 + reg2
8437 // reg + SIZE_IN_BYTES * reg
8438
8439 // No global is ever allowed as a base.
8440 if (AM.BaseGV)
8441 return false;
8442
8443 // No reg+reg+imm addressing.
8444 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8445 return false;
8446
8447 // check reg + imm case:
8448 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8449 uint64_t NumBytes = 0;
8450 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008451 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008452 NumBytes = NumBits / 8;
8453 if (!isPowerOf2_64(NumBits))
8454 NumBytes = 0;
8455 }
8456
8457 if (!AM.Scale) {
8458 int64_t Offset = AM.BaseOffs;
8459
8460 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008461 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008462 return true;
8463
8464 // 12-bit unsigned offset
8465 unsigned shift = Log2_64(NumBytes);
8466 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8467 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8468 (Offset >> shift) << shift == Offset)
8469 return true;
8470 return false;
8471 }
8472
8473 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8474
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008475 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008476}
8477
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008478bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8479 // Consider splitting large offset of struct or array.
8480 return true;
8481}
8482
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008483int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8484 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008485 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008486 // Scaling factors are not free at all.
8487 // Operands | Rt Latency
8488 // -------------------------------------------
8489 // Rt, [Xn, Xm] | 4
8490 // -------------------------------------------
8491 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8492 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008493 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008494 // Scale represents reg2 * scale, thus account for 1 if
8495 // it is not equal to 0 or 1.
8496 return AM.Scale != 0 && AM.Scale != 1;
8497 return -1;
8498}
8499
8500bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8501 VT = VT.getScalarType();
8502
8503 if (!VT.isSimple())
8504 return false;
8505
8506 switch (VT.getSimpleVT().SimpleTy) {
8507 case MVT::f32:
8508 case MVT::f64:
8509 return true;
8510 default:
8511 break;
8512 }
8513
8514 return false;
8515}
8516
8517const MCPhysReg *
8518AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8519 // LR is a callee-save register, but we must treat it as clobbered by any call
8520 // site. Hence we include LR in the scratch registers, which are in turn added
8521 // as implicit-defs for stackmaps and patchpoints.
8522 static const MCPhysReg ScratchRegs[] = {
8523 AArch64::X16, AArch64::X17, AArch64::LR, 0
8524 };
8525 return ScratchRegs;
8526}
8527
8528bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008529AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8530 CombineLevel Level) const {
8531 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008532 EVT VT = N->getValueType(0);
8533 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8534 // it with shift to let it be lowered to UBFX.
8535 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8536 isa<ConstantSDNode>(N->getOperand(1))) {
8537 uint64_t TruncMask = N->getConstantOperandVal(1);
8538 if (isMask_64(TruncMask) &&
8539 N->getOperand(0).getOpcode() == ISD::SRL &&
8540 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8541 return false;
8542 }
8543 return true;
8544}
8545
8546bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8547 Type *Ty) const {
8548 assert(Ty->isIntegerTy());
8549
8550 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8551 if (BitSize == 0)
8552 return false;
8553
8554 int64_t Val = Imm.getSExtValue();
8555 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8556 return true;
8557
8558 if ((int64_t)Val < 0)
8559 Val = ~Val;
8560 if (BitSize == 32)
8561 Val &= (1LL << 32) - 1;
8562
8563 unsigned LZ = countLeadingZeros((uint64_t)Val);
8564 unsigned Shift = (63 - LZ) / 16;
8565 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008566 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008567}
8568
Sebastian Pop41073e82018-03-06 16:54:55 +00008569bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8570 unsigned Index) const {
8571 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8572 return false;
8573
8574 return (Index == 0 || Index == ResVT.getVectorNumElements());
8575}
8576
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008577/// Turn vector tests of the signbit in the form of:
8578/// xor (sra X, elt_size(X)-1), -1
8579/// into:
8580/// cmge X, X, #0
8581static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8582 const AArch64Subtarget *Subtarget) {
8583 EVT VT = N->getValueType(0);
8584 if (!Subtarget->hasNEON() || !VT.isVector())
8585 return SDValue();
8586
8587 // There must be a shift right algebraic before the xor, and the xor must be a
8588 // 'not' operation.
8589 SDValue Shift = N->getOperand(0);
8590 SDValue Ones = N->getOperand(1);
8591 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8592 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8593 return SDValue();
8594
8595 // The shift should be smearing the sign bit across each vector element.
8596 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8597 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8598 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8599 return SDValue();
8600
8601 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8602}
8603
Tim Northover3b0846e2014-05-24 12:50:23 +00008604// Generate SUBS and CSEL for integer abs.
8605static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8606 EVT VT = N->getValueType(0);
8607
8608 SDValue N0 = N->getOperand(0);
8609 SDValue N1 = N->getOperand(1);
8610 SDLoc DL(N);
8611
8612 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8613 // and change it to SUB and CSEL.
8614 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8615 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8616 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8617 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8618 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008619 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008620 N0.getOperand(0));
8621 // Generate SUBS & CSEL.
8622 SDValue Cmp =
8623 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008624 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008625 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008626 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008627 SDValue(Cmp.getNode(), 1));
8628 }
8629 return SDValue();
8630}
8631
Tim Northover3b0846e2014-05-24 12:50:23 +00008632static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8633 TargetLowering::DAGCombinerInfo &DCI,
8634 const AArch64Subtarget *Subtarget) {
8635 if (DCI.isBeforeLegalizeOps())
8636 return SDValue();
8637
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008638 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8639 return Cmp;
8640
Tim Northover3b0846e2014-05-24 12:50:23 +00008641 return performIntegerAbsCombine(N, DAG);
8642}
8643
Chad Rosier17020f92014-07-23 14:57:52 +00008644SDValue
8645AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8646 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008647 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008648 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008649 if (isIntDivCheap(N->getValueType(0), Attr))
8650 return SDValue(N,0); // Lower SDIV as SDIV
8651
Chad Rosier17020f92014-07-23 14:57:52 +00008652 // fold (sdiv X, pow2)
8653 EVT VT = N->getValueType(0);
8654 if ((VT != MVT::i32 && VT != MVT::i64) ||
8655 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8656 return SDValue();
8657
8658 SDLoc DL(N);
8659 SDValue N0 = N->getOperand(0);
8660 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008661 SDValue Zero = DAG.getConstant(0, DL, VT);
8662 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008663
8664 // Add (N0 < 0) ? Pow2 - 1 : 0;
8665 SDValue CCVal;
8666 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8667 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8668 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8669
Craig Toppera568a272018-07-30 21:04:34 +00008670 Created.push_back(Cmp.getNode());
8671 Created.push_back(Add.getNode());
8672 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00008673
8674 // Divide by pow2.
8675 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008676 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008677
8678 // If we're dividing by a positive value, we're done. Otherwise, we must
8679 // negate the result.
8680 if (Divisor.isNonNegative())
8681 return SRA;
8682
Craig Toppera568a272018-07-30 21:04:34 +00008683 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008684 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008685}
8686
Tim Northover3b0846e2014-05-24 12:50:23 +00008687static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8688 TargetLowering::DAGCombinerInfo &DCI,
8689 const AArch64Subtarget *Subtarget) {
8690 if (DCI.isBeforeLegalizeOps())
8691 return SDValue();
8692
Chad Rosier31ee8132016-11-11 17:07:37 +00008693 // The below optimizations require a constant RHS.
8694 if (!isa<ConstantSDNode>(N->getOperand(1)))
8695 return SDValue();
8696
8697 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8698 const APInt &ConstValue = C->getAPIntValue();
8699
Tim Northover3b0846e2014-05-24 12:50:23 +00008700 // Multiplication of a power of two plus/minus one can be done more
8701 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8702 // future CPUs have a cheaper MADD instruction, this may need to be
8703 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8704 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008705 // More aggressively, some multiplications N0 * C can be lowered to
8706 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8707 // e.g. 6=3*2=(2+1)*2.
8708 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8709 // which equals to (1+2)*16-(1+2).
8710 SDValue N0 = N->getOperand(0);
8711 // TrailingZeroes is used to test if the mul can be lowered to
8712 // shift+add+shift.
8713 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8714 if (TrailingZeroes) {
8715 // Conservatively do not lower to shift+add+shift if the mul might be
8716 // folded into smul or umul.
8717 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8718 isZeroExtended(N0.getNode(), DAG)))
8719 return SDValue();
8720 // Conservatively do not lower to shift+add+shift if the mul might be
8721 // folded into madd or msub.
8722 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8723 N->use_begin()->getOpcode() == ISD::SUB))
8724 return SDValue();
8725 }
8726 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8727 // and shift+add+shift.
8728 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8729
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008730 unsigned ShiftAmt, AddSubOpc;
8731 // Is the shifted value the LHS operand of the add/sub?
8732 bool ShiftValUseIsN0 = true;
8733 // Do we need to negate the result?
8734 bool NegateResult = false;
8735
Chad Rosier31ee8132016-11-11 17:07:37 +00008736 if (ConstValue.isNonNegative()) {
8737 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00008738 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00008739 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8740 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008741 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00008742 if (SCVMinus1.isPowerOf2()) {
8743 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008744 AddSubOpc = ISD::ADD;
8745 } else if (CVPlus1.isPowerOf2()) {
8746 ShiftAmt = CVPlus1.logBase2();
8747 AddSubOpc = ISD::SUB;
8748 } else
8749 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00008750 } else {
8751 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00008752 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008753 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008754 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008755 if (CVNegPlus1.isPowerOf2()) {
8756 ShiftAmt = CVNegPlus1.logBase2();
8757 AddSubOpc = ISD::SUB;
8758 ShiftValUseIsN0 = false;
8759 } else if (CVNegMinus1.isPowerOf2()) {
8760 ShiftAmt = CVNegMinus1.logBase2();
8761 AddSubOpc = ISD::ADD;
8762 NegateResult = true;
8763 } else
8764 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008765 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008766
8767 SDLoc DL(N);
8768 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008769 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008770 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8771
8772 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8773 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8774 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008775 assert(!(NegateResult && TrailingZeroes) &&
8776 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008777 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008778 if (NegateResult)
8779 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8780 // Shift the result.
8781 if (TrailingZeroes)
8782 return DAG.getNode(ISD::SHL, DL, VT, Res,
8783 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8784 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00008785}
8786
Jim Grosbachf7502c42014-07-18 00:40:52 +00008787static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8788 SelectionDAG &DAG) {
8789 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8790 // optimize away operation when it's from a constant.
8791 //
8792 // The general transformation is:
8793 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8794 // AND(VECTOR_CMP(x,y), constant2)
8795 // constant2 = UNARYOP(constant)
8796
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008797 // Early exit if this isn't a vector operation, the operand of the
8798 // unary operation isn't a bitwise AND, or if the sizes of the operations
8799 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00008800 EVT VT = N->getValueType(0);
8801 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008802 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8803 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008804 return SDValue();
8805
Jim Grosbach724e4382014-07-23 20:41:43 +00008806 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00008807 // make the transformation for non-constant splats as well, but it's unclear
8808 // that would be a benefit as it would not eliminate any operations, just
8809 // perform one more step in scalar code before moving to the vector unit.
8810 if (BuildVectorSDNode *BV =
8811 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00008812 // Bail out if the vector isn't a constant.
8813 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008814 return SDValue();
8815
8816 // Everything checks out. Build up the new and improved node.
8817 SDLoc DL(N);
8818 EVT IntVT = BV->getValueType(0);
8819 // Create a new constant of the appropriate type for the transformed
8820 // DAG.
8821 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8822 // The AND node needs bitcasts to/from an integer vector type around it.
8823 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8824 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8825 N->getOperand(0)->getOperand(0), MaskConst);
8826 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8827 return Res;
8828 }
8829
8830 return SDValue();
8831}
8832
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008833static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8834 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00008835 // First try to optimize away the conversion when it's conditionally from
8836 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008837 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00008838 return Res;
8839
Tim Northover3b0846e2014-05-24 12:50:23 +00008840 EVT VT = N->getValueType(0);
8841 if (VT != MVT::f32 && VT != MVT::f64)
8842 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00008843
Tim Northover3b0846e2014-05-24 12:50:23 +00008844 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008845 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00008846 return SDValue();
8847
8848 // If the result of an integer load is only used by an integer-to-float
8849 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00008850 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00008851 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008852 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008853 // Do not change the width of a volatile load.
8854 !cast<LoadSDNode>(N0)->isVolatile()) {
8855 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8856 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00008857 LN0->getPointerInfo(), LN0->getAlignment(),
8858 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008859
8860 // Make sure successors of the original load stay after it by updating them
8861 // to use the new Chain.
8862 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8863
8864 unsigned Opcode =
8865 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8866 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8867 }
8868
8869 return SDValue();
8870}
8871
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008872/// Fold a floating-point multiply by power of two into floating-point to
8873/// fixed-point conversion.
8874static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00008875 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008876 const AArch64Subtarget *Subtarget) {
8877 if (!Subtarget->hasNEON())
8878 return SDValue();
8879
8880 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00008881 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8882 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008883 return SDValue();
8884
8885 SDValue ConstVec = Op->getOperand(1);
8886 if (!isa<BuildVectorSDNode>(ConstVec))
8887 return SDValue();
8888
8889 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8890 uint32_t FloatBits = FloatTy.getSizeInBits();
8891 if (FloatBits != 32 && FloatBits != 64)
8892 return SDValue();
8893
8894 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8895 uint32_t IntBits = IntTy.getSizeInBits();
8896 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8897 return SDValue();
8898
8899 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8900 if (IntBits > FloatBits)
8901 return SDValue();
8902
8903 BitVector UndefElements;
8904 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8905 int32_t Bits = IntBits == 64 ? 64 : 32;
8906 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8907 if (C == -1 || C == 0 || C > Bits)
8908 return SDValue();
8909
8910 MVT ResTy;
8911 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8912 switch (NumLanes) {
8913 default:
8914 return SDValue();
8915 case 2:
8916 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8917 break;
8918 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00008919 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008920 break;
8921 }
8922
Silviu Barangafa00ba32016-08-08 13:13:57 +00008923 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8924 return SDValue();
8925
8926 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8927 "Illegal vector type after legalization");
8928
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008929 SDLoc DL(N);
8930 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8931 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8932 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8933 SDValue FixConv =
8934 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8935 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8936 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8937 // We can handle smaller integers by generating an extra trunc.
8938 if (IntBits < FloatBits)
8939 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8940
8941 return FixConv;
8942}
8943
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008944/// Fold a floating-point divide by power of two into fixed-point to
8945/// floating-point conversion.
8946static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00008947 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008948 const AArch64Subtarget *Subtarget) {
8949 if (!Subtarget->hasNEON())
8950 return SDValue();
8951
8952 SDValue Op = N->getOperand(0);
8953 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00008954 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8955 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008956 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8957 return SDValue();
8958
8959 SDValue ConstVec = N->getOperand(1);
8960 if (!isa<BuildVectorSDNode>(ConstVec))
8961 return SDValue();
8962
8963 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8964 int32_t IntBits = IntTy.getSizeInBits();
8965 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8966 return SDValue();
8967
8968 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8969 int32_t FloatBits = FloatTy.getSizeInBits();
8970 if (FloatBits != 32 && FloatBits != 64)
8971 return SDValue();
8972
8973 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8974 if (IntBits > FloatBits)
8975 return SDValue();
8976
8977 BitVector UndefElements;
8978 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8979 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8980 if (C == -1 || C == 0 || C > FloatBits)
8981 return SDValue();
8982
8983 MVT ResTy;
8984 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8985 switch (NumLanes) {
8986 default:
8987 return SDValue();
8988 case 2:
8989 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8990 break;
8991 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00008992 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008993 break;
8994 }
8995
Tim Northover85cf5642016-08-26 18:52:31 +00008996 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8997 return SDValue();
8998
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008999 SDLoc DL(N);
9000 SDValue ConvInput = Op.getOperand(0);
9001 bool IsSigned = Opc == ISD::SINT_TO_FP;
9002 if (IntBits < FloatBits)
9003 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9004 ResTy, ConvInput);
9005
9006 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9007 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9008 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9009 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9010 DAG.getConstant(C, DL, MVT::i32));
9011}
9012
Tim Northover3b0846e2014-05-24 12:50:23 +00009013/// An EXTR instruction is made up of two shifts, ORed together. This helper
9014/// searches for and classifies those shifts.
9015static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9016 bool &FromHi) {
9017 if (N.getOpcode() == ISD::SHL)
9018 FromHi = false;
9019 else if (N.getOpcode() == ISD::SRL)
9020 FromHi = true;
9021 else
9022 return false;
9023
9024 if (!isa<ConstantSDNode>(N.getOperand(1)))
9025 return false;
9026
9027 ShiftAmount = N->getConstantOperandVal(1);
9028 Src = N->getOperand(0);
9029 return true;
9030}
9031
9032/// EXTR instruction extracts a contiguous chunk of bits from two existing
9033/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009034/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9035/// with an EXTR. Can't quite be done in TableGen because the two immediates
9036/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009037static SDValue tryCombineToEXTR(SDNode *N,
9038 TargetLowering::DAGCombinerInfo &DCI) {
9039 SelectionDAG &DAG = DCI.DAG;
9040 SDLoc DL(N);
9041 EVT VT = N->getValueType(0);
9042
9043 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9044
9045 if (VT != MVT::i32 && VT != MVT::i64)
9046 return SDValue();
9047
9048 SDValue LHS;
9049 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009050 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009051 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9052 return SDValue();
9053
9054 SDValue RHS;
9055 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009056 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009057 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9058 return SDValue();
9059
9060 // If they're both trying to come from the high part of the register, they're
9061 // not really an EXTR.
9062 if (LHSFromHi == RHSFromHi)
9063 return SDValue();
9064
9065 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9066 return SDValue();
9067
9068 if (LHSFromHi) {
9069 std::swap(LHS, RHS);
9070 std::swap(ShiftLHS, ShiftRHS);
9071 }
9072
9073 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009074 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009075}
9076
9077static SDValue tryCombineToBSL(SDNode *N,
9078 TargetLowering::DAGCombinerInfo &DCI) {
9079 EVT VT = N->getValueType(0);
9080 SelectionDAG &DAG = DCI.DAG;
9081 SDLoc DL(N);
9082
9083 if (!VT.isVector())
9084 return SDValue();
9085
9086 SDValue N0 = N->getOperand(0);
9087 if (N0.getOpcode() != ISD::AND)
9088 return SDValue();
9089
9090 SDValue N1 = N->getOperand(1);
9091 if (N1.getOpcode() != ISD::AND)
9092 return SDValue();
9093
9094 // We only have to look for constant vectors here since the general, variable
9095 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009096 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009097 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9098 for (int i = 1; i >= 0; --i)
9099 for (int j = 1; j >= 0; --j) {
9100 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9101 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9102 if (!BVN0 || !BVN1)
9103 continue;
9104
9105 bool FoundMatch = true;
9106 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9107 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9108 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9109 if (!CN0 || !CN1 ||
9110 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9111 FoundMatch = false;
9112 break;
9113 }
9114 }
9115
9116 if (FoundMatch)
9117 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9118 N0->getOperand(1 - i), N1->getOperand(1 - j));
9119 }
9120
9121 return SDValue();
9122}
9123
9124static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9125 const AArch64Subtarget *Subtarget) {
9126 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009127 SelectionDAG &DAG = DCI.DAG;
9128 EVT VT = N->getValueType(0);
9129
9130 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9131 return SDValue();
9132
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009133 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009134 return Res;
9135
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009136 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009137 return Res;
9138
9139 return SDValue();
9140}
9141
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009142static SDValue performSRLCombine(SDNode *N,
9143 TargetLowering::DAGCombinerInfo &DCI) {
9144 SelectionDAG &DAG = DCI.DAG;
9145 EVT VT = N->getValueType(0);
9146 if (VT != MVT::i32 && VT != MVT::i64)
9147 return SDValue();
9148
9149 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9150 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9151 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9152 SDValue N0 = N->getOperand(0);
9153 if (N0.getOpcode() == ISD::BSWAP) {
9154 SDLoc DL(N);
9155 SDValue N1 = N->getOperand(1);
9156 SDValue N00 = N0.getOperand(0);
9157 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9158 uint64_t ShiftAmt = C->getZExtValue();
9159 if (VT == MVT::i32 && ShiftAmt == 16 &&
9160 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9161 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9162 if (VT == MVT::i64 && ShiftAmt == 32 &&
9163 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9164 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9165 }
9166 }
9167 return SDValue();
9168}
9169
Tim Northover3b0846e2014-05-24 12:50:23 +00009170static SDValue performBitcastCombine(SDNode *N,
9171 TargetLowering::DAGCombinerInfo &DCI,
9172 SelectionDAG &DAG) {
9173 // Wait 'til after everything is legalized to try this. That way we have
9174 // legal vector types and such.
9175 if (DCI.isBeforeLegalizeOps())
9176 return SDValue();
9177
9178 // Remove extraneous bitcasts around an extract_subvector.
9179 // For example,
9180 // (v4i16 (bitconvert
9181 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9182 // becomes
9183 // (extract_subvector ((v8i16 ...), (i64 4)))
9184
9185 // Only interested in 64-bit vectors as the ultimate result.
9186 EVT VT = N->getValueType(0);
9187 if (!VT.isVector())
9188 return SDValue();
9189 if (VT.getSimpleVT().getSizeInBits() != 64)
9190 return SDValue();
9191 // Is the operand an extract_subvector starting at the beginning or halfway
9192 // point of the vector? A low half may also come through as an
9193 // EXTRACT_SUBREG, so look for that, too.
9194 SDValue Op0 = N->getOperand(0);
9195 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9196 !(Op0->isMachineOpcode() &&
9197 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9198 return SDValue();
9199 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9200 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9201 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9202 return SDValue();
9203 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9204 if (idx != AArch64::dsub)
9205 return SDValue();
9206 // The dsub reference is equivalent to a lane zero subvector reference.
9207 idx = 0;
9208 }
9209 // Look through the bitcast of the input to the extract.
9210 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9211 return SDValue();
9212 SDValue Source = Op0->getOperand(0)->getOperand(0);
9213 // If the source type has twice the number of elements as our destination
9214 // type, we know this is an extract of the high or low half of the vector.
9215 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009216 if (!SVT.isVector() ||
9217 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009218 return SDValue();
9219
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009220 LLVM_DEBUG(
9221 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009222
9223 // Create the simplified form to just extract the low or high half of the
9224 // vector directly rather than bothering with the bitcasts.
9225 SDLoc dl(N);
9226 unsigned NumElements = VT.getVectorNumElements();
9227 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009228 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009229 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9230 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009231 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009232 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9233 Source, SubReg),
9234 0);
9235 }
9236}
9237
9238static SDValue performConcatVectorsCombine(SDNode *N,
9239 TargetLowering::DAGCombinerInfo &DCI,
9240 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009241 SDLoc dl(N);
9242 EVT VT = N->getValueType(0);
9243 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9244
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009245 // Optimize concat_vectors of truncated vectors, where the intermediate
9246 // type is illegal, to avoid said illegality, e.g.,
9247 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9248 // (v2i16 (truncate (v2i64)))))
9249 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009250 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9251 // (v4i32 (bitcast (v2i64))),
9252 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009253 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9254 // on both input and result type, so we might generate worse code.
9255 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9256 if (N->getNumOperands() == 2 &&
9257 N0->getOpcode() == ISD::TRUNCATE &&
9258 N1->getOpcode() == ISD::TRUNCATE) {
9259 SDValue N00 = N0->getOperand(0);
9260 SDValue N10 = N1->getOperand(0);
9261 EVT N00VT = N00.getValueType();
9262
9263 if (N00VT == N10.getValueType() &&
9264 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9265 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009266 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9267 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9268 for (size_t i = 0; i < Mask.size(); ++i)
9269 Mask[i] = i * 2;
9270 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9271 DAG.getVectorShuffle(
9272 MidVT, dl,
9273 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9274 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009275 }
9276 }
9277
Tim Northover3b0846e2014-05-24 12:50:23 +00009278 // Wait 'til after everything is legalized to try this. That way we have
9279 // legal vector types and such.
9280 if (DCI.isBeforeLegalizeOps())
9281 return SDValue();
9282
Tim Northover3b0846e2014-05-24 12:50:23 +00009283 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9284 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9285 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009286 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009287 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009288 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009289 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009290 }
9291
9292 // Canonicalise concat_vectors so that the right-hand vector has as few
9293 // bit-casts as possible before its real operation. The primary matching
9294 // destination for these operations will be the narrowing "2" instructions,
9295 // which depend on the operation being performed on this right-hand vector.
9296 // For example,
9297 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9298 // becomes
9299 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9300
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009301 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009302 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009303 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009304 MVT RHSTy = RHS.getValueType().getSimpleVT();
9305 // If the RHS is not a vector, this is not the pattern we're looking for.
9306 if (!RHSTy.isVector())
9307 return SDValue();
9308
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009309 LLVM_DEBUG(
9310 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009311
9312 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9313 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009314 return DAG.getNode(ISD::BITCAST, dl, VT,
9315 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9316 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9317 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009318}
9319
9320static SDValue tryCombineFixedPointConvert(SDNode *N,
9321 TargetLowering::DAGCombinerInfo &DCI,
9322 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009323 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009324 // legal vector types and such.
9325 if (DCI.isBeforeLegalizeOps())
9326 return SDValue();
9327 // Transform a scalar conversion of a value from a lane extract into a
9328 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9329 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9330 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9331 //
9332 // The second form interacts better with instruction selection and the
9333 // register allocator to avoid cross-class register copies that aren't
9334 // coalescable due to a lane reference.
9335
9336 // Check the operand and see if it originates from a lane extract.
9337 SDValue Op1 = N->getOperand(1);
9338 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9339 // Yep, no additional predication needed. Perform the transform.
9340 SDValue IID = N->getOperand(0);
9341 SDValue Shift = N->getOperand(2);
9342 SDValue Vec = Op1.getOperand(0);
9343 SDValue Lane = Op1.getOperand(1);
9344 EVT ResTy = N->getValueType(0);
9345 EVT VecResTy;
9346 SDLoc DL(N);
9347
9348 // The vector width should be 128 bits by the time we get here, even
9349 // if it started as 64 bits (the extract_vector handling will have
9350 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009351 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009352 "unexpected vector size on extract_vector_elt!");
9353 if (Vec.getValueType() == MVT::v4i32)
9354 VecResTy = MVT::v4f32;
9355 else if (Vec.getValueType() == MVT::v2i64)
9356 VecResTy = MVT::v2f64;
9357 else
Craig Topper2a30d782014-06-18 05:05:13 +00009358 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009359
9360 SDValue Convert =
9361 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9362 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9363 }
9364 return SDValue();
9365}
9366
9367// AArch64 high-vector "long" operations are formed by performing the non-high
9368// version on an extract_subvector of each operand which gets the high half:
9369//
9370// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9371//
9372// However, there are cases which don't have an extract_high explicitly, but
9373// have another operation that can be made compatible with one for free. For
9374// example:
9375//
9376// (dupv64 scalar) --> (extract_high (dup128 scalar))
9377//
9378// This routine does the actual conversion of such DUPs, once outer routines
9379// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009380// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9381// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009382static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009383 switch (N.getOpcode()) {
9384 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009385 case AArch64ISD::DUPLANE8:
9386 case AArch64ISD::DUPLANE16:
9387 case AArch64ISD::DUPLANE32:
9388 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009389 case AArch64ISD::MOVI:
9390 case AArch64ISD::MOVIshift:
9391 case AArch64ISD::MOVIedit:
9392 case AArch64ISD::MOVImsl:
9393 case AArch64ISD::MVNIshift:
9394 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009395 break;
9396 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009397 // FMOV could be supported, but isn't very useful, as it would only occur
9398 // if you passed a bitcast' floating point immediate to an eligible long
9399 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009400 return SDValue();
9401 }
9402
9403 MVT NarrowTy = N.getSimpleValueType();
9404 if (!NarrowTy.is64BitVector())
9405 return SDValue();
9406
9407 MVT ElementTy = NarrowTy.getVectorElementType();
9408 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009409 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009410
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009411 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9413 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009414 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009415}
9416
9417static bool isEssentiallyExtractSubvector(SDValue N) {
9418 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9419 return true;
9420
9421 return N.getOpcode() == ISD::BITCAST &&
9422 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9423}
9424
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009425/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009426struct GenericSetCCInfo {
9427 const SDValue *Opnd0;
9428 const SDValue *Opnd1;
9429 ISD::CondCode CC;
9430};
9431
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009432/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009433struct AArch64SetCCInfo {
9434 const SDValue *Cmp;
9435 AArch64CC::CondCode CC;
9436};
9437
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009438/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009439union SetCCInfo {
9440 GenericSetCCInfo Generic;
9441 AArch64SetCCInfo AArch64;
9442};
9443
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009444/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009445/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9446/// GenericSetCCInfo.
9447struct SetCCInfoAndKind {
9448 SetCCInfo Info;
9449 bool IsAArch64;
9450};
9451
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009452/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009453/// an
9454/// AArch64 lowered one.
9455/// \p SetCCInfo is filled accordingly.
9456/// \post SetCCInfo is meanginfull only when this function returns true.
9457/// \return True when Op is a kind of SET_CC operation.
9458static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9459 // If this is a setcc, this is straight forward.
9460 if (Op.getOpcode() == ISD::SETCC) {
9461 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9462 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9463 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9464 SetCCInfo.IsAArch64 = false;
9465 return true;
9466 }
9467 // Otherwise, check if this is a matching csel instruction.
9468 // In other words:
9469 // - csel 1, 0, cc
9470 // - csel 0, 1, !cc
9471 if (Op.getOpcode() != AArch64ISD::CSEL)
9472 return false;
9473 // Set the information about the operands.
9474 // TODO: we want the operands of the Cmp not the csel
9475 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9476 SetCCInfo.IsAArch64 = true;
9477 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9478 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9479
9480 // Check that the operands matches the constraints:
9481 // (1) Both operands must be constants.
9482 // (2) One must be 1 and the other must be 0.
9483 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9484 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9485
9486 // Check (1).
9487 if (!TValue || !FValue)
9488 return false;
9489
9490 // Check (2).
9491 if (!TValue->isOne()) {
9492 // Update the comparison when we are interested in !cc.
9493 std::swap(TValue, FValue);
9494 SetCCInfo.Info.AArch64.CC =
9495 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9496 }
9497 return TValue->isOne() && FValue->isNullValue();
9498}
9499
9500// Returns true if Op is setcc or zext of setcc.
9501static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9502 if (isSetCC(Op, Info))
9503 return true;
9504 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9505 isSetCC(Op->getOperand(0), Info));
9506}
9507
9508// The folding we want to perform is:
9509// (add x, [zext] (setcc cc ...) )
9510// -->
9511// (csel x, (add x, 1), !cc ...)
9512//
9513// The latter will get matched to a CSINC instruction.
9514static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9515 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9516 SDValue LHS = Op->getOperand(0);
9517 SDValue RHS = Op->getOperand(1);
9518 SetCCInfoAndKind InfoAndKind;
9519
9520 // If neither operand is a SET_CC, give up.
9521 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9522 std::swap(LHS, RHS);
9523 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9524 return SDValue();
9525 }
9526
9527 // FIXME: This could be generatized to work for FP comparisons.
9528 EVT CmpVT = InfoAndKind.IsAArch64
9529 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9530 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9531 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9532 return SDValue();
9533
9534 SDValue CCVal;
9535 SDValue Cmp;
9536 SDLoc dl(Op);
9537 if (InfoAndKind.IsAArch64) {
9538 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009539 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9540 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009541 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9542 } else
9543 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9544 *InfoAndKind.Info.Generic.Opnd1,
9545 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9546 CCVal, DAG, dl);
9547
9548 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009549 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009550 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9551}
9552
9553// The basic add/sub long vector instructions have variants with "2" on the end
9554// which act on the high-half of their inputs. They are normally matched by
9555// patterns like:
9556//
9557// (add (zeroext (extract_high LHS)),
9558// (zeroext (extract_high RHS)))
9559// -> uaddl2 vD, vN, vM
9560//
9561// However, if one of the extracts is something like a duplicate, this
9562// instruction can still be used profitably. This function puts the DAG into a
9563// more appropriate form for those patterns to trigger.
9564static SDValue performAddSubLongCombine(SDNode *N,
9565 TargetLowering::DAGCombinerInfo &DCI,
9566 SelectionDAG &DAG) {
9567 if (DCI.isBeforeLegalizeOps())
9568 return SDValue();
9569
9570 MVT VT = N->getSimpleValueType(0);
9571 if (!VT.is128BitVector()) {
9572 if (N->getOpcode() == ISD::ADD)
9573 return performSetccAddFolding(N, DAG);
9574 return SDValue();
9575 }
9576
9577 // Make sure both branches are extended in the same way.
9578 SDValue LHS = N->getOperand(0);
9579 SDValue RHS = N->getOperand(1);
9580 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9581 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9582 LHS.getOpcode() != RHS.getOpcode())
9583 return SDValue();
9584
9585 unsigned ExtType = LHS.getOpcode();
9586
9587 // It's not worth doing if at least one of the inputs isn't already an
9588 // extract, but we don't know which it'll be so we have to try both.
9589 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9590 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9591 if (!RHS.getNode())
9592 return SDValue();
9593
9594 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9595 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9596 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9597 if (!LHS.getNode())
9598 return SDValue();
9599
9600 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9601 }
9602
9603 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9604}
9605
9606// Massage DAGs which we can use the high-half "long" operations on into
9607// something isel will recognize better. E.g.
9608//
9609// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9610// (aarch64_neon_umull (extract_high (v2i64 vec)))
9611// (extract_high (v2i64 (dup128 scalar)))))
9612//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009613static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009614 TargetLowering::DAGCombinerInfo &DCI,
9615 SelectionDAG &DAG) {
9616 if (DCI.isBeforeLegalizeOps())
9617 return SDValue();
9618
Hal Finkelcd8664c2015-12-11 23:11:52 +00009619 SDValue LHS = N->getOperand(1);
9620 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009621 assert(LHS.getValueType().is64BitVector() &&
9622 RHS.getValueType().is64BitVector() &&
9623 "unexpected shape for long operation");
9624
9625 // Either node could be a DUP, but it's not worth doing both of them (you'd
9626 // just as well use the non-high version) so look for a corresponding extract
9627 // operation on the other "wing".
9628 if (isEssentiallyExtractSubvector(LHS)) {
9629 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9630 if (!RHS.getNode())
9631 return SDValue();
9632 } else if (isEssentiallyExtractSubvector(RHS)) {
9633 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9634 if (!LHS.getNode())
9635 return SDValue();
9636 }
9637
Hal Finkelcd8664c2015-12-11 23:11:52 +00009638 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9639 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009640}
9641
9642static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9643 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9644 unsigned ElemBits = ElemTy.getSizeInBits();
9645
9646 int64_t ShiftAmount;
9647 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9648 APInt SplatValue, SplatUndef;
9649 unsigned SplatBitSize;
9650 bool HasAnyUndefs;
9651 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9652 HasAnyUndefs, ElemBits) ||
9653 SplatBitSize != ElemBits)
9654 return SDValue();
9655
9656 ShiftAmount = SplatValue.getSExtValue();
9657 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9658 ShiftAmount = CVN->getSExtValue();
9659 } else
9660 return SDValue();
9661
9662 unsigned Opcode;
9663 bool IsRightShift;
9664 switch (IID) {
9665 default:
9666 llvm_unreachable("Unknown shift intrinsic");
9667 case Intrinsic::aarch64_neon_sqshl:
9668 Opcode = AArch64ISD::SQSHL_I;
9669 IsRightShift = false;
9670 break;
9671 case Intrinsic::aarch64_neon_uqshl:
9672 Opcode = AArch64ISD::UQSHL_I;
9673 IsRightShift = false;
9674 break;
9675 case Intrinsic::aarch64_neon_srshl:
9676 Opcode = AArch64ISD::SRSHR_I;
9677 IsRightShift = true;
9678 break;
9679 case Intrinsic::aarch64_neon_urshl:
9680 Opcode = AArch64ISD::URSHR_I;
9681 IsRightShift = true;
9682 break;
9683 case Intrinsic::aarch64_neon_sqshlu:
9684 Opcode = AArch64ISD::SQSHLU_I;
9685 IsRightShift = false;
9686 break;
9687 }
9688
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009689 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9690 SDLoc dl(N);
9691 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9692 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9693 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9694 SDLoc dl(N);
9695 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9696 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9697 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009698
9699 return SDValue();
9700}
9701
9702// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9703// the intrinsics must be legal and take an i32, this means there's almost
9704// certainly going to be a zext in the DAG which we can eliminate.
9705static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9706 SDValue AndN = N->getOperand(2);
9707 if (AndN.getOpcode() != ISD::AND)
9708 return SDValue();
9709
9710 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9711 if (!CMask || CMask->getZExtValue() != Mask)
9712 return SDValue();
9713
9714 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9715 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9716}
9717
Ahmed Bougachafab58922015-03-10 20:45:38 +00009718static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9719 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009720 SDLoc dl(N);
9721 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9722 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009723 N->getOperand(1).getSimpleValueType(),
9724 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009725 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009726}
9727
Tim Northover3b0846e2014-05-24 12:50:23 +00009728static SDValue performIntrinsicCombine(SDNode *N,
9729 TargetLowering::DAGCombinerInfo &DCI,
9730 const AArch64Subtarget *Subtarget) {
9731 SelectionDAG &DAG = DCI.DAG;
9732 unsigned IID = getIntrinsicID(N);
9733 switch (IID) {
9734 default:
9735 break;
9736 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9737 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9738 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00009739 case Intrinsic::aarch64_neon_saddv:
9740 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9741 case Intrinsic::aarch64_neon_uaddv:
9742 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9743 case Intrinsic::aarch64_neon_sminv:
9744 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9745 case Intrinsic::aarch64_neon_uminv:
9746 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9747 case Intrinsic::aarch64_neon_smaxv:
9748 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9749 case Intrinsic::aarch64_neon_umaxv:
9750 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009751 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00009752 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009753 N->getOperand(1), N->getOperand(2));
9754 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00009755 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009756 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00009757 case Intrinsic::aarch64_neon_fmaxnm:
9758 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9759 N->getOperand(1), N->getOperand(2));
9760 case Intrinsic::aarch64_neon_fminnm:
9761 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9762 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009763 case Intrinsic::aarch64_neon_smull:
9764 case Intrinsic::aarch64_neon_umull:
9765 case Intrinsic::aarch64_neon_pmull:
9766 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00009767 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009768 case Intrinsic::aarch64_neon_sqshl:
9769 case Intrinsic::aarch64_neon_uqshl:
9770 case Intrinsic::aarch64_neon_sqshlu:
9771 case Intrinsic::aarch64_neon_srshl:
9772 case Intrinsic::aarch64_neon_urshl:
9773 return tryCombineShiftImm(IID, N, DAG);
9774 case Intrinsic::aarch64_crc32b:
9775 case Intrinsic::aarch64_crc32cb:
9776 return tryCombineCRC32(0xff, N, DAG);
9777 case Intrinsic::aarch64_crc32h:
9778 case Intrinsic::aarch64_crc32ch:
9779 return tryCombineCRC32(0xffff, N, DAG);
9780 }
9781 return SDValue();
9782}
9783
9784static SDValue performExtendCombine(SDNode *N,
9785 TargetLowering::DAGCombinerInfo &DCI,
9786 SelectionDAG &DAG) {
9787 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9788 // we can convert that DUP into another extract_high (of a bigger DUP), which
9789 // helps the backend to decide that an sabdl2 would be useful, saving a real
9790 // extract_high operation.
9791 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00009792 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009793 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00009794 unsigned IID = getIntrinsicID(ABDNode);
9795 if (IID == Intrinsic::aarch64_neon_sabd ||
9796 IID == Intrinsic::aarch64_neon_uabd) {
9797 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9798 if (!NewABD.getNode())
9799 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009800
Hal Finkelcd8664c2015-12-11 23:11:52 +00009801 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9802 NewABD);
9803 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009804 }
9805
9806 // This is effectively a custom type legalization for AArch64.
9807 //
9808 // Type legalization will split an extend of a small, legal, type to a larger
9809 // illegal type by first splitting the destination type, often creating
9810 // illegal source types, which then get legalized in isel-confusing ways,
9811 // leading to really terrible codegen. E.g.,
9812 // %result = v8i32 sext v8i8 %value
9813 // becomes
9814 // %losrc = extract_subreg %value, ...
9815 // %hisrc = extract_subreg %value, ...
9816 // %lo = v4i32 sext v4i8 %losrc
9817 // %hi = v4i32 sext v4i8 %hisrc
9818 // Things go rapidly downhill from there.
9819 //
9820 // For AArch64, the [sz]ext vector instructions can only go up one element
9821 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9822 // take two instructions.
9823 //
9824 // This implies that the most efficient way to do the extend from v8i8
9825 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9826 // the normal splitting to happen for the v8i16->v8i32.
9827
9828 // This is pre-legalization to catch some cases where the default
9829 // type legalization will create ill-tempered code.
9830 if (!DCI.isBeforeLegalizeOps())
9831 return SDValue();
9832
9833 // We're only interested in cleaning things up for non-legal vector types
9834 // here. If both the source and destination are legal, things will just
9835 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00009836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00009837 EVT ResVT = N->getValueType(0);
9838 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9839 return SDValue();
9840 // If the vector type isn't a simple VT, it's beyond the scope of what
9841 // we're worried about here. Let legalization do its thing and hope for
9842 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00009843 SDValue Src = N->getOperand(0);
9844 EVT SrcVT = Src->getValueType(0);
9845 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00009846 return SDValue();
9847
Tim Northover3b0846e2014-05-24 12:50:23 +00009848 // If the source VT is a 64-bit vector, we can play games and get the
9849 // better results we want.
9850 if (SrcVT.getSizeInBits() != 64)
9851 return SDValue();
9852
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009853 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009854 unsigned ElementCount = SrcVT.getVectorNumElements();
9855 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9856 SDLoc DL(N);
9857 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9858
9859 // Now split the rest of the operation into two halves, each with a 64
9860 // bit source.
9861 EVT LoVT, HiVT;
9862 SDValue Lo, Hi;
9863 unsigned NumElements = ResVT.getVectorNumElements();
9864 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9865 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9866 ResVT.getVectorElementType(), NumElements / 2);
9867
9868 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9869 LoVT.getVectorNumElements());
9870 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009871 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009872 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009873 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009874 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9875 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9876
9877 // Now combine the parts back together so we still have a single result
9878 // like the combiner expects.
9879 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9880}
9881
Geoff Berry8301c642016-11-16 19:35:19 +00009882static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9883 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009884 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +00009885 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009886
9887 // Create scalar stores. This is at least as good as the code sequence for a
9888 // split unaligned store which is a dup.s, ext.b, and two stores.
9889 // Most of the time the three stores should be replaced by store pair
9890 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009891 SDLoc DL(&St);
9892 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009893 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +00009894
John Brawn3a9c8422017-02-06 18:07:20 +00009895 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009896 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +00009897 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +00009898 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009899
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009900 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +00009901 if (BasePtr->getOpcode() == ISD::ADD &&
9902 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9903 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9904 BasePtr = BasePtr->getOperand(0);
9905 }
9906
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009907 unsigned Offset = EltOffset;
9908 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +00009909 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009910 SDValue OffsetPtr =
9911 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9912 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009913 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +00009914 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009915 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009916 Offset += EltOffset;
9917 }
9918 return NewST1;
9919}
9920
Geoff Berry526c5052016-11-14 19:39:04 +00009921/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9922/// load store optimizer pass will merge them to store pair stores. This should
9923/// be better than a movi to create the vector zero followed by a vector store
9924/// if the zero constant is not re-used, since one instructions and one register
9925/// live range will be removed.
9926///
9927/// For example, the final generated code should be:
9928///
9929/// stp xzr, xzr, [x0]
9930///
9931/// instead of:
9932///
9933/// movi v0.2d, #0
9934/// str q0, [x0]
9935///
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009936static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9937 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +00009938 EVT VT = StVal.getValueType();
9939
Geoff Berry8301c642016-11-16 19:35:19 +00009940 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9941 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +00009942 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +00009943 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9944 VT.getVectorElementType().getSizeInBits() == 64) ||
9945 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9946 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +00009947 return SDValue();
9948
9949 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9950 return SDValue();
9951
9952 // If the zero constant has more than one use then the vector store could be
9953 // better since the constant mov will be amortized and stp q instructions
9954 // should be able to be formed.
9955 if (!StVal.hasOneUse())
9956 return SDValue();
9957
9958 // If the immediate offset of the address operand is too large for the stp
9959 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009960 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9961 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +00009962 if (Offset < -512 || Offset > 504)
9963 return SDValue();
9964 }
9965
9966 for (int I = 0; I < NumVecElts; ++I) {
9967 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +00009968 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +00009969 return SDValue();
9970 }
Geoff Berry8301c642016-11-16 19:35:19 +00009971
Geoff Berrybb23df92017-09-21 21:10:06 +00009972 // Use a CopyFromReg WZR/XZR here to prevent
9973 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
9974 SDLoc DL(&St);
9975 unsigned ZeroReg;
9976 EVT ZeroVT;
9977 if (VT.getVectorElementType().getSizeInBits() == 32) {
9978 ZeroReg = AArch64::WZR;
9979 ZeroVT = MVT::i32;
9980 } else {
9981 ZeroReg = AArch64::XZR;
9982 ZeroVT = MVT::i64;
9983 }
9984 SDValue SplatVal =
9985 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +00009986 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +00009987}
9988
Tim Northover3b0846e2014-05-24 12:50:23 +00009989/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9990/// value. The load store optimizer pass will merge them to store pair stores.
9991/// This has better performance than a splat of the scalar followed by a split
9992/// vector store. Even if the stores are not merged it is four stores vs a dup,
9993/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009994static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9995 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009996 EVT VT = StVal.getValueType();
9997
9998 // Don't replace floating point stores, they possibly won't be transformed to
9999 // stp because of the store pair suppress pass.
10000 if (VT.isFloatingPoint())
10001 return SDValue();
10002
Tim Northover3b0846e2014-05-24 12:50:23 +000010003 // We can express a splat as store pair(s) for 2 or 4 elements.
10004 unsigned NumVecElts = VT.getVectorNumElements();
10005 if (NumVecElts != 4 && NumVecElts != 2)
10006 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010007
10008 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010009 // Make sure that each of the relevant vector element locations are inserted
10010 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10011 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10012 SDValue SplatVal;
10013 for (unsigned I = 0; I < NumVecElts; ++I) {
10014 // Check for insert vector elements.
10015 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010016 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010017
10018 // Check that same value is inserted at each vector element.
10019 if (I == 0)
10020 SplatVal = StVal.getOperand(1);
10021 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010022 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010023
10024 // Check insert element index.
10025 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10026 if (!CIndex)
10027 return SDValue();
10028 uint64_t IndexVal = CIndex->getZExtValue();
10029 if (IndexVal >= NumVecElts)
10030 return SDValue();
10031 IndexNotInserted.reset(IndexVal);
10032
10033 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010034 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010035 // Check that all vector element locations were inserted to.
10036 if (IndexNotInserted.any())
10037 return SDValue();
10038
Geoff Berry8301c642016-11-16 19:35:19 +000010039 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010040}
10041
Geoff Berry8301c642016-11-16 19:35:19 +000010042static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10043 SelectionDAG &DAG,
10044 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010045
10046 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010047 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010048 return SDValue();
10049
Geoff Berry526c5052016-11-14 19:39:04 +000010050 SDValue StVal = S->getValue();
10051 EVT VT = StVal.getValueType();
10052 if (!VT.isVector())
10053 return SDValue();
10054
10055 // If we get a splat of zeros, convert this vector store to a store of
10056 // scalars. They will be merged into store pairs of xzr thereby removing one
10057 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010058 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010059 return ReplacedZeroSplat;
10060
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010061 // FIXME: The logic for deciding if an unaligned store should be split should
10062 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10063 // a call to that function here.
10064
Matthias Braun651cff42016-06-02 18:03:53 +000010065 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010066 return SDValue();
10067
Sanjay Patel924879a2015-08-04 15:49:57 +000010068 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +000010069 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010070 return SDValue();
10071
Tim Northover3b0846e2014-05-24 12:50:23 +000010072 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10073 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010074 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010075 return SDValue();
10076
10077 // Split unaligned 16B stores. They are terrible for performance.
10078 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10079 // extensions can use this to mark that it does not want splitting to happen
10080 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10081 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10082 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10083 S->getAlignment() <= 2)
10084 return SDValue();
10085
10086 // If we get a splat of a scalar convert this vector store to a store of
10087 // scalars. They will be merged into store pairs thereby removing two
10088 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010089 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010090 return ReplacedSplat;
10091
10092 SDLoc DL(S);
10093 unsigned NumElts = VT.getVectorNumElements() / 2;
10094 // Split VT into two.
10095 EVT HalfVT =
10096 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10097 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010098 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010099 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010100 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010101 SDValue BasePtr = S->getBasePtr();
10102 SDValue NewST1 =
10103 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010104 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010105 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010106 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010107 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010108 S->getPointerInfo(), S->getAlignment(),
10109 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010110}
10111
10112/// Target-specific DAG combine function for post-increment LD1 (lane) and
10113/// post-increment LD1R.
10114static SDValue performPostLD1Combine(SDNode *N,
10115 TargetLowering::DAGCombinerInfo &DCI,
10116 bool IsLaneOp) {
10117 if (DCI.isBeforeLegalizeOps())
10118 return SDValue();
10119
10120 SelectionDAG &DAG = DCI.DAG;
10121 EVT VT = N->getValueType(0);
10122
10123 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10124 SDNode *LD = N->getOperand(LoadIdx).getNode();
10125 // If it is not LOAD, can not do such combine.
10126 if (LD->getOpcode() != ISD::LOAD)
10127 return SDValue();
10128
Geoff Berry60460262018-05-11 16:25:06 +000010129 // The vector lane must be a constant in the LD1LANE opcode.
10130 SDValue Lane;
10131 if (IsLaneOp) {
10132 Lane = N->getOperand(2);
10133 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10134 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10135 return SDValue();
10136 }
10137
Tim Northover3b0846e2014-05-24 12:50:23 +000010138 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10139 EVT MemVT = LoadSDN->getMemoryVT();
10140 // Check if memory operand is the same type as the vector element.
10141 if (MemVT != VT.getVectorElementType())
10142 return SDValue();
10143
10144 // Check if there are other uses. If so, do not combine as it will introduce
10145 // an extra load.
10146 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10147 ++UI) {
10148 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10149 continue;
10150 if (*UI != N)
10151 return SDValue();
10152 }
10153
10154 SDValue Addr = LD->getOperand(1);
10155 SDValue Vector = N->getOperand(0);
10156 // Search for a use of the address operand that is an increment.
10157 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10158 Addr.getNode()->use_end(); UI != UE; ++UI) {
10159 SDNode *User = *UI;
10160 if (User->getOpcode() != ISD::ADD
10161 || UI.getUse().getResNo() != Addr.getResNo())
10162 continue;
10163
10164 // Check that the add is independent of the load. Otherwise, folding it
10165 // would create a cycle.
10166 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
10167 continue;
10168 // Also check that add is not used in the vector operand. This would also
10169 // create a cycle.
10170 if (User->isPredecessorOf(Vector.getNode()))
10171 continue;
10172
10173 // If the increment is a constant, it must match the memory ref size.
10174 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10175 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10176 uint32_t IncVal = CInc->getZExtValue();
10177 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10178 if (IncVal != NumBytes)
10179 continue;
10180 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10181 }
10182
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010183 // Finally, check that the vector doesn't depend on the load.
10184 // Again, this would create a cycle.
10185 // The load depending on the vector is fine, as that's the case for the
10186 // LD1*post we'll eventually generate anyway.
10187 if (LoadSDN->isPredecessorOf(Vector.getNode()))
10188 continue;
10189
Tim Northover3b0846e2014-05-24 12:50:23 +000010190 SmallVector<SDValue, 8> Ops;
10191 Ops.push_back(LD->getOperand(0)); // Chain
10192 if (IsLaneOp) {
10193 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010194 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010195 }
10196 Ops.push_back(Addr);
10197 Ops.push_back(Inc);
10198
10199 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010200 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010201 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10202 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10203 MemVT,
10204 LoadSDN->getMemOperand());
10205
10206 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010207 SDValue NewResults[] = {
10208 SDValue(LD, 0), // The result of load
10209 SDValue(UpdN.getNode(), 2) // Chain
10210 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010211 DCI.CombineTo(LD, NewResults);
10212 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10213 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10214
10215 break;
10216 }
10217 return SDValue();
10218}
10219
Joel Jones7466ccf2017-07-10 22:11:50 +000010220/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010221/// address translation.
10222static bool performTBISimplification(SDValue Addr,
10223 TargetLowering::DAGCombinerInfo &DCI,
10224 SelectionDAG &DAG) {
10225 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010226 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010227 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10228 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010229 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010230 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010231 DCI.CommitTargetLoweringOpt(TLO);
10232 return true;
10233 }
10234 return false;
10235}
10236
10237static SDValue performSTORECombine(SDNode *N,
10238 TargetLowering::DAGCombinerInfo &DCI,
10239 SelectionDAG &DAG,
10240 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010241 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010242 return Split;
10243
10244 if (Subtarget->supportsAddressTopByteIgnored() &&
10245 performTBISimplification(N->getOperand(2), DCI, DAG))
10246 return SDValue(N, 0);
10247
10248 return SDValue();
10249}
10250
Chad Rosier6c36eff2015-09-03 18:13:57 +000010251
Tim Northover3b0846e2014-05-24 12:50:23 +000010252/// Target-specific DAG combine function for NEON load/store intrinsics
10253/// to merge base address updates.
10254static SDValue performNEONPostLDSTCombine(SDNode *N,
10255 TargetLowering::DAGCombinerInfo &DCI,
10256 SelectionDAG &DAG) {
10257 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10258 return SDValue();
10259
10260 unsigned AddrOpIdx = N->getNumOperands() - 1;
10261 SDValue Addr = N->getOperand(AddrOpIdx);
10262
10263 // Search for a use of the address operand that is an increment.
10264 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10265 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10266 SDNode *User = *UI;
10267 if (User->getOpcode() != ISD::ADD ||
10268 UI.getUse().getResNo() != Addr.getResNo())
10269 continue;
10270
10271 // Check that the add is independent of the load/store. Otherwise, folding
10272 // it would create a cycle.
10273 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10274 continue;
10275
10276 // Find the new opcode for the updating load/store.
10277 bool IsStore = false;
10278 bool IsLaneOp = false;
10279 bool IsDupOp = false;
10280 unsigned NewOpc = 0;
10281 unsigned NumVecs = 0;
10282 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10283 switch (IntNo) {
10284 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10285 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10286 NumVecs = 2; break;
10287 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10288 NumVecs = 3; break;
10289 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10290 NumVecs = 4; break;
10291 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10292 NumVecs = 2; IsStore = true; break;
10293 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10294 NumVecs = 3; IsStore = true; break;
10295 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10296 NumVecs = 4; IsStore = true; break;
10297 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10298 NumVecs = 2; break;
10299 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10300 NumVecs = 3; break;
10301 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10302 NumVecs = 4; break;
10303 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10304 NumVecs = 2; IsStore = true; break;
10305 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10306 NumVecs = 3; IsStore = true; break;
10307 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10308 NumVecs = 4; IsStore = true; break;
10309 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10310 NumVecs = 2; IsDupOp = true; break;
10311 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10312 NumVecs = 3; IsDupOp = true; break;
10313 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10314 NumVecs = 4; IsDupOp = true; break;
10315 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10316 NumVecs = 2; IsLaneOp = true; break;
10317 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10318 NumVecs = 3; IsLaneOp = true; break;
10319 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10320 NumVecs = 4; IsLaneOp = true; break;
10321 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10322 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10323 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10324 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10325 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10326 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10327 }
10328
10329 EVT VecTy;
10330 if (IsStore)
10331 VecTy = N->getOperand(2).getValueType();
10332 else
10333 VecTy = N->getValueType(0);
10334
10335 // If the increment is a constant, it must match the memory ref size.
10336 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10337 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10338 uint32_t IncVal = CInc->getZExtValue();
10339 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10340 if (IsLaneOp || IsDupOp)
10341 NumBytes /= VecTy.getVectorNumElements();
10342 if (IncVal != NumBytes)
10343 continue;
10344 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10345 }
10346 SmallVector<SDValue, 8> Ops;
10347 Ops.push_back(N->getOperand(0)); // Incoming chain
10348 // Load lane and store have vector list as input.
10349 if (IsLaneOp || IsStore)
10350 for (unsigned i = 2; i < AddrOpIdx; ++i)
10351 Ops.push_back(N->getOperand(i));
10352 Ops.push_back(Addr); // Base register
10353 Ops.push_back(Inc);
10354
10355 // Return Types.
10356 EVT Tys[6];
10357 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10358 unsigned n;
10359 for (n = 0; n < NumResultVecs; ++n)
10360 Tys[n] = VecTy;
10361 Tys[n++] = MVT::i64; // Type of write back register
10362 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010363 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010364
10365 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10366 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10367 MemInt->getMemoryVT(),
10368 MemInt->getMemOperand());
10369
10370 // Update the uses.
10371 std::vector<SDValue> NewResults;
10372 for (unsigned i = 0; i < NumResultVecs; ++i) {
10373 NewResults.push_back(SDValue(UpdN.getNode(), i));
10374 }
10375 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10376 DCI.CombineTo(N, NewResults);
10377 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10378
10379 break;
10380 }
10381 return SDValue();
10382}
10383
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010384// Checks to see if the value is the prescribed width and returns information
10385// about its extension mode.
10386static
10387bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10388 ExtType = ISD::NON_EXTLOAD;
10389 switch(V.getNode()->getOpcode()) {
10390 default:
10391 return false;
10392 case ISD::LOAD: {
10393 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10394 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10395 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10396 ExtType = LoadNode->getExtensionType();
10397 return true;
10398 }
10399 return false;
10400 }
10401 case ISD::AssertSext: {
10402 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10403 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10404 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10405 ExtType = ISD::SEXTLOAD;
10406 return true;
10407 }
10408 return false;
10409 }
10410 case ISD::AssertZext: {
10411 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10412 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10413 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10414 ExtType = ISD::ZEXTLOAD;
10415 return true;
10416 }
10417 return false;
10418 }
10419 case ISD::Constant:
10420 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010421 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10422 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010423 }
10424 }
10425
10426 return true;
10427}
10428
10429// This function does a whole lot of voodoo to determine if the tests are
10430// equivalent without and with a mask. Essentially what happens is that given a
10431// DAG resembling:
10432//
10433// +-------------+ +-------------+ +-------------+ +-------------+
10434// | Input | | AddConstant | | CompConstant| | CC |
10435// +-------------+ +-------------+ +-------------+ +-------------+
10436// | | | |
10437// V V | +----------+
10438// +-------------+ +----+ | |
10439// | ADD | |0xff| | |
10440// +-------------+ +----+ | |
10441// | | | |
10442// V V | |
10443// +-------------+ | |
10444// | AND | | |
10445// +-------------+ | |
10446// | | |
10447// +-----+ | |
10448// | | |
10449// V V V
10450// +-------------+
10451// | CMP |
10452// +-------------+
10453//
10454// The AND node may be safely removed for some combinations of inputs. In
10455// particular we need to take into account the extension type of the Input,
10456// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10457// width of the input (this can work for any width inputs, the above graph is
10458// specific to 8 bits.
10459//
10460// The specific equations were worked out by generating output tables for each
10461// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10462// problem was simplified by working with 4 bit inputs, which means we only
10463// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10464// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10465// patterns present in both extensions (0,7). For every distinct set of
10466// AddConstant and CompConstants bit patterns we can consider the masked and
10467// unmasked versions to be equivalent if the result of this function is true for
10468// all 16 distinct bit patterns of for the current extension type of Input (w0).
10469//
10470// sub w8, w0, w1
10471// and w10, w8, #0x0f
10472// cmp w8, w2
10473// cset w9, AArch64CC
10474// cmp w10, w2
10475// cset w11, AArch64CC
10476// cmp w9, w11
10477// cset w0, eq
10478// ret
10479//
10480// Since the above function shows when the outputs are equivalent it defines
10481// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10482// would be expensive to run during compiles. The equations below were written
10483// in a test harness that confirmed they gave equivalent outputs to the above
10484// for all inputs function, so they can be used determine if the removal is
10485// legal instead.
10486//
10487// isEquivalentMaskless() is the code for testing if the AND can be removed
10488// factored out of the DAG recognition as the DAG can take several forms.
10489
David Majnemere61e4bf2016-06-21 05:10:24 +000010490static bool isEquivalentMaskless(unsigned CC, unsigned width,
10491 ISD::LoadExtType ExtType, int AddConstant,
10492 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010493 // By being careful about our equations and only writing the in term
10494 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10495 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010496 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010497
10498 // For the purposes of these comparisons sign extending the type is
10499 // equivalent to zero extending the add and displacing it by half the integer
10500 // width. Provided we are careful and make sure our equations are valid over
10501 // the whole range we can just adjust the input and avoid writing equations
10502 // for sign extended inputs.
10503 if (ExtType == ISD::SEXTLOAD)
10504 AddConstant -= (1 << (width-1));
10505
10506 switch(CC) {
10507 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010508 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010509 if ((AddConstant == 0) ||
10510 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10511 (AddConstant >= 0 && CompConstant < 0) ||
10512 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10513 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010514 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010515 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010516 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010517 if ((AddConstant == 0) ||
10518 (AddConstant >= 0 && CompConstant <= 0) ||
10519 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10520 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010521 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010522 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010523 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010524 if ((AddConstant >= 0 && CompConstant < 0) ||
10525 (AddConstant <= 0 && CompConstant >= -1 &&
10526 CompConstant < AddConstant + MaxUInt))
10527 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010528 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010529 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010530 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010531 if ((AddConstant == 0) ||
10532 (AddConstant > 0 && CompConstant <= 0) ||
10533 (AddConstant < 0 && CompConstant <= AddConstant))
10534 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010535 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010536 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010537 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010538 if ((AddConstant >= 0 && CompConstant <= 0) ||
10539 (AddConstant <= 0 && CompConstant >= 0 &&
10540 CompConstant <= AddConstant + MaxUInt))
10541 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010542 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010543 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010544 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010545 if ((AddConstant > 0 && CompConstant < 0) ||
10546 (AddConstant < 0 && CompConstant >= 0 &&
10547 CompConstant < AddConstant + MaxUInt) ||
10548 (AddConstant >= 0 && CompConstant >= 0 &&
10549 CompConstant >= AddConstant) ||
10550 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010551 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010552 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010553 case AArch64CC::VS:
10554 case AArch64CC::VC:
10555 case AArch64CC::AL:
10556 case AArch64CC::NV:
10557 return true;
10558 case AArch64CC::Invalid:
10559 break;
10560 }
10561
10562 return false;
10563}
10564
10565static
10566SDValue performCONDCombine(SDNode *N,
10567 TargetLowering::DAGCombinerInfo &DCI,
10568 SelectionDAG &DAG, unsigned CCIndex,
10569 unsigned CmpIndex) {
10570 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10571 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10572 unsigned CondOpcode = SubsNode->getOpcode();
10573
10574 if (CondOpcode != AArch64ISD::SUBS)
10575 return SDValue();
10576
10577 // There is a SUBS feeding this condition. Is it fed by a mask we can
10578 // use?
10579
10580 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10581 unsigned MaskBits = 0;
10582
10583 if (AndNode->getOpcode() != ISD::AND)
10584 return SDValue();
10585
10586 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10587 uint32_t CNV = CN->getZExtValue();
10588 if (CNV == 255)
10589 MaskBits = 8;
10590 else if (CNV == 65535)
10591 MaskBits = 16;
10592 }
10593
10594 if (!MaskBits)
10595 return SDValue();
10596
10597 SDValue AddValue = AndNode->getOperand(0);
10598
10599 if (AddValue.getOpcode() != ISD::ADD)
10600 return SDValue();
10601
10602 // The basic dag structure is correct, grab the inputs and validate them.
10603
10604 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10605 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10606 SDValue SubsInputValue = SubsNode->getOperand(1);
10607
10608 // The mask is present and the provenance of all the values is a smaller type,
10609 // lets see if the mask is superfluous.
10610
10611 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10612 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10613 return SDValue();
10614
10615 ISD::LoadExtType ExtType;
10616
10617 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10618 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10619 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10620 return SDValue();
10621
10622 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10623 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10624 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10625 return SDValue();
10626
10627 // The AND is not necessary, remove it.
10628
10629 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10630 SubsNode->getValueType(1));
10631 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10632
10633 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10634 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10635
10636 return SDValue(N, 0);
10637}
10638
Tim Northover3b0846e2014-05-24 12:50:23 +000010639// Optimize compare with zero and branch.
10640static SDValue performBRCONDCombine(SDNode *N,
10641 TargetLowering::DAGCombinerInfo &DCI,
10642 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010643 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010644 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010645 SDValue Chain = N->getOperand(0);
10646 SDValue Dest = N->getOperand(1);
10647 SDValue CCVal = N->getOperand(2);
10648 SDValue Cmp = N->getOperand(3);
10649
10650 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10651 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10652 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10653 return SDValue();
10654
10655 unsigned CmpOpc = Cmp.getOpcode();
10656 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10657 return SDValue();
10658
10659 // Only attempt folding if there is only one use of the flag and no use of the
10660 // value.
10661 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10662 return SDValue();
10663
10664 SDValue LHS = Cmp.getOperand(0);
10665 SDValue RHS = Cmp.getOperand(1);
10666
10667 assert(LHS.getValueType() == RHS.getValueType() &&
10668 "Expected the value type to be the same for both operands!");
10669 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10670 return SDValue();
10671
Artyom Skrobov314ee042015-11-25 19:41:11 +000010672 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010673 std::swap(LHS, RHS);
10674
Artyom Skrobov314ee042015-11-25 19:41:11 +000010675 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010676 return SDValue();
10677
10678 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10679 LHS.getOpcode() == ISD::SRL)
10680 return SDValue();
10681
10682 // Fold the compare into the branch instruction.
10683 SDValue BR;
10684 if (CC == AArch64CC::EQ)
10685 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10686 else
10687 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10688
10689 // Do not add new nodes to DAG combiner worklist.
10690 DCI.CombineTo(N, BR, false);
10691
10692 return SDValue();
10693}
10694
Geoff Berry9e934b02016-01-04 18:55:47 +000010695// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10696// as well as whether the test should be inverted. This code is required to
10697// catch these cases (as opposed to standard dag combines) because
10698// AArch64ISD::TBZ is matched during legalization.
10699static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10700 SelectionDAG &DAG) {
10701
10702 if (!Op->hasOneUse())
10703 return Op;
10704
10705 // We don't handle undef/constant-fold cases below, as they should have
10706 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10707 // etc.)
10708
10709 // (tbz (trunc x), b) -> (tbz x, b)
10710 // This case is just here to enable more of the below cases to be caught.
10711 if (Op->getOpcode() == ISD::TRUNCATE &&
10712 Bit < Op->getValueType(0).getSizeInBits()) {
10713 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10714 }
10715
10716 if (Op->getNumOperands() != 2)
10717 return Op;
10718
10719 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10720 if (!C)
10721 return Op;
10722
10723 switch (Op->getOpcode()) {
10724 default:
10725 return Op;
10726
10727 // (tbz (and x, m), b) -> (tbz x, b)
10728 case ISD::AND:
10729 if ((C->getZExtValue() >> Bit) & 1)
10730 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10731 return Op;
10732
10733 // (tbz (shl x, c), b) -> (tbz x, b-c)
10734 case ISD::SHL:
10735 if (C->getZExtValue() <= Bit &&
10736 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10737 Bit = Bit - C->getZExtValue();
10738 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10739 }
10740 return Op;
10741
10742 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10743 case ISD::SRA:
10744 Bit = Bit + C->getZExtValue();
10745 if (Bit >= Op->getValueType(0).getSizeInBits())
10746 Bit = Op->getValueType(0).getSizeInBits() - 1;
10747 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10748
10749 // (tbz (srl x, c), b) -> (tbz x, b+c)
10750 case ISD::SRL:
10751 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10752 Bit = Bit + C->getZExtValue();
10753 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10754 }
10755 return Op;
10756
10757 // (tbz (xor x, -1), b) -> (tbnz x, b)
10758 case ISD::XOR:
10759 if ((C->getZExtValue() >> Bit) & 1)
10760 Invert = !Invert;
10761 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10762 }
10763}
10764
10765// Optimize test single bit zero/non-zero and branch.
10766static SDValue performTBZCombine(SDNode *N,
10767 TargetLowering::DAGCombinerInfo &DCI,
10768 SelectionDAG &DAG) {
10769 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10770 bool Invert = false;
10771 SDValue TestSrc = N->getOperand(1);
10772 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10773
10774 if (TestSrc == NewTestSrc)
10775 return SDValue();
10776
10777 unsigned NewOpc = N->getOpcode();
10778 if (Invert) {
10779 if (NewOpc == AArch64ISD::TBZ)
10780 NewOpc = AArch64ISD::TBNZ;
10781 else {
10782 assert(NewOpc == AArch64ISD::TBNZ);
10783 NewOpc = AArch64ISD::TBZ;
10784 }
10785 }
10786
10787 SDLoc DL(N);
10788 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10789 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10790}
10791
Tim Northover3b0846e2014-05-24 12:50:23 +000010792// vselect (v1i1 setcc) ->
10793// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10794// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10795// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10796// such VSELECT.
10797static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10798 SDValue N0 = N->getOperand(0);
10799 EVT CCVT = N0.getValueType();
10800
10801 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10802 CCVT.getVectorElementType() != MVT::i1)
10803 return SDValue();
10804
10805 EVT ResVT = N->getValueType(0);
10806 EVT CmpVT = N0.getOperand(0).getValueType();
10807 // Only combine when the result type is of the same size as the compared
10808 // operands.
10809 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10810 return SDValue();
10811
10812 SDValue IfTrue = N->getOperand(1);
10813 SDValue IfFalse = N->getOperand(2);
10814 SDValue SetCC =
10815 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10816 N0.getOperand(0), N0.getOperand(1),
10817 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10818 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10819 IfTrue, IfFalse);
10820}
10821
10822/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10823/// the compare-mask instructions rather than going via NZCV, even if LHS and
10824/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10825/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010826static SDValue performSelectCombine(SDNode *N,
10827 TargetLowering::DAGCombinerInfo &DCI) {
10828 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010829 SDValue N0 = N->getOperand(0);
10830 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010831
Ahmed Bougachac004c602015-04-27 21:43:12 +000010832 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010833 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010834
Ahmed Bougachac004c602015-04-27 21:43:12 +000010835 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10836 // scalar SetCCResultType. We also don't expect vectors, because we assume
10837 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10838 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10839 "Scalar-SETCC feeding SELECT has unexpected result type!");
10840
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010841 // If NumMaskElts == 0, the comparison is larger than select result. The
10842 // largest real NEON comparison is 64-bits per lane, which means the result is
10843 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010844 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000010845
10846 // Don't try to do this optimization when the setcc itself has i1 operands.
10847 // There are no legal vectors of i1, so this would be pointless.
10848 if (SrcVT == MVT::i1)
10849 return SDValue();
10850
Tim Northover3c0915e2014-08-29 15:34:58 +000010851 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010852 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000010853 return SDValue();
10854
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010855 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010856 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10857
Ahmed Bougacha89bba612015-04-27 21:01:20 +000010858 // Also bail out if the vector CCVT isn't the same size as ResVT.
10859 // This can happen if the SETCC operand size doesn't divide the ResVT size
10860 // (e.g., f64 vs v3f32).
10861 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10862 return SDValue();
10863
Ahmed Bougachac004c602015-04-27 21:43:12 +000010864 // Make sure we didn't create illegal types, if we're not supposed to.
10865 assert(DCI.isBeforeLegalize() ||
10866 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10867
Tim Northover3b0846e2014-05-24 12:50:23 +000010868 // First perform a vector comparison, where lane 0 is the one we're interested
10869 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010870 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010871 SDValue LHS =
10872 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10873 SDValue RHS =
10874 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10875 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10876
10877 // Now duplicate the comparison mask we want across all other lanes.
10878 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000010879 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010880 Mask = DAG.getNode(ISD::BITCAST, DL,
10881 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000010882
10883 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10884}
10885
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010886/// Get rid of unnecessary NVCASTs (that don't change the type).
10887static SDValue performNVCASTCombine(SDNode *N) {
10888 if (N->getValueType(0) == N->getOperand(0).getValueType())
10889 return N->getOperand(0);
10890
10891 return SDValue();
10892}
10893
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000010894// If all users of the globaladdr are of the form (globaladdr + constant), find
10895// the smallest constant, fold it into the globaladdr's offset and rewrite the
10896// globaladdr as (globaladdr + constant) - constant.
10897static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
10898 const AArch64Subtarget *Subtarget,
10899 const TargetMachine &TM) {
10900 auto *GN = dyn_cast<GlobalAddressSDNode>(N);
10901 if (!GN || Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
10902 AArch64II::MO_NO_FLAG)
10903 return SDValue();
10904
10905 uint64_t MinOffset = -1ull;
10906 for (SDNode *N : GN->uses()) {
10907 if (N->getOpcode() != ISD::ADD)
10908 return SDValue();
10909 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
10910 if (!C)
10911 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10912 if (!C)
10913 return SDValue();
10914 MinOffset = std::min(MinOffset, C->getZExtValue());
10915 }
10916 uint64_t Offset = MinOffset + GN->getOffset();
10917
10918 // Require that the new offset is larger than the existing one. Otherwise, we
10919 // can end up oscillating between two possible DAGs, for example,
10920 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
10921 if (Offset <= uint64_t(GN->getOffset()))
10922 return SDValue();
10923
10924 // Check whether folding this offset is legal. It must not go out of bounds of
10925 // the referenced object to avoid violating the code model, and must be
10926 // smaller than 2^21 because this is the largest offset expressible in all
10927 // object formats.
10928 //
10929 // This check also prevents us from folding negative offsets, which will end
10930 // up being treated in the same way as large positive ones. They could also
10931 // cause code model violations, and aren't really common enough to matter.
10932 if (Offset >= (1 << 21))
10933 return SDValue();
10934
10935 const GlobalValue *GV = GN->getGlobal();
10936 Type *T = GV->getValueType();
10937 if (!T->isSized() ||
10938 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
10939 return SDValue();
10940
10941 SDLoc DL(GN);
10942 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
10943 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
10944 DAG.getConstant(MinOffset, DL, MVT::i64));
10945}
10946
Tim Northover3b0846e2014-05-24 12:50:23 +000010947SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10948 DAGCombinerInfo &DCI) const {
10949 SelectionDAG &DAG = DCI.DAG;
10950 switch (N->getOpcode()) {
10951 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000010952 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000010953 break;
10954 case ISD::ADD:
10955 case ISD::SUB:
10956 return performAddSubLongCombine(N, DCI, DAG);
10957 case ISD::XOR:
10958 return performXorCombine(N, DAG, DCI, Subtarget);
10959 case ISD::MUL:
10960 return performMulCombine(N, DAG, DCI, Subtarget);
10961 case ISD::SINT_TO_FP:
10962 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000010963 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000010964 case ISD::FP_TO_SINT:
10965 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000010966 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000010967 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000010968 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010969 case ISD::OR:
10970 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000010971 case ISD::SRL:
10972 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010973 case ISD::INTRINSIC_WO_CHAIN:
10974 return performIntrinsicCombine(N, DCI, Subtarget);
10975 case ISD::ANY_EXTEND:
10976 case ISD::ZERO_EXTEND:
10977 case ISD::SIGN_EXTEND:
10978 return performExtendCombine(N, DCI, DAG);
10979 case ISD::BITCAST:
10980 return performBitcastCombine(N, DCI, DAG);
10981 case ISD::CONCAT_VECTORS:
10982 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000010983 case ISD::SELECT:
10984 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010985 case ISD::VSELECT:
10986 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000010987 case ISD::LOAD:
10988 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10989 return SDValue(N, 0);
10990 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000010991 case ISD::STORE:
10992 return performSTORECombine(N, DCI, DAG, Subtarget);
10993 case AArch64ISD::BRCOND:
10994 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000010995 case AArch64ISD::TBNZ:
10996 case AArch64ISD::TBZ:
10997 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010998 case AArch64ISD::CSEL:
10999 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011000 case AArch64ISD::DUP:
11001 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011002 case AArch64ISD::NVCAST:
11003 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011004 case ISD::INSERT_VECTOR_ELT:
11005 return performPostLD1Combine(N, DCI, true);
11006 case ISD::INTRINSIC_VOID:
11007 case ISD::INTRINSIC_W_CHAIN:
11008 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11009 case Intrinsic::aarch64_neon_ld2:
11010 case Intrinsic::aarch64_neon_ld3:
11011 case Intrinsic::aarch64_neon_ld4:
11012 case Intrinsic::aarch64_neon_ld1x2:
11013 case Intrinsic::aarch64_neon_ld1x3:
11014 case Intrinsic::aarch64_neon_ld1x4:
11015 case Intrinsic::aarch64_neon_ld2lane:
11016 case Intrinsic::aarch64_neon_ld3lane:
11017 case Intrinsic::aarch64_neon_ld4lane:
11018 case Intrinsic::aarch64_neon_ld2r:
11019 case Intrinsic::aarch64_neon_ld3r:
11020 case Intrinsic::aarch64_neon_ld4r:
11021 case Intrinsic::aarch64_neon_st2:
11022 case Intrinsic::aarch64_neon_st3:
11023 case Intrinsic::aarch64_neon_st4:
11024 case Intrinsic::aarch64_neon_st1x2:
11025 case Intrinsic::aarch64_neon_st1x3:
11026 case Intrinsic::aarch64_neon_st1x4:
11027 case Intrinsic::aarch64_neon_st2lane:
11028 case Intrinsic::aarch64_neon_st3lane:
11029 case Intrinsic::aarch64_neon_st4lane:
11030 return performNEONPostLDSTCombine(N, DCI, DAG);
11031 default:
11032 break;
11033 }
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011034 case ISD::GlobalAddress:
11035 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011036 }
11037 return SDValue();
11038}
11039
11040// Check if the return value is used as only a return value, as otherwise
11041// we can't perform a tail-call. In particular, we need to check for
11042// target ISD nodes that are returns and any other "odd" constructs
11043// that the generic analysis code won't necessarily catch.
11044bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11045 SDValue &Chain) const {
11046 if (N->getNumValues() != 1)
11047 return false;
11048 if (!N->hasNUsesOfValue(1, 0))
11049 return false;
11050
11051 SDValue TCChain = Chain;
11052 SDNode *Copy = *N->use_begin();
11053 if (Copy->getOpcode() == ISD::CopyToReg) {
11054 // If the copy has a glue operand, we conservatively assume it isn't safe to
11055 // perform a tail call.
11056 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11057 MVT::Glue)
11058 return false;
11059 TCChain = Copy->getOperand(0);
11060 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11061 return false;
11062
11063 bool HasRet = false;
11064 for (SDNode *Node : Copy->uses()) {
11065 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11066 return false;
11067 HasRet = true;
11068 }
11069
11070 if (!HasRet)
11071 return false;
11072
11073 Chain = TCChain;
11074 return true;
11075}
11076
11077// Return whether the an instruction can potentially be optimized to a tail
11078// call. This will cause the optimizers to attempt to move, or duplicate,
11079// return instructions to help enable tail call optimizations for this
11080// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011081bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011082 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011083}
11084
11085bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11086 SDValue &Offset,
11087 ISD::MemIndexedMode &AM,
11088 bool &IsInc,
11089 SelectionDAG &DAG) const {
11090 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11091 return false;
11092
11093 Base = Op->getOperand(0);
11094 // All of the indexed addressing mode instructions take a signed
11095 // 9 bit immediate offset.
11096 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011097 int64_t RHSC = RHS->getSExtValue();
11098 if (Op->getOpcode() == ISD::SUB)
11099 RHSC = -(uint64_t)RHSC;
11100 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011101 return false;
11102 IsInc = (Op->getOpcode() == ISD::ADD);
11103 Offset = Op->getOperand(1);
11104 return true;
11105 }
11106 return false;
11107}
11108
11109bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11110 SDValue &Offset,
11111 ISD::MemIndexedMode &AM,
11112 SelectionDAG &DAG) const {
11113 EVT VT;
11114 SDValue Ptr;
11115 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11116 VT = LD->getMemoryVT();
11117 Ptr = LD->getBasePtr();
11118 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11119 VT = ST->getMemoryVT();
11120 Ptr = ST->getBasePtr();
11121 } else
11122 return false;
11123
11124 bool IsInc;
11125 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11126 return false;
11127 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11128 return true;
11129}
11130
11131bool AArch64TargetLowering::getPostIndexedAddressParts(
11132 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11133 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11134 EVT VT;
11135 SDValue Ptr;
11136 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11137 VT = LD->getMemoryVT();
11138 Ptr = LD->getBasePtr();
11139 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11140 VT = ST->getMemoryVT();
11141 Ptr = ST->getBasePtr();
11142 } else
11143 return false;
11144
11145 bool IsInc;
11146 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11147 return false;
11148 // Post-indexing updates the base, so it's not a valid transform
11149 // if that's not the same as the load's pointer.
11150 if (Ptr != Base)
11151 return false;
11152 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11153 return true;
11154}
11155
Tim Northoverf8bfe212014-07-18 13:07:05 +000011156static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11157 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011158 SDLoc DL(N);
11159 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011160
11161 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11162 return;
11163
Tim Northoverf8bfe212014-07-18 13:07:05 +000011164 Op = SDValue(
11165 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11166 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011167 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011168 0);
11169 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11170 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11171}
11172
Charlie Turner434d4592015-10-16 15:38:25 +000011173static void ReplaceReductionResults(SDNode *N,
11174 SmallVectorImpl<SDValue> &Results,
11175 SelectionDAG &DAG, unsigned InterOp,
11176 unsigned AcrossOp) {
11177 EVT LoVT, HiVT;
11178 SDValue Lo, Hi;
11179 SDLoc dl(N);
11180 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11181 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11182 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11183 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11184 Results.push_back(SplitVal);
11185}
11186
Tim Northover2f32e7f2016-08-04 19:32:28 +000011187static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11188 SDLoc DL(N);
11189 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11190 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11191 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11192 DAG.getConstant(64, DL, MVT::i64)));
11193 return std::make_pair(Lo, Hi);
11194}
11195
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011196// Create an even/odd pair of X registers holding integer value V.
11197static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11198 SDLoc dl(V.getNode());
11199 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11200 SDValue VHi = DAG.getAnyExtOrTrunc(
11201 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11202 dl, MVT::i64);
11203 if (DAG.getDataLayout().isBigEndian())
11204 std::swap (VLo, VHi);
11205 SDValue RegClass =
11206 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11207 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11208 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11209 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11210 return SDValue(
11211 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11212}
11213
Tim Northovercdf15292016-04-14 17:03:29 +000011214static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011215 SmallVectorImpl<SDValue> &Results,
11216 SelectionDAG &DAG,
11217 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011218 assert(N->getValueType(0) == MVT::i128 &&
11219 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011220
11221 if (Subtarget->hasLSE()) {
11222 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11223 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11224 SDValue Ops[] = {
11225 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11226 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11227 N->getOperand(1), // Ptr
11228 N->getOperand(0), // Chain in
11229 };
11230
Chandler Carruth66654b72018-08-14 23:30:32 +000011231 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011232
11233 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011234 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011235 case AtomicOrdering::Monotonic:
11236 Opcode = AArch64::CASPX;
11237 break;
11238 case AtomicOrdering::Acquire:
11239 Opcode = AArch64::CASPAX;
11240 break;
11241 case AtomicOrdering::Release:
11242 Opcode = AArch64::CASPLX;
11243 break;
11244 case AtomicOrdering::AcquireRelease:
11245 case AtomicOrdering::SequentiallyConsistent:
11246 Opcode = AArch64::CASPALX;
11247 break;
11248 default:
11249 llvm_unreachable("Unexpected ordering!");
11250 }
11251
11252 MachineSDNode *CmpSwap = DAG.getMachineNode(
11253 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011254 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011255
11256 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11257 if (DAG.getDataLayout().isBigEndian())
11258 std::swap(SubReg1, SubReg2);
11259 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11260 SDValue(CmpSwap, 0)));
11261 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11262 SDValue(CmpSwap, 0)));
11263 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11264 return;
11265 }
11266
Tim Northover2f32e7f2016-08-04 19:32:28 +000011267 auto Desired = splitInt128(N->getOperand(2), DAG);
11268 auto New = splitInt128(N->getOperand(3), DAG);
11269 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11270 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011271 SDNode *CmpSwap = DAG.getMachineNode(
11272 AArch64::CMP_SWAP_128, SDLoc(N),
11273 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11274
Chandler Carruth66654b72018-08-14 23:30:32 +000011275 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11276 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011277
11278 Results.push_back(SDValue(CmpSwap, 0));
11279 Results.push_back(SDValue(CmpSwap, 1));
11280 Results.push_back(SDValue(CmpSwap, 3));
11281}
11282
Tim Northover3b0846e2014-05-24 12:50:23 +000011283void AArch64TargetLowering::ReplaceNodeResults(
11284 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11285 switch (N->getOpcode()) {
11286 default:
11287 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011288 case ISD::BITCAST:
11289 ReplaceBITCASTResults(N, Results, DAG);
11290 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011291 case ISD::VECREDUCE_ADD:
11292 case ISD::VECREDUCE_SMAX:
11293 case ISD::VECREDUCE_SMIN:
11294 case ISD::VECREDUCE_UMAX:
11295 case ISD::VECREDUCE_UMIN:
11296 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11297 return;
11298
Charlie Turner434d4592015-10-16 15:38:25 +000011299 case AArch64ISD::SADDV:
11300 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11301 return;
11302 case AArch64ISD::UADDV:
11303 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11304 return;
11305 case AArch64ISD::SMINV:
11306 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11307 return;
11308 case AArch64ISD::UMINV:
11309 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11310 return;
11311 case AArch64ISD::SMAXV:
11312 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11313 return;
11314 case AArch64ISD::UMAXV:
11315 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11316 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011317 case ISD::FP_TO_UINT:
11318 case ISD::FP_TO_SINT:
11319 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11320 // Let normal code take care of it by not adding anything to Results.
11321 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011322 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011323 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011324 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011325 }
11326}
11327
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011328bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011329 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11330 return TargetLowering::useLoadStackGuardNode();
11331 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011332}
11333
Sanjay Patel1dd15592015-07-28 23:05:48 +000011334unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011335 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11336 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011337 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011338}
11339
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011340TargetLoweringBase::LegalizeTypeAction
11341AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
11342 MVT SVT = VT.getSimpleVT();
11343 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11344 // v4i16, v2i32 instead of to promote.
11345 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
11346 || SVT == MVT::v1f32)
11347 return TypeWidenVector;
11348
11349 return TargetLoweringBase::getPreferredVectorAction(VT);
11350}
11351
Robin Morisseted3d48f2014-09-03 21:29:59 +000011352// Loads and stores less than 128-bits are already atomic; ones above that
11353// are doomed anyway, so defer to the default libcall and blame the OS when
11354// things go wrong.
11355bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11356 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11357 return Size == 128;
11358}
11359
11360// Loads and stores less than 128-bits are already atomic; ones above that
11361// are doomed anyway, so defer to the default libcall and blame the OS when
11362// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011363TargetLowering::AtomicExpansionKind
11364AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011365 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011366 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011367}
11368
11369// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011370TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011371AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011372 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011373 if (Size > 128) return AtomicExpansionKind::None;
11374 // Nand not supported in LSE.
11375 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011376 // Leave 128 bits to LLSC.
11377 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011378}
11379
Ahmed Bougacha52468672015-09-11 17:08:28 +000011380bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11381 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011382 // If subtarget has LSE, leave cmpxchg intact for codegen.
11383 if (Subtarget->hasLSE()) return false;
Tim Northovercdf15292016-04-14 17:03:29 +000011384 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11385 // implement cmpxchg without spilling. If the address being exchanged is also
11386 // on the stack and close enough to the spill slot, this can lead to a
11387 // situation where the monitor always gets cleared and the atomic operation
11388 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11389 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000011390}
11391
Tim Northover3b0846e2014-05-24 12:50:23 +000011392Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11393 AtomicOrdering Ord) const {
11394 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11395 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011396 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011397
11398 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11399 // intrinsic must return {i64, i64} and we have to recombine them into a
11400 // single i128 here.
11401 if (ValTy->getPrimitiveSizeInBits() == 128) {
11402 Intrinsic::ID Int =
11403 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011404 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011405
11406 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11407 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11408
11409 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11410 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11411 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11412 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11413 return Builder.CreateOr(
11414 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11415 }
11416
11417 Type *Tys[] = { Addr->getType() };
11418 Intrinsic::ID Int =
11419 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011420 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011421
11422 return Builder.CreateTruncOrBitCast(
11423 Builder.CreateCall(Ldxr, Addr),
11424 cast<PointerType>(Addr->getType())->getElementType());
11425}
11426
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011427void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11428 IRBuilder<> &Builder) const {
11429 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011430 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011431}
11432
Tim Northover3b0846e2014-05-24 12:50:23 +000011433Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11434 Value *Val, Value *Addr,
11435 AtomicOrdering Ord) const {
11436 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011437 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011438
11439 // Since the intrinsics must have legal type, the i128 intrinsics take two
11440 // parameters: "i64, i64". We must marshal Val into the appropriate form
11441 // before the call.
11442 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11443 Intrinsic::ID Int =
11444 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11445 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11446 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11447
11448 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11449 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11450 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011451 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011452 }
11453
11454 Intrinsic::ID Int =
11455 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11456 Type *Tys[] = { Addr->getType() };
11457 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11458
David Blaikieff6409d2015-05-18 22:13:54 +000011459 return Builder.CreateCall(Stxr,
11460 {Builder.CreateZExtOrBitCast(
11461 Val, Stxr->getFunctionType()->getParamType(0)),
11462 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011463}
Tim Northover3c55cca2014-11-27 21:02:42 +000011464
11465bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11466 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11467 return Ty->isArrayTy();
11468}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011469
11470bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11471 EVT) const {
11472 return false;
11473}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011474
Petr Hoseka7d59162017-02-24 03:10:10 +000011475static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011476 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11477 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011478 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011479 return IRB.CreatePointerCast(
Petr Hoseka7d59162017-02-24 03:10:10 +000011480 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011481 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
11482}
11483
Petr Hoseka7d59162017-02-24 03:10:10 +000011484Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11485 // Android provides a fixed TLS slot for the stack cookie. See the definition
11486 // of TLS_SLOT_STACK_GUARD in
11487 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11488 if (Subtarget->isTargetAndroid())
11489 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011490
Petr Hoseka7d59162017-02-24 03:10:10 +000011491 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011492 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011493 if (Subtarget->isTargetFuchsia())
11494 return UseTlsOffset(IRB, -0x10);
11495
11496 return TargetLowering::getIRStackGuard(IRB);
11497}
11498
11499Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011500 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11501 // definition of TLS_SLOT_SAFESTACK in
11502 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011503 if (Subtarget->isTargetAndroid())
11504 return UseTlsOffset(IRB, 0x48);
11505
11506 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011507 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011508 if (Subtarget->isTargetFuchsia())
11509 return UseTlsOffset(IRB, -0x8);
11510
11511 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011512}
Manman Rencbe4f942015-12-16 21:04:19 +000011513
Geoff Berry5d534b62017-02-21 18:53:14 +000011514bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11515 const Instruction &AndI) const {
11516 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11517 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11518 // may be beneficial to sink in other cases, but we would have to check that
11519 // the cmp would not get folded into the br to form a cbz for these to be
11520 // beneficial.
11521 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11522 if (!Mask)
11523 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011524 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011525}
11526
Manman Rencbe4f942015-12-16 21:04:19 +000011527void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11528 // Update IsSplitCSR in AArch64unctionInfo.
11529 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11530 AFI->setIsSplitCSR(true);
11531}
11532
11533void AArch64TargetLowering::insertCopiesSplitCSR(
11534 MachineBasicBlock *Entry,
11535 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11536 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11537 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11538 if (!IStart)
11539 return;
11540
11541 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11542 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011543 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011544 for (const MCPhysReg *I = IStart; *I; ++I) {
11545 const TargetRegisterClass *RC = nullptr;
11546 if (AArch64::GPR64RegClass.contains(*I))
11547 RC = &AArch64::GPR64RegClass;
11548 else if (AArch64::FPR64RegClass.contains(*I))
11549 RC = &AArch64::FPR64RegClass;
11550 else
11551 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11552
11553 unsigned NewVR = MRI->createVirtualRegister(RC);
11554 // Create copy from CSR to a virtual register.
11555 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11556 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11557 // nounwind. If we want to generalize this later, we may need to emit
11558 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011559 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011560 Attribute::NoUnwind) &&
11561 "Function should be nounwind in insertCopiesSplitCSR!");
11562 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011563 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011564 .addReg(*I);
11565
Manman Ren4632e8e2016-01-15 20:13:28 +000011566 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011567 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011568 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11569 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011570 .addReg(NewVR);
11571 }
11572}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011573
Reid Klecknerb5180542017-03-21 16:57:19 +000011574bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011575 // Integer division on AArch64 is expensive. However, when aggressively
11576 // optimizing for code size, we prefer to use a div instruction, as it is
11577 // usually smaller than the alternative sequence.
11578 // The exception to this is vector division. Since AArch64 doesn't have vector
11579 // integer division, leaving the division as-is is a loss even in terms of
11580 // size, because it will have to be scalarized, while the alternative code
11581 // sequence can be performed in vector form.
11582 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011583 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011584 return OptSize && !VT.isVector();
11585}
Tim Northoverf19d4672017-02-08 17:57:20 +000011586
Joel Jones07150922018-01-25 21:55:39 +000011587bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11588 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11589}
11590
Tim Northoverf19d4672017-02-08 17:57:20 +000011591unsigned
11592AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011593 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011594 return getPointerTy(DL).getSizeInBits();
11595
11596 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11597}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011598
11599void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11600 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11601 TargetLoweringBase::finalizeLowering(MF);
11602}