Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Target/ARM/ARMISelLowering.cpp
Warning:line 2679, column 20
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ARMISelLowering.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Target/ARM -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Target/ARM -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility=hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Target/ARM/ARMISelLowering.cpp
1//===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that ARM uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARMISelLowering.h"
15#include "ARMBaseInstrInfo.h"
16#include "ARMBaseRegisterInfo.h"
17#include "ARMCallingConv.h"
18#include "ARMConstantPoolValue.h"
19#include "ARMMachineFunctionInfo.h"
20#include "ARMPerfectShuffle.h"
21#include "ARMRegisterInfo.h"
22#include "ARMSelectionDAGInfo.h"
23#include "ARMSubtarget.h"
24#include "ARMTargetTransformInfo.h"
25#include "MCTargetDesc/ARMAddressingModes.h"
26#include "MCTargetDesc/ARMBaseInfo.h"
27#include "Utils/ARMBaseInfo.h"
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ADT/StringSwitch.h"
40#include "llvm/ADT/Triple.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/Analysis/VectorUtils.h"
43#include "llvm/CodeGen/CallingConvLower.h"
44#include "llvm/CodeGen/ISDOpcodes.h"
45#include "llvm/CodeGen/IntrinsicLowering.h"
46#include "llvm/CodeGen/MachineBasicBlock.h"
47#include "llvm/CodeGen/MachineConstantPool.h"
48#include "llvm/CodeGen/MachineFrameInfo.h"
49#include "llvm/CodeGen/MachineFunction.h"
50#include "llvm/CodeGen/MachineInstr.h"
51#include "llvm/CodeGen/MachineInstrBuilder.h"
52#include "llvm/CodeGen/MachineJumpTableInfo.h"
53#include "llvm/CodeGen/MachineMemOperand.h"
54#include "llvm/CodeGen/MachineOperand.h"
55#include "llvm/CodeGen/MachineRegisterInfo.h"
56#include "llvm/CodeGen/RuntimeLibcalls.h"
57#include "llvm/CodeGen/SelectionDAG.h"
58#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
59#include "llvm/CodeGen/SelectionDAGNodes.h"
60#include "llvm/CodeGen/TargetInstrInfo.h"
61#include "llvm/CodeGen/TargetLowering.h"
62#include "llvm/CodeGen/TargetOpcodes.h"
63#include "llvm/CodeGen/TargetRegisterInfo.h"
64#include "llvm/CodeGen/TargetSubtargetInfo.h"
65#include "llvm/CodeGen/ValueTypes.h"
66#include "llvm/IR/Attributes.h"
67#include "llvm/IR/CallingConv.h"
68#include "llvm/IR/Constant.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/DebugLoc.h"
72#include "llvm/IR/DerivedTypes.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GlobalAlias.h"
75#include "llvm/IR/GlobalValue.h"
76#include "llvm/IR/GlobalVariable.h"
77#include "llvm/IR/IRBuilder.h"
78#include "llvm/IR/InlineAsm.h"
79#include "llvm/IR/Instruction.h"
80#include "llvm/IR/Instructions.h"
81#include "llvm/IR/IntrinsicInst.h"
82#include "llvm/IR/Intrinsics.h"
83#include "llvm/IR/IntrinsicsARM.h"
84#include "llvm/IR/Module.h"
85#include "llvm/IR/PatternMatch.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/User.h"
88#include "llvm/IR/Value.h"
89#include "llvm/MC/MCInstrDesc.h"
90#include "llvm/MC/MCInstrItineraries.h"
91#include "llvm/MC/MCRegisterInfo.h"
92#include "llvm/MC/MCSchedule.h"
93#include "llvm/Support/AtomicOrdering.h"
94#include "llvm/Support/BranchProbability.h"
95#include "llvm/Support/Casting.h"
96#include "llvm/Support/CodeGen.h"
97#include "llvm/Support/CommandLine.h"
98#include "llvm/Support/Compiler.h"
99#include "llvm/Support/Debug.h"
100#include "llvm/Support/ErrorHandling.h"
101#include "llvm/Support/KnownBits.h"
102#include "llvm/Support/MachineValueType.h"
103#include "llvm/Support/MathExtras.h"
104#include "llvm/Support/raw_ostream.h"
105#include "llvm/Target/TargetMachine.h"
106#include "llvm/Target/TargetOptions.h"
107#include <algorithm>
108#include <cassert>
109#include <cstdint>
110#include <cstdlib>
111#include <iterator>
112#include <limits>
113#include <string>
114#include <tuple>
115#include <utility>
116#include <vector>
117
118using namespace llvm;
119using namespace llvm::PatternMatch;
120
121#define DEBUG_TYPE"arm-isel" "arm-isel"
122
123STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"arm-isel", "NumTailCalls"
, "Number of tail calls"}
;
124STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt")static llvm::Statistic NumMovwMovt = {"arm-isel", "NumMovwMovt"
, "Number of GAs materialized with movw + movt"}
;
125STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments")static llvm::Statistic NumLoopByVals = {"arm-isel", "NumLoopByVals"
, "Number of loops generated for byval arguments"}
;
126STATISTIC(NumConstpoolPromoted,static llvm::Statistic NumConstpoolPromoted = {"arm-isel", "NumConstpoolPromoted"
, "Number of constants with their storage promoted into constant pools"
}
127 "Number of constants with their storage promoted into constant pools")static llvm::Statistic NumConstpoolPromoted = {"arm-isel", "NumConstpoolPromoted"
, "Number of constants with their storage promoted into constant pools"
}
;
128
129static cl::opt<bool>
130ARMInterworking("arm-interworking", cl::Hidden,
131 cl::desc("Enable / disable ARM interworking (for debugging only)"),
132 cl::init(true));
133
134static cl::opt<bool> EnableConstpoolPromotion(
135 "arm-promote-constant", cl::Hidden,
136 cl::desc("Enable / disable promotion of unnamed_addr constants into "
137 "constant pools"),
138 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
139static cl::opt<unsigned> ConstpoolPromotionMaxSize(
140 "arm-promote-constant-max-size", cl::Hidden,
141 cl::desc("Maximum size of constant to promote into a constant pool"),
142 cl::init(64));
143static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
144 "arm-promote-constant-max-total", cl::Hidden,
145 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
146 cl::init(128));
147
148cl::opt<unsigned>
149MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
150 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
151 cl::init(2));
152
153// The APCS parameter registers.
154static const MCPhysReg GPRArgRegs[] = {
155 ARM::R0, ARM::R1, ARM::R2, ARM::R3
156};
157
158void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
159 if (VT != PromotedLdStVT) {
160 setOperationAction(ISD::LOAD, VT, Promote);
161 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
162
163 setOperationAction(ISD::STORE, VT, Promote);
164 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
165 }
166
167 MVT ElemTy = VT.getVectorElementType();
168 if (ElemTy != MVT::f64)
169 setOperationAction(ISD::SETCC, VT, Custom);
170 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
171 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
172 if (ElemTy == MVT::i32) {
173 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
174 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
175 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
176 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
177 } else {
178 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
179 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
180 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
181 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
182 }
183 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
184 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
185 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
186 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
187 setOperationAction(ISD::SELECT, VT, Expand);
188 setOperationAction(ISD::SELECT_CC, VT, Expand);
189 setOperationAction(ISD::VSELECT, VT, Expand);
190 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
191 if (VT.isInteger()) {
192 setOperationAction(ISD::SHL, VT, Custom);
193 setOperationAction(ISD::SRA, VT, Custom);
194 setOperationAction(ISD::SRL, VT, Custom);
195 }
196
197 // Neon does not support vector divide/remainder operations.
198 setOperationAction(ISD::SDIV, VT, Expand);
199 setOperationAction(ISD::UDIV, VT, Expand);
200 setOperationAction(ISD::FDIV, VT, Expand);
201 setOperationAction(ISD::SREM, VT, Expand);
202 setOperationAction(ISD::UREM, VT, Expand);
203 setOperationAction(ISD::FREM, VT, Expand);
204 setOperationAction(ISD::SDIVREM, VT, Expand);
205 setOperationAction(ISD::UDIVREM, VT, Expand);
206
207 if (!VT.isFloatingPoint() &&
208 VT != MVT::v2i64 && VT != MVT::v1i64)
209 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
210 setOperationAction(Opcode, VT, Legal);
211 if (!VT.isFloatingPoint())
212 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
213 setOperationAction(Opcode, VT, Legal);
214}
215
216void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
217 addRegisterClass(VT, &ARM::DPRRegClass);
218 addTypeForNEON(VT, MVT::f64);
219}
220
221void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
222 addRegisterClass(VT, &ARM::DPairRegClass);
223 addTypeForNEON(VT, MVT::v2f64);
224}
225
226void ARMTargetLowering::setAllExpand(MVT VT) {
227 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
228 setOperationAction(Opc, VT, Expand);
229
230 // We support these really simple operations even on types where all
231 // the actual arithmetic has to be broken down into simpler
232 // operations or turned into library calls.
233 setOperationAction(ISD::BITCAST, VT, Legal);
234 setOperationAction(ISD::LOAD, VT, Legal);
235 setOperationAction(ISD::STORE, VT, Legal);
236 setOperationAction(ISD::UNDEF, VT, Legal);
237}
238
239void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
240 LegalizeAction Action) {
241 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
242 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
243 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
244}
245
246void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
247 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
248
249 for (auto VT : IntTypes) {
250 addRegisterClass(VT, &ARM::MQPRRegClass);
251 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
252 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
253 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
254 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
255 setOperationAction(ISD::SHL, VT, Custom);
256 setOperationAction(ISD::SRA, VT, Custom);
257 setOperationAction(ISD::SRL, VT, Custom);
258 setOperationAction(ISD::SMIN, VT, Legal);
259 setOperationAction(ISD::SMAX, VT, Legal);
260 setOperationAction(ISD::UMIN, VT, Legal);
261 setOperationAction(ISD::UMAX, VT, Legal);
262 setOperationAction(ISD::ABS, VT, Legal);
263 setOperationAction(ISD::SETCC, VT, Custom);
264 setOperationAction(ISD::MLOAD, VT, Custom);
265 setOperationAction(ISD::MSTORE, VT, Legal);
266 setOperationAction(ISD::CTLZ, VT, Legal);
267 setOperationAction(ISD::CTTZ, VT, Custom);
268 setOperationAction(ISD::BITREVERSE, VT, Legal);
269 setOperationAction(ISD::BSWAP, VT, Legal);
270 setOperationAction(ISD::SADDSAT, VT, Legal);
271 setOperationAction(ISD::UADDSAT, VT, Legal);
272 setOperationAction(ISD::SSUBSAT, VT, Legal);
273 setOperationAction(ISD::USUBSAT, VT, Legal);
274 setOperationAction(ISD::ABDS, VT, Legal);
275 setOperationAction(ISD::ABDU, VT, Legal);
276 setOperationAction(ISD::AVGFLOORS, VT, Legal);
277 setOperationAction(ISD::AVGFLOORU, VT, Legal);
278 setOperationAction(ISD::AVGCEILS, VT, Legal);
279 setOperationAction(ISD::AVGCEILU, VT, Legal);
280
281 // No native support for these.
282 setOperationAction(ISD::UDIV, VT, Expand);
283 setOperationAction(ISD::SDIV, VT, Expand);
284 setOperationAction(ISD::UREM, VT, Expand);
285 setOperationAction(ISD::SREM, VT, Expand);
286 setOperationAction(ISD::UDIVREM, VT, Expand);
287 setOperationAction(ISD::SDIVREM, VT, Expand);
288 setOperationAction(ISD::CTPOP, VT, Expand);
289 setOperationAction(ISD::SELECT, VT, Expand);
290 setOperationAction(ISD::SELECT_CC, VT, Expand);
291
292 // Vector reductions
293 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
294 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
295 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
296 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
297 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
298 setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
299 setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
300 setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
301 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
302
303 if (!HasMVEFP) {
304 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
305 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
306 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
307 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
308 } else {
309 setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
310 setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
311 }
312
313 // Pre and Post inc are supported on loads and stores
314 for (unsigned im = (unsigned)ISD::PRE_INC;
315 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
316 setIndexedLoadAction(im, VT, Legal);
317 setIndexedStoreAction(im, VT, Legal);
318 setIndexedMaskedLoadAction(im, VT, Legal);
319 setIndexedMaskedStoreAction(im, VT, Legal);
320 }
321 }
322
323 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
324 for (auto VT : FloatTypes) {
325 addRegisterClass(VT, &ARM::MQPRRegClass);
326 if (!HasMVEFP)
327 setAllExpand(VT);
328
329 // These are legal or custom whether we have MVE.fp or not
330 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
331 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
332 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
334 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
335 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
336 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
337 setOperationAction(ISD::SETCC, VT, Custom);
338 setOperationAction(ISD::MLOAD, VT, Custom);
339 setOperationAction(ISD::MSTORE, VT, Legal);
340 setOperationAction(ISD::SELECT, VT, Expand);
341 setOperationAction(ISD::SELECT_CC, VT, Expand);
342
343 // Pre and Post inc are supported on loads and stores
344 for (unsigned im = (unsigned)ISD::PRE_INC;
345 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
346 setIndexedLoadAction(im, VT, Legal);
347 setIndexedStoreAction(im, VT, Legal);
348 setIndexedMaskedLoadAction(im, VT, Legal);
349 setIndexedMaskedStoreAction(im, VT, Legal);
350 }
351
352 if (HasMVEFP) {
353 setOperationAction(ISD::FMINNUM, VT, Legal);
354 setOperationAction(ISD::FMAXNUM, VT, Legal);
355 setOperationAction(ISD::FROUND, VT, Legal);
356 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
357 setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
358 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
359 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
360
361 // No native support for these.
362 setOperationAction(ISD::FDIV, VT, Expand);
363 setOperationAction(ISD::FREM, VT, Expand);
364 setOperationAction(ISD::FSQRT, VT, Expand);
365 setOperationAction(ISD::FSIN, VT, Expand);
366 setOperationAction(ISD::FCOS, VT, Expand);
367 setOperationAction(ISD::FPOW, VT, Expand);
368 setOperationAction(ISD::FLOG, VT, Expand);
369 setOperationAction(ISD::FLOG2, VT, Expand);
370 setOperationAction(ISD::FLOG10, VT, Expand);
371 setOperationAction(ISD::FEXP, VT, Expand);
372 setOperationAction(ISD::FEXP2, VT, Expand);
373 setOperationAction(ISD::FNEARBYINT, VT, Expand);
374 }
375 }
376
377 // Custom Expand smaller than legal vector reductions to prevent false zero
378 // items being added.
379 setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
380 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
381 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
382 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
383 setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
384 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
385 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
386 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
387
388 // We 'support' these types up to bitcast/load/store level, regardless of
389 // MVE integer-only / float support. Only doing FP data processing on the FP
390 // vector types is inhibited at integer-only level.
391 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
392 for (auto VT : LongTypes) {
393 addRegisterClass(VT, &ARM::MQPRRegClass);
394 setAllExpand(VT);
395 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
397 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
398 setOperationAction(ISD::VSELECT, VT, Legal);
399 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
400 }
401 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
402
403 // We can do bitwise operations on v2i64 vectors
404 setOperationAction(ISD::AND, MVT::v2i64, Legal);
405 setOperationAction(ISD::OR, MVT::v2i64, Legal);
406 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
407
408 // It is legal to extload from v4i8 to v4i16 or v4i32.
409 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
410 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
411 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
412
413 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
414 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
415 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
416 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
417 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal);
418 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
419
420 // Some truncating stores are legal too.
421 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
422 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
423 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
424
425 // Pre and Post inc on these are legal, given the correct extends
426 for (unsigned im = (unsigned)ISD::PRE_INC;
427 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
428 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
429 setIndexedLoadAction(im, VT, Legal);
430 setIndexedStoreAction(im, VT, Legal);
431 setIndexedMaskedLoadAction(im, VT, Legal);
432 setIndexedMaskedStoreAction(im, VT, Legal);
433 }
434 }
435
436 // Predicate types
437 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
438 for (auto VT : pTypes) {
439 addRegisterClass(VT, &ARM::VCCRRegClass);
440 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
441 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
442 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
443 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
444 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
445 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
446 setOperationAction(ISD::SETCC, VT, Custom);
447 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
448 setOperationAction(ISD::LOAD, VT, Custom);
449 setOperationAction(ISD::STORE, VT, Custom);
450 setOperationAction(ISD::TRUNCATE, VT, Custom);
451 setOperationAction(ISD::VSELECT, VT, Expand);
452 setOperationAction(ISD::SELECT, VT, Expand);
453 setOperationAction(ISD::SELECT_CC, VT, Expand);
454
455 if (!HasMVEFP) {
456 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
457 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
458 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
459 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
460 }
461 }
462 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
463 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Expand);
464 setOperationAction(ISD::AND, MVT::v2i1, Expand);
465 setOperationAction(ISD::OR, MVT::v2i1, Expand);
466 setOperationAction(ISD::XOR, MVT::v2i1, Expand);
467 setOperationAction(ISD::SINT_TO_FP, MVT::v2i1, Expand);
468 setOperationAction(ISD::UINT_TO_FP, MVT::v2i1, Expand);
469 setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Expand);
470 setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Expand);
471
472 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
473 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
474 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
475 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
476 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
477 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
478 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
479 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
480}
481
482ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
483 const ARMSubtarget &STI)
484 : TargetLowering(TM), Subtarget(&STI) {
485 RegInfo = Subtarget->getRegisterInfo();
486 Itins = Subtarget->getInstrItineraryData();
487
488 setBooleanContents(ZeroOrOneBooleanContent);
489 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
490
491 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
492 !Subtarget->isTargetWatchOS() && !Subtarget->isTargetDriverKit()) {
493 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
494 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
495 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
496 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
497 : CallingConv::ARM_AAPCS);
498 }
499
500 if (Subtarget->isTargetMachO()) {
501 // Uses VFP for Thumb libfuncs if available.
502 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
503 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
504 static const struct {
505 const RTLIB::Libcall Op;
506 const char * const Name;
507 const ISD::CondCode Cond;
508 } LibraryCalls[] = {
509 // Single-precision floating-point arithmetic.
510 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
511 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
512 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
513 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
514
515 // Double-precision floating-point arithmetic.
516 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
517 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
518 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
519 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
520
521 // Single-precision comparisons.
522 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
523 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
524 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
525 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
526 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
527 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
528 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
529
530 // Double-precision comparisons.
531 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
532 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
533 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
534 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
535 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
536 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
537 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
538
539 // Floating-point to integer conversions.
540 // i64 conversions are done via library routines even when generating VFP
541 // instructions, so use the same ones.
542 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
543 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
544 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
545 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
546
547 // Conversions between floating types.
548 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
549 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
550
551 // Integer to floating-point conversions.
552 // i64 conversions are done via library routines even when generating VFP
553 // instructions, so use the same ones.
554 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
555 // e.g., __floatunsidf vs. __floatunssidfvfp.
556 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
557 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
558 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
559 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
560 };
561
562 for (const auto &LC : LibraryCalls) {
563 setLibcallName(LC.Op, LC.Name);
564 if (LC.Cond != ISD::SETCC_INVALID)
565 setCmpLibcallCC(LC.Op, LC.Cond);
566 }
567 }
568 }
569
570 // These libcalls are not available in 32-bit.
571 setLibcallName(RTLIB::SHL_I128, nullptr);
572 setLibcallName(RTLIB::SRL_I128, nullptr);
573 setLibcallName(RTLIB::SRA_I128, nullptr);
574 setLibcallName(RTLIB::MUL_I128, nullptr);
575 setLibcallName(RTLIB::MULO_I64, nullptr);
576 setLibcallName(RTLIB::MULO_I128, nullptr);
577
578 // RTLIB
579 if (Subtarget->isAAPCS_ABI() &&
580 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
581 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
582 static const struct {
583 const RTLIB::Libcall Op;
584 const char * const Name;
585 const CallingConv::ID CC;
586 const ISD::CondCode Cond;
587 } LibraryCalls[] = {
588 // Double-precision floating-point arithmetic helper functions
589 // RTABI chapter 4.1.2, Table 2
590 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
593 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
594
595 // Double-precision floating-point comparison helper functions
596 // RTABI chapter 4.1.2, Table 3
597 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
598 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
599 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
600 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
601 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
602 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
603 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
604
605 // Single-precision floating-point arithmetic helper functions
606 // RTABI chapter 4.1.2, Table 4
607 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
608 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
610 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
611
612 // Single-precision floating-point comparison helper functions
613 // RTABI chapter 4.1.2, Table 5
614 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
615 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
616 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
617 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
618 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
619 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
620 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
621
622 // Floating-point to integer conversions.
623 // RTABI chapter 4.1.2, Table 6
624 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
628 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
629 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
630 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
631 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
632
633 // Conversions between floating types.
634 // RTABI chapter 4.1.2, Table 7
635 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
636 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
637 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
638
639 // Integer to floating-point conversions.
640 // RTABI chapter 4.1.2, Table 8
641 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
642 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
643 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
644 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
645 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
646 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
647 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
648 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
649
650 // Long long helper functions
651 // RTABI chapter 4.2, Table 9
652 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
653 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
654 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
655 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
656
657 // Integer division functions
658 // RTABI chapter 4.3.1
659 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
660 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
661 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
662 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
663 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
664 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
665 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
666 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
667 };
668
669 for (const auto &LC : LibraryCalls) {
670 setLibcallName(LC.Op, LC.Name);
671 setLibcallCallingConv(LC.Op, LC.CC);
672 if (LC.Cond != ISD::SETCC_INVALID)
673 setCmpLibcallCC(LC.Op, LC.Cond);
674 }
675
676 // EABI dependent RTLIB
677 if (TM.Options.EABIVersion == EABI::EABI4 ||
678 TM.Options.EABIVersion == EABI::EABI5) {
679 static const struct {
680 const RTLIB::Libcall Op;
681 const char *const Name;
682 const CallingConv::ID CC;
683 const ISD::CondCode Cond;
684 } MemOpsLibraryCalls[] = {
685 // Memory operations
686 // RTABI chapter 4.3.4
687 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
688 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
689 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
690 };
691
692 for (const auto &LC : MemOpsLibraryCalls) {
693 setLibcallName(LC.Op, LC.Name);
694 setLibcallCallingConv(LC.Op, LC.CC);
695 if (LC.Cond != ISD::SETCC_INVALID)
696 setCmpLibcallCC(LC.Op, LC.Cond);
697 }
698 }
699 }
700
701 if (Subtarget->isTargetWindows()) {
702 static const struct {
703 const RTLIB::Libcall Op;
704 const char * const Name;
705 const CallingConv::ID CC;
706 } LibraryCalls[] = {
707 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
708 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
709 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
710 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
711 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
712 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
713 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
714 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
715 };
716
717 for (const auto &LC : LibraryCalls) {
718 setLibcallName(LC.Op, LC.Name);
719 setLibcallCallingConv(LC.Op, LC.CC);
720 }
721 }
722
723 // Use divmod compiler-rt calls for iOS 5.0 and later.
724 if (Subtarget->isTargetMachO() &&
725 !(Subtarget->isTargetIOS() &&
726 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
727 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
728 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
729 }
730
731 // The half <-> float conversion functions are always soft-float on
732 // non-watchos platforms, but are needed for some targets which use a
733 // hard-float calling convention by default.
734 if (!Subtarget->isTargetWatchABI()) {
735 if (Subtarget->isAAPCS_ABI()) {
736 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
737 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
738 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
739 } else {
740 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
741 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
742 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
743 }
744 }
745
746 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
747 // a __gnu_ prefix (which is the default).
748 if (Subtarget->isTargetAEABI()) {
749 static const struct {
750 const RTLIB::Libcall Op;
751 const char * const Name;
752 const CallingConv::ID CC;
753 } LibraryCalls[] = {
754 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
755 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
756 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
757 };
758
759 for (const auto &LC : LibraryCalls) {
760 setLibcallName(LC.Op, LC.Name);
761 setLibcallCallingConv(LC.Op, LC.CC);
762 }
763 }
764
765 if (Subtarget->isThumb1Only())
766 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
767 else
768 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
769
770 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
771 Subtarget->hasFPRegs()) {
772 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
773 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
774
775 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
776 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
777 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
778 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
779
780 if (!Subtarget->hasVFP2Base())
781 setAllExpand(MVT::f32);
782 if (!Subtarget->hasFP64())
783 setAllExpand(MVT::f64);
784 }
785
786 if (Subtarget->hasFullFP16()) {
787 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
788 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
789 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
790
791 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
792 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
793 }
794
795 if (Subtarget->hasBF16()) {
796 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
797 setAllExpand(MVT::bf16);
798 if (!Subtarget->hasFullFP16())
799 setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
800 }
801
802 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
803 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
804 setTruncStoreAction(VT, InnerVT, Expand);
805 addAllExtLoads(VT, InnerVT, Expand);
806 }
807
808 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
809 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
810
811 setOperationAction(ISD::BSWAP, VT, Expand);
812 }
813
814 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
815 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
816
817 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
818 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
819
820 if (Subtarget->hasMVEIntegerOps())
821 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
822
823 // Combine low-overhead loop intrinsics so that we can lower i1 types.
824 if (Subtarget->hasLOB()) {
825 setTargetDAGCombine({ISD::BRCOND, ISD::BR_CC});
826 }
827
828 if (Subtarget->hasNEON()) {
829 addDRTypeForNEON(MVT::v2f32);
830 addDRTypeForNEON(MVT::v8i8);
831 addDRTypeForNEON(MVT::v4i16);
832 addDRTypeForNEON(MVT::v2i32);
833 addDRTypeForNEON(MVT::v1i64);
834
835 addQRTypeForNEON(MVT::v4f32);
836 addQRTypeForNEON(MVT::v2f64);
837 addQRTypeForNEON(MVT::v16i8);
838 addQRTypeForNEON(MVT::v8i16);
839 addQRTypeForNEON(MVT::v4i32);
840 addQRTypeForNEON(MVT::v2i64);
841
842 if (Subtarget->hasFullFP16()) {
843 addQRTypeForNEON(MVT::v8f16);
844 addDRTypeForNEON(MVT::v4f16);
845 }
846
847 if (Subtarget->hasBF16()) {
848 addQRTypeForNEON(MVT::v8bf16);
849 addDRTypeForNEON(MVT::v4bf16);
850 }
851 }
852
853 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
854 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
855 // none of Neon, MVE or VFP supports any arithmetic operations on it.
856 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
857 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
858 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
859 // FIXME: Code duplication: FDIV and FREM are expanded always, see
860 // ARMTargetLowering::addTypeForNEON method for details.
861 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
862 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
863 // FIXME: Create unittest.
864 // In another words, find a way when "copysign" appears in DAG with vector
865 // operands.
866 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
867 // FIXME: Code duplication: SETCC has custom operation action, see
868 // ARMTargetLowering::addTypeForNEON method for details.
869 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
870 // FIXME: Create unittest for FNEG and for FABS.
871 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
872 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
873 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
874 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
875 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
876 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
877 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
878 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
879 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
880 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
881 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
882 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
883 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
884 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
885 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
886 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
887 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
888 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
889 }
890
891 if (Subtarget->hasNEON()) {
892 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
893 // supported for v4f32.
894 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
895 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
896 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
897 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
898 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
899 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
900 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
901 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
902 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
903 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
904 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
905 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
906 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
907 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
908
909 // Mark v2f32 intrinsics.
910 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
911 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
912 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
913 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
914 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
915 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
916 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
917 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
918 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
919 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
920 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
921 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
922 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
923 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
924
925 // Neon does not support some operations on v1i64 and v2i64 types.
926 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
927 // Custom handling for some quad-vector types to detect VMULL.
928 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
929 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
930 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
931 // Custom handling for some vector types to avoid expensive expansions
932 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
933 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
934 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
935 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
936 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
937 // a destination type that is wider than the source, and nor does
938 // it have a FP_TO_[SU]INT instruction with a narrower destination than
939 // source.
940 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
941 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
942 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
943 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
944 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
945 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
946 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
947 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
948
949 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
950 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
951
952 // NEON does not have single instruction CTPOP for vectors with element
953 // types wider than 8-bits. However, custom lowering can leverage the
954 // v8i8/v16i8 vcnt instruction.
955 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
956 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
957 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
958 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
959 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
960 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
961
962 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
963 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
964
965 // NEON does not have single instruction CTTZ for vectors.
966 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
967 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
968 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
969 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
970
971 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
972 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
973 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
974 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
975
976 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
977 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
978 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
979 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
980
981 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
982 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
983 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
984 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
985
986 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
987 setOperationAction(ISD::MULHS, VT, Expand);
988 setOperationAction(ISD::MULHU, VT, Expand);
989 }
990
991 // NEON only has FMA instructions as of VFP4.
992 if (!Subtarget->hasVFP4Base()) {
993 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
994 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
995 }
996
997 setTargetDAGCombine({ISD::SHL, ISD::SRL, ISD::SRA, ISD::FP_TO_SINT,
998 ISD::FP_TO_UINT, ISD::FDIV, ISD::LOAD});
999
1000 // It is legal to extload from v4i8 to v4i16 or v4i32.
1001 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
1002 MVT::v2i32}) {
1003 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
1004 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
1005 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
1006 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
1007 }
1008 }
1009 }
1010
1011 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1012 setTargetDAGCombine(
1013 {ISD::BUILD_VECTOR, ISD::VECTOR_SHUFFLE, ISD::INSERT_SUBVECTOR,
1014 ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
1015 ISD::SIGN_EXTEND_INREG, ISD::STORE, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND,
1016 ISD::ANY_EXTEND, ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN,
1017 ISD::INTRINSIC_VOID, ISD::VECREDUCE_ADD, ISD::ADD, ISD::BITCAST});
1018 }
1019 if (Subtarget->hasMVEIntegerOps()) {
1020 setTargetDAGCombine({ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
1021 ISD::FP_EXTEND, ISD::SELECT, ISD::SELECT_CC,
1022 ISD::SETCC});
1023 }
1024 if (Subtarget->hasMVEFloatOps()) {
1025 setTargetDAGCombine(ISD::FADD);
1026 }
1027
1028 if (!Subtarget->hasFP64()) {
1029 // When targeting a floating-point unit with only single-precision
1030 // operations, f64 is legal for the few double-precision instructions which
1031 // are present However, no double-precision operations other than moves,
1032 // loads and stores are provided by the hardware.
1033 setOperationAction(ISD::FADD, MVT::f64, Expand);
1034 setOperationAction(ISD::FSUB, MVT::f64, Expand);
1035 setOperationAction(ISD::FMUL, MVT::f64, Expand);
1036 setOperationAction(ISD::FMA, MVT::f64, Expand);
1037 setOperationAction(ISD::FDIV, MVT::f64, Expand);
1038 setOperationAction(ISD::FREM, MVT::f64, Expand);
1039 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1040 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
1041 setOperationAction(ISD::FNEG, MVT::f64, Expand);
1042 setOperationAction(ISD::FABS, MVT::f64, Expand);
1043 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
1044 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1045 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1046 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1047 setOperationAction(ISD::FLOG, MVT::f64, Expand);
1048 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
1049 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
1050 setOperationAction(ISD::FEXP, MVT::f64, Expand);
1051 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
1052 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
1053 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
1054 setOperationAction(ISD::FRINT, MVT::f64, Expand);
1055 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1056 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
1057 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1058 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1059 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1060 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1061 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1062 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1063 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
1064 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1065 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1066 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1067 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1068 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
1069 }
1070
1071 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1072 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
1073 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1074 if (Subtarget->hasFullFP16()) {
1075 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
1076 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1077 }
1078 }
1079
1080 if (!Subtarget->hasFP16()) {
1081 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
1082 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1083 }
1084
1085 computeRegisterProperties(Subtarget->getRegisterInfo());
1086
1087 // ARM does not have floating-point extending loads.
1088 for (MVT VT : MVT::fp_valuetypes()) {
1089 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1090 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1091 }
1092
1093 // ... or truncating stores
1094 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1095 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1096 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1097
1098 // ARM does not have i1 sign extending load.
1099 for (MVT VT : MVT::integer_valuetypes())
1100 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1101
1102 // ARM supports all 4 flavors of integer indexed load / store.
1103 if (!Subtarget->isThumb1Only()) {
1104 for (unsigned im = (unsigned)ISD::PRE_INC;
1105 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1106 setIndexedLoadAction(im, MVT::i1, Legal);
1107 setIndexedLoadAction(im, MVT::i8, Legal);
1108 setIndexedLoadAction(im, MVT::i16, Legal);
1109 setIndexedLoadAction(im, MVT::i32, Legal);
1110 setIndexedStoreAction(im, MVT::i1, Legal);
1111 setIndexedStoreAction(im, MVT::i8, Legal);
1112 setIndexedStoreAction(im, MVT::i16, Legal);
1113 setIndexedStoreAction(im, MVT::i32, Legal);
1114 }
1115 } else {
1116 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1117 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1118 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1119 }
1120
1121 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1122 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1123 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1124 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1125
1126 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1127 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1128 if (Subtarget->hasDSP()) {
1129 setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1130 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1131 setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1132 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1133 setOperationAction(ISD::UADDSAT, MVT::i8, Custom);
1134 setOperationAction(ISD::USUBSAT, MVT::i8, Custom);
1135 setOperationAction(ISD::UADDSAT, MVT::i16, Custom);
1136 setOperationAction(ISD::USUBSAT, MVT::i16, Custom);
1137 }
1138 if (Subtarget->hasBaseDSP()) {
1139 setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1140 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1141 }
1142
1143 // i64 operation support.
1144 setOperationAction(ISD::MUL, MVT::i64, Expand);
1145 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1146 if (Subtarget->isThumb1Only()) {
1147 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1148 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1149 }
1150 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1151 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1152 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1153
1154 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1155 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1156 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1157 setOperationAction(ISD::SRL, MVT::i64, Custom);
1158 setOperationAction(ISD::SRA, MVT::i64, Custom);
1159 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1160 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1161 setOperationAction(ISD::LOAD, MVT::i64, Custom);
1162 setOperationAction(ISD::STORE, MVT::i64, Custom);
1163
1164 // MVE lowers 64 bit shifts to lsll and lsrl
1165 // assuming that ISD::SRL and SRA of i64 are already marked custom
1166 if (Subtarget->hasMVEIntegerOps())
1167 setOperationAction(ISD::SHL, MVT::i64, Custom);
1168
1169 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1170 if (Subtarget->isThumb1Only()) {
1171 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1172 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1173 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1174 }
1175
1176 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1177 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1178
1179 // ARM does not have ROTL.
1180 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1181 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1182 setOperationAction(ISD::ROTL, VT, Expand);
1183 setOperationAction(ISD::ROTR, VT, Expand);
1184 }
1185 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1186 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1187 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1188 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1189 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1190 }
1191
1192 // @llvm.readcyclecounter requires the Performance Monitors extension.
1193 // Default to the 0 expansion on unsupported platforms.
1194 // FIXME: Technically there are older ARM CPUs that have
1195 // implementation-specific ways of obtaining this information.
1196 if (Subtarget->hasPerfMon())
1197 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1198
1199 // Only ARMv6 has BSWAP.
1200 if (!Subtarget->hasV6Ops())
1201 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1202
1203 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1204 : Subtarget->hasDivideInARMMode();
1205 if (!hasDivide) {
1206 // These are expanded into libcalls if the cpu doesn't have HW divider.
1207 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1208 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1209 }
1210
1211 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1212 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1213 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1214
1215 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1216 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1217 }
1218
1219 setOperationAction(ISD::SREM, MVT::i32, Expand);
1220 setOperationAction(ISD::UREM, MVT::i32, Expand);
1221
1222 // Register based DivRem for AEABI (RTABI 4.2)
1223 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1224 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1225 Subtarget->isTargetWindows()) {
1226 setOperationAction(ISD::SREM, MVT::i64, Custom);
1227 setOperationAction(ISD::UREM, MVT::i64, Custom);
1228 HasStandaloneRem = false;
1229
1230 if (Subtarget->isTargetWindows()) {
1231 const struct {
1232 const RTLIB::Libcall Op;
1233 const char * const Name;
1234 const CallingConv::ID CC;
1235 } LibraryCalls[] = {
1236 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1237 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1238 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1239 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1240
1241 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1242 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1243 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1244 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1245 };
1246
1247 for (const auto &LC : LibraryCalls) {
1248 setLibcallName(LC.Op, LC.Name);
1249 setLibcallCallingConv(LC.Op, LC.CC);
1250 }
1251 } else {
1252 const struct {
1253 const RTLIB::Libcall Op;
1254 const char * const Name;
1255 const CallingConv::ID CC;
1256 } LibraryCalls[] = {
1257 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1258 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1259 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1260 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1261
1262 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1263 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1264 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1265 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1266 };
1267
1268 for (const auto &LC : LibraryCalls) {
1269 setLibcallName(LC.Op, LC.Name);
1270 setLibcallCallingConv(LC.Op, LC.CC);
1271 }
1272 }
1273
1274 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1275 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1276 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1277 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1278 } else {
1279 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1280 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1281 }
1282
1283 if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1284 // MSVCRT doesn't have powi; fall back to pow
1285 setLibcallName(RTLIB::POWI_F32, nullptr);
1286 setLibcallName(RTLIB::POWI_F64, nullptr);
1287 }
1288
1289 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1290 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1291 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1292 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1293
1294 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1295 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1296
1297 // Use the default implementation.
1298 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1299 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1300 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1301 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1302 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1303 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1304
1305 if (Subtarget->isTargetWindows())
1306 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1307 else
1308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1309
1310 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1311 // the default expansion.
1312 InsertFencesForAtomic = false;
1313 if (Subtarget->hasAnyDataBarrier() &&
1314 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1315 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1316 // to ldrex/strex loops already.
1317 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1318 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1319 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1320
1321 // On v8, we have particularly efficient implementations of atomic fences
1322 // if they can be combined with nearby atomic loads and stores.
1323 if (!Subtarget->hasAcquireRelease() ||
1324 getTargetMachine().getOptLevel() == 0) {
1325 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1326 InsertFencesForAtomic = true;
1327 }
1328 } else {
1329 // If there's anything we can use as a barrier, go through custom lowering
1330 // for ATOMIC_FENCE.
1331 // If target has DMB in thumb, Fences can be inserted.
1332 if (Subtarget->hasDataBarrier())
1333 InsertFencesForAtomic = true;
1334
1335 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1336 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1337
1338 // Set them all for expansion, which will force libcalls.
1339 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1340 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1341 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1342 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1343 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1344 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1345 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1346 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1347 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1348 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1349 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1350 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1351 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1352 // Unordered/Monotonic case.
1353 if (!InsertFencesForAtomic) {
1354 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1355 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1356 }
1357 }
1358
1359 // Compute supported atomic widths.
1360 if (Subtarget->isTargetLinux() ||
1361 (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1362 // For targets where __sync_* routines are reliably available, we use them
1363 // if necessary.
1364 //
1365 // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1366 // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1367 //
1368 // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1369 // such targets should provide __sync_* routines, which use the ARM mode
1370 // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1371 // encoding; see ARMISD::MEMBARRIER_MCR.)
1372 setMaxAtomicSizeInBitsSupported(64);
1373 } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1374 Subtarget->hasForced32BitAtomics()) {
1375 // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1376 setMaxAtomicSizeInBitsSupported(32);
1377 } else {
1378 // We can't assume anything about other targets; just use libatomic
1379 // routines.
1380 setMaxAtomicSizeInBitsSupported(0);
1381 }
1382
1383 setMaxDivRemBitWidthSupported(64);
1384
1385 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1386
1387 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1388 if (!Subtarget->hasV6Ops()) {
1389 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1390 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1391 }
1392 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1393
1394 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1395 !Subtarget->isThumb1Only()) {
1396 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1397 // iff target supports vfp2.
1398 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1399 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1400 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
1401 }
1402
1403 // We want to custom lower some of our intrinsics.
1404 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1405 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1406 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1407 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1408 if (Subtarget->useSjLjEH())
1409 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1410
1411 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1412 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1413 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1414 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1415 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1416 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1417 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1418 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1419 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1420 if (Subtarget->hasFullFP16()) {
1421 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1422 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1423 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1424 }
1425
1426 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1427
1428 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1429 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1430 if (Subtarget->hasFullFP16())
1431 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1432 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1433 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1434 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1435
1436 // We don't support sin/cos/fmod/copysign/pow
1437 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1438 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1439 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1440 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1441 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1442 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1443 setOperationAction(ISD::FREM, MVT::f64, Expand);
1444 setOperationAction(ISD::FREM, MVT::f32, Expand);
1445 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1446 !Subtarget->isThumb1Only()) {
1447 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1448 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1449 }
1450 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1451 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1452
1453 if (!Subtarget->hasVFP4Base()) {
1454 setOperationAction(ISD::FMA, MVT::f64, Expand);
1455 setOperationAction(ISD::FMA, MVT::f32, Expand);
1456 }
1457
1458 // Various VFP goodness
1459 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1460 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1461 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1462 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1463 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1464 }
1465
1466 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1467 if (!Subtarget->hasFP16()) {
1468 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1469 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1470 }
1471
1472 // Strict floating-point comparisons need custom lowering.
1473 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
1474 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1475 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
1476 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1477 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
1478 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1479 }
1480
1481 // Use __sincos_stret if available.
1482 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1483 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1484 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1485 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1486 }
1487
1488 // FP-ARMv8 implements a lot of rounding-like FP operations.
1489 if (Subtarget->hasFPARMv8Base()) {
1490 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1491 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1492 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1493 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1494 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1495 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1496 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1497 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1498 if (Subtarget->hasNEON()) {
1499 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1500 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1501 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1502 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1503 }
1504
1505 if (Subtarget->hasFP64()) {
1506 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1507 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1508 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1509 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1510 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1511 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1512 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1513 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1514 }
1515 }
1516
1517 // FP16 often need to be promoted to call lib functions
1518 if (Subtarget->hasFullFP16()) {
1519 setOperationAction(ISD::FREM, MVT::f16, Promote);
1520 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1521 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1522 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1523 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1524 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1525 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1526 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1527 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1528 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1529 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1530 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1531
1532 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1533 }
1534
1535 if (Subtarget->hasNEON()) {
1536 // vmin and vmax aren't available in a scalar form, so we can use
1537 // a NEON instruction with an undef lane instead. This has a performance
1538 // penalty on some cores, so we don't do this unless we have been
1539 // asked to by the core tuning model.
1540 if (Subtarget->useNEONForSinglePrecisionFP()) {
1541 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1542 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1543 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1544 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1545 }
1546 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1547 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1548 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1549 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1550
1551 if (Subtarget->hasFullFP16()) {
1552 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1553 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1554 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1555 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1556
1557 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1558 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1559 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1560 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1561 }
1562 }
1563
1564 // We have target-specific dag combine patterns for the following nodes:
1565 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1566 setTargetDAGCombine(
1567 {ISD::ADD, ISD::SUB, ISD::MUL, ISD::AND, ISD::OR, ISD::XOR});
1568
1569 if (Subtarget->hasMVEIntegerOps())
1570 setTargetDAGCombine(ISD::VSELECT);
1571
1572 if (Subtarget->hasV6Ops())
1573 setTargetDAGCombine(ISD::SRL);
1574 if (Subtarget->isThumb1Only())
1575 setTargetDAGCombine(ISD::SHL);
1576 // Attempt to lower smin/smax to ssat/usat
1577 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1578 Subtarget->isThumb2()) {
1579 setTargetDAGCombine({ISD::SMIN, ISD::SMAX});
1580 }
1581
1582 setStackPointerRegisterToSaveRestore(ARM::SP);
1583
1584 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1585 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1586 setSchedulingPreference(Sched::RegPressure);
1587 else
1588 setSchedulingPreference(Sched::Hybrid);
1589
1590 //// temporary - rewrite interface to use type
1591 MaxStoresPerMemset = 8;
1592 MaxStoresPerMemsetOptSize = 4;
1593 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1594 MaxStoresPerMemcpyOptSize = 2;
1595 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1596 MaxStoresPerMemmoveOptSize = 2;
1597
1598 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1599 // are at least 4 bytes aligned.
1600 setMinStackArgumentAlignment(Align(4));
1601
1602 // Prefer likely predicted branches to selects on out-of-order cores.
1603 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1604
1605 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1606
1607 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1608
1609 if (Subtarget->isThumb() || Subtarget->isThumb2())
1610 setTargetDAGCombine(ISD::ABS);
1611}
1612
1613bool ARMTargetLowering::useSoftFloat() const {
1614 return Subtarget->useSoftFloat();
1615}
1616
1617// FIXME: It might make sense to define the representative register class as the
1618// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1619// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1620// SPR's representative would be DPR_VFP2. This should work well if register
1621// pressure tracking were modified such that a register use would increment the
1622// pressure of the register class's representative and all of it's super
1623// classes' representatives transitively. We have not implemented this because
1624// of the difficulty prior to coalescing of modeling operand register classes
1625// due to the common occurrence of cross class copies and subregister insertions
1626// and extractions.
1627std::pair<const TargetRegisterClass *, uint8_t>
1628ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1629 MVT VT) const {
1630 const TargetRegisterClass *RRC = nullptr;
1631 uint8_t Cost = 1;
1632 switch (VT.SimpleTy) {
1633 default:
1634 return TargetLowering::findRepresentativeClass(TRI, VT);
1635 // Use DPR as representative register class for all floating point
1636 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1637 // the cost is 1 for both f32 and f64.
1638 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1639 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1640 RRC = &ARM::DPRRegClass;
1641 // When NEON is used for SP, only half of the register file is available
1642 // because operations that define both SP and DP results will be constrained
1643 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1644 // coalescing by double-counting the SP regs. See the FIXME above.
1645 if (Subtarget->useNEONForSinglePrecisionFP())
1646 Cost = 2;
1647 break;
1648 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1649 case MVT::v4f32: case MVT::v2f64:
1650 RRC = &ARM::DPRRegClass;
1651 Cost = 2;
1652 break;
1653 case MVT::v4i64:
1654 RRC = &ARM::DPRRegClass;
1655 Cost = 4;
1656 break;
1657 case MVT::v8i64:
1658 RRC = &ARM::DPRRegClass;
1659 Cost = 8;
1660 break;
1661 }
1662 return std::make_pair(RRC, Cost);
1663}
1664
1665const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1666#define MAKE_CASE(V) \
1667 case V: \
1668 return #V;
1669 switch ((ARMISD::NodeType)Opcode) {
1670 case ARMISD::FIRST_NUMBER:
1671 break;
1672 MAKE_CASE(ARMISD::Wrapper)
1673 MAKE_CASE(ARMISD::WrapperPIC)
1674 MAKE_CASE(ARMISD::WrapperJT)
1675 MAKE_CASE(ARMISD::COPY_STRUCT_BYVAL)
1676 MAKE_CASE(ARMISD::CALL)
1677 MAKE_CASE(ARMISD::CALL_PRED)
1678 MAKE_CASE(ARMISD::CALL_NOLINK)
1679 MAKE_CASE(ARMISD::tSECALL)
1680 MAKE_CASE(ARMISD::t2CALL_BTI)
1681 MAKE_CASE(ARMISD::BRCOND)
1682 MAKE_CASE(ARMISD::BR_JT)
1683 MAKE_CASE(ARMISD::BR2_JT)
1684 MAKE_CASE(ARMISD::RET_FLAG)
1685 MAKE_CASE(ARMISD::SERET_FLAG)
1686 MAKE_CASE(ARMISD::INTRET_FLAG)
1687 MAKE_CASE(ARMISD::PIC_ADD)
1688 MAKE_CASE(ARMISD::CMP)
1689 MAKE_CASE(ARMISD::CMN)
1690 MAKE_CASE(ARMISD::CMPZ)
1691 MAKE_CASE(ARMISD::CMPFP)
1692 MAKE_CASE(ARMISD::CMPFPE)
1693 MAKE_CASE(ARMISD::CMPFPw0)
1694 MAKE_CASE(ARMISD::CMPFPEw0)
1695 MAKE_CASE(ARMISD::BCC_i64)
1696 MAKE_CASE(ARMISD::FMSTAT)
1697 MAKE_CASE(ARMISD::CMOV)
1698 MAKE_CASE(ARMISD::SUBS)
1699 MAKE_CASE(ARMISD::SSAT)
1700 MAKE_CASE(ARMISD::USAT)
1701 MAKE_CASE(ARMISD::ASRL)
1702 MAKE_CASE(ARMISD::LSRL)
1703 MAKE_CASE(ARMISD::LSLL)
1704 MAKE_CASE(ARMISD::SRL_FLAG)
1705 MAKE_CASE(ARMISD::SRA_FLAG)
1706 MAKE_CASE(ARMISD::RRX)
1707 MAKE_CASE(ARMISD::ADDC)
1708 MAKE_CASE(ARMISD::ADDE)
1709 MAKE_CASE(ARMISD::SUBC)
1710 MAKE_CASE(ARMISD::SUBE)
1711 MAKE_CASE(ARMISD::LSLS)
1712 MAKE_CASE(ARMISD::VMOVRRD)
1713 MAKE_CASE(ARMISD::VMOVDRR)
1714 MAKE_CASE(ARMISD::VMOVhr)
1715 MAKE_CASE(ARMISD::VMOVrh)
1716 MAKE_CASE(ARMISD::VMOVSR)
1717 MAKE_CASE(ARMISD::EH_SJLJ_SETJMP)
1718 MAKE_CASE(ARMISD::EH_SJLJ_LONGJMP)
1719 MAKE_CASE(ARMISD::EH_SJLJ_SETUP_DISPATCH)
1720 MAKE_CASE(ARMISD::TC_RETURN)
1721 MAKE_CASE(ARMISD::THREAD_POINTER)
1722 MAKE_CASE(ARMISD::DYN_ALLOC)
1723 MAKE_CASE(ARMISD::MEMBARRIER_MCR)
1724 MAKE_CASE(ARMISD::PRELOAD)
1725 MAKE_CASE(ARMISD::LDRD)
1726 MAKE_CASE(ARMISD::STRD)
1727 MAKE_CASE(ARMISD::WIN__CHKSTK)
1728 MAKE_CASE(ARMISD::WIN__DBZCHK)
1729 MAKE_CASE(ARMISD::PREDICATE_CAST)
1730 MAKE_CASE(ARMISD::VECTOR_REG_CAST)
1731 MAKE_CASE(ARMISD::MVESEXT)
1732 MAKE_CASE(ARMISD::MVEZEXT)
1733 MAKE_CASE(ARMISD::MVETRUNC)
1734 MAKE_CASE(ARMISD::VCMP)
1735 MAKE_CASE(ARMISD::VCMPZ)
1736 MAKE_CASE(ARMISD::VTST)
1737 MAKE_CASE(ARMISD::VSHLs)
1738 MAKE_CASE(ARMISD::VSHLu)
1739 MAKE_CASE(ARMISD::VSHLIMM)
1740 MAKE_CASE(ARMISD::VSHRsIMM)
1741 MAKE_CASE(ARMISD::VSHRuIMM)
1742 MAKE_CASE(ARMISD::VRSHRsIMM)
1743 MAKE_CASE(ARMISD::VRSHRuIMM)
1744 MAKE_CASE(ARMISD::VRSHRNIMM)
1745 MAKE_CASE(ARMISD::VQSHLsIMM)
1746 MAKE_CASE(ARMISD::VQSHLuIMM)
1747 MAKE_CASE(ARMISD::VQSHLsuIMM)
1748 MAKE_CASE(ARMISD::VQSHRNsIMM)
1749 MAKE_CASE(ARMISD::VQSHRNuIMM)
1750 MAKE_CASE(ARMISD::VQSHRNsuIMM)
1751 MAKE_CASE(ARMISD::VQRSHRNsIMM)
1752 MAKE_CASE(ARMISD::VQRSHRNuIMM)
1753 MAKE_CASE(ARMISD::VQRSHRNsuIMM)
1754 MAKE_CASE(ARMISD::VSLIIMM)
1755 MAKE_CASE(ARMISD::VSRIIMM)
1756 MAKE_CASE(ARMISD::VGETLANEu)
1757 MAKE_CASE(ARMISD::VGETLANEs)
1758 MAKE_CASE(ARMISD::VMOVIMM)
1759 MAKE_CASE(ARMISD::VMVNIMM)
1760 MAKE_CASE(ARMISD::VMOVFPIMM)
1761 MAKE_CASE(ARMISD::VDUP)
1762 MAKE_CASE(ARMISD::VDUPLANE)
1763 MAKE_CASE(ARMISD::VEXT)
1764 MAKE_CASE(ARMISD::VREV64)
1765 MAKE_CASE(ARMISD::VREV32)
1766 MAKE_CASE(ARMISD::VREV16)
1767 MAKE_CASE(ARMISD::VZIP)
1768 MAKE_CASE(ARMISD::VUZP)
1769 MAKE_CASE(ARMISD::VTRN)
1770 MAKE_CASE(ARMISD::VTBL1)
1771 MAKE_CASE(ARMISD::VTBL2)
1772 MAKE_CASE(ARMISD::VMOVN)
1773 MAKE_CASE(ARMISD::VQMOVNs)
1774 MAKE_CASE(ARMISD::VQMOVNu)
1775 MAKE_CASE(ARMISD::VCVTN)
1776 MAKE_CASE(ARMISD::VCVTL)
1777 MAKE_CASE(ARMISD::VIDUP)
1778 MAKE_CASE(ARMISD::VMULLs)
1779 MAKE_CASE(ARMISD::VMULLu)
1780 MAKE_CASE(ARMISD::VQDMULH)
1781 MAKE_CASE(ARMISD::VADDVs)
1782 MAKE_CASE(ARMISD::VADDVu)
1783 MAKE_CASE(ARMISD::VADDVps)
1784 MAKE_CASE(ARMISD::VADDVpu)
1785 MAKE_CASE(ARMISD::VADDLVs)
1786 MAKE_CASE(ARMISD::VADDLVu)
1787 MAKE_CASE(ARMISD::VADDLVAs)
1788 MAKE_CASE(ARMISD::VADDLVAu)
1789 MAKE_CASE(ARMISD::VADDLVps)
1790 MAKE_CASE(ARMISD::VADDLVpu)
1791 MAKE_CASE(ARMISD::VADDLVAps)
1792 MAKE_CASE(ARMISD::VADDLVApu)
1793 MAKE_CASE(ARMISD::VMLAVs)
1794 MAKE_CASE(ARMISD::VMLAVu)
1795 MAKE_CASE(ARMISD::VMLAVps)
1796 MAKE_CASE(ARMISD::VMLAVpu)
1797 MAKE_CASE(ARMISD::VMLALVs)
1798 MAKE_CASE(ARMISD::VMLALVu)
1799 MAKE_CASE(ARMISD::VMLALVps)
1800 MAKE_CASE(ARMISD::VMLALVpu)
1801 MAKE_CASE(ARMISD::VMLALVAs)
1802 MAKE_CASE(ARMISD::VMLALVAu)
1803 MAKE_CASE(ARMISD::VMLALVAps)
1804 MAKE_CASE(ARMISD::VMLALVApu)
1805 MAKE_CASE(ARMISD::VMINVu)
1806 MAKE_CASE(ARMISD::VMINVs)
1807 MAKE_CASE(ARMISD::VMAXVu)
1808 MAKE_CASE(ARMISD::VMAXVs)
1809 MAKE_CASE(ARMISD::UMAAL)
1810 MAKE_CASE(ARMISD::UMLAL)
1811 MAKE_CASE(ARMISD::SMLAL)
1812 MAKE_CASE(ARMISD::SMLALBB)
1813 MAKE_CASE(ARMISD::SMLALBT)
1814 MAKE_CASE(ARMISD::SMLALTB)
1815 MAKE_CASE(ARMISD::SMLALTT)
1816 MAKE_CASE(ARMISD::SMULWB)
1817 MAKE_CASE(ARMISD::SMULWT)
1818 MAKE_CASE(ARMISD::SMLALD)
1819 MAKE_CASE(ARMISD::SMLALDX)
1820 MAKE_CASE(ARMISD::SMLSLD)
1821 MAKE_CASE(ARMISD::SMLSLDX)
1822 MAKE_CASE(ARMISD::SMMLAR)
1823 MAKE_CASE(ARMISD::SMMLSR)
1824 MAKE_CASE(ARMISD::QADD16b)
1825 MAKE_CASE(ARMISD::QSUB16b)
1826 MAKE_CASE(ARMISD::QADD8b)
1827 MAKE_CASE(ARMISD::QSUB8b)
1828 MAKE_CASE(ARMISD::UQADD16b)
1829 MAKE_CASE(ARMISD::UQSUB16b)
1830 MAKE_CASE(ARMISD::UQADD8b)
1831 MAKE_CASE(ARMISD::UQSUB8b)
1832 MAKE_CASE(ARMISD::BUILD_VECTOR)
1833 MAKE_CASE(ARMISD::BFI)
1834 MAKE_CASE(ARMISD::VORRIMM)
1835 MAKE_CASE(ARMISD::VBICIMM)
1836 MAKE_CASE(ARMISD::VBSP)
1837 MAKE_CASE(ARMISD::MEMCPY)
1838 MAKE_CASE(ARMISD::VLD1DUP)
1839 MAKE_CASE(ARMISD::VLD2DUP)
1840 MAKE_CASE(ARMISD::VLD3DUP)
1841 MAKE_CASE(ARMISD::VLD4DUP)
1842 MAKE_CASE(ARMISD::VLD1_UPD)
1843 MAKE_CASE(ARMISD::VLD2_UPD)
1844 MAKE_CASE(ARMISD::VLD3_UPD)
1845 MAKE_CASE(ARMISD::VLD4_UPD)
1846 MAKE_CASE(ARMISD::VLD1x2_UPD)
1847 MAKE_CASE(ARMISD::VLD1x3_UPD)
1848 MAKE_CASE(ARMISD::VLD1x4_UPD)
1849 MAKE_CASE(ARMISD::VLD2LN_UPD)
1850 MAKE_CASE(ARMISD::VLD3LN_UPD)
1851 MAKE_CASE(ARMISD::VLD4LN_UPD)
1852 MAKE_CASE(ARMISD::VLD1DUP_UPD)
1853 MAKE_CASE(ARMISD::VLD2DUP_UPD)
1854 MAKE_CASE(ARMISD::VLD3DUP_UPD)
1855 MAKE_CASE(ARMISD::VLD4DUP_UPD)
1856 MAKE_CASE(ARMISD::VST1_UPD)
1857 MAKE_CASE(ARMISD::VST2_UPD)
1858 MAKE_CASE(ARMISD::VST3_UPD)
1859 MAKE_CASE(ARMISD::VST4_UPD)
1860 MAKE_CASE(ARMISD::VST1x2_UPD)
1861 MAKE_CASE(ARMISD::VST1x3_UPD)
1862 MAKE_CASE(ARMISD::VST1x4_UPD)
1863 MAKE_CASE(ARMISD::VST2LN_UPD)
1864 MAKE_CASE(ARMISD::VST3LN_UPD)
1865 MAKE_CASE(ARMISD::VST4LN_UPD)
1866 MAKE_CASE(ARMISD::WLS)
1867 MAKE_CASE(ARMISD::WLSSETUP)
1868 MAKE_CASE(ARMISD::LE)
1869 MAKE_CASE(ARMISD::LOOP_DEC)
1870 MAKE_CASE(ARMISD::CSINV)
1871 MAKE_CASE(ARMISD::CSNEG)
1872 MAKE_CASE(ARMISD::CSINC)
1873 MAKE_CASE(ARMISD::MEMCPYLOOP)
1874 MAKE_CASE(ARMISD::MEMSETLOOP)
1875#undef MAKE_CASE
1876 }
1877 return nullptr;
1878}
1879
1880EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1881 EVT VT) const {
1882 if (!VT.isVector())
1883 return getPointerTy(DL);
1884
1885 // MVE has a predicate register.
1886 if ((Subtarget->hasMVEIntegerOps() &&
1887 (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
1888 VT == MVT::v16i8)) ||
1889 (Subtarget->hasMVEFloatOps() &&
1890 (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16)))
1891 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1892 return VT.changeVectorElementTypeToInteger();
1893}
1894
1895/// getRegClassFor - Return the register class that should be used for the
1896/// specified value type.
1897const TargetRegisterClass *
1898ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1899 (void)isDivergent;
1900 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1901 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1902 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1903 // MVE Q registers.
1904 if (Subtarget->hasNEON()) {
1905 if (VT == MVT::v4i64)
1906 return &ARM::QQPRRegClass;
1907 if (VT == MVT::v8i64)
1908 return &ARM::QQQQPRRegClass;
1909 }
1910 if (Subtarget->hasMVEIntegerOps()) {
1911 if (VT == MVT::v4i64)
1912 return &ARM::MQQPRRegClass;
1913 if (VT == MVT::v8i64)
1914 return &ARM::MQQQQPRRegClass;
1915 }
1916 return TargetLowering::getRegClassFor(VT);
1917}
1918
1919// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1920// source/dest is aligned and the copy size is large enough. We therefore want
1921// to align such objects passed to memory intrinsics.
1922bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1923 Align &PrefAlign) const {
1924 if (!isa<MemIntrinsic>(CI))
1925 return false;
1926 MinSize = 8;
1927 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1928 // cycle faster than 4-byte aligned LDM.
1929 PrefAlign =
1930 (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1931 return true;
1932}
1933
1934// Create a fast isel object.
1935FastISel *
1936ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1937 const TargetLibraryInfo *libInfo) const {
1938 return ARM::createFastISel(funcInfo, libInfo);
1939}
1940
1941Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1942 unsigned NumVals = N->getNumValues();
1943 if (!NumVals)
1944 return Sched::RegPressure;
1945
1946 for (unsigned i = 0; i != NumVals; ++i) {
1947 EVT VT = N->getValueType(i);
1948 if (VT == MVT::Glue || VT == MVT::Other)
1949 continue;
1950 if (VT.isFloatingPoint() || VT.isVector())
1951 return Sched::ILP;
1952 }
1953
1954 if (!N->isMachineOpcode())
1955 return Sched::RegPressure;
1956
1957 // Load are scheduled for latency even if there instruction itinerary
1958 // is not available.
1959 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1960 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1961
1962 if (MCID.getNumDefs() == 0)
1963 return Sched::RegPressure;
1964 if (!Itins->isEmpty() &&
1965 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1966 return Sched::ILP;
1967
1968 return Sched::RegPressure;
1969}
1970
1971//===----------------------------------------------------------------------===//
1972// Lowering Code
1973//===----------------------------------------------------------------------===//
1974
1975static bool isSRL16(const SDValue &Op) {
1976 if (Op.getOpcode() != ISD::SRL)
1977 return false;
1978 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1979 return Const->getZExtValue() == 16;
1980 return false;
1981}
1982
1983static bool isSRA16(const SDValue &Op) {
1984 if (Op.getOpcode() != ISD::SRA)
1985 return false;
1986 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1987 return Const->getZExtValue() == 16;
1988 return false;
1989}
1990
1991static bool isSHL16(const SDValue &Op) {
1992 if (Op.getOpcode() != ISD::SHL)
1993 return false;
1994 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1995 return Const->getZExtValue() == 16;
1996 return false;
1997}
1998
1999// Check for a signed 16-bit value. We special case SRA because it makes it
2000// more simple when also looking for SRAs that aren't sign extending a
2001// smaller value. Without the check, we'd need to take extra care with
2002// checking order for some operations.
2003static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
2004 if (isSRA16(Op))
2005 return isSHL16(Op.getOperand(0));
2006 return DAG.ComputeNumSignBits(Op) == 17;
2007}
2008
2009/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
2010static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
2011 switch (CC) {
2012 default: llvm_unreachable("Unknown condition code!")::llvm::llvm_unreachable_internal("Unknown condition code!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2012)
;
2013 case ISD::SETNE: return ARMCC::NE;
2014 case ISD::SETEQ: return ARMCC::EQ;
2015 case ISD::SETGT: return ARMCC::GT;
2016 case ISD::SETGE: return ARMCC::GE;
2017 case ISD::SETLT: return ARMCC::LT;
2018 case ISD::SETLE: return ARMCC::LE;
2019 case ISD::SETUGT: return ARMCC::HI;
2020 case ISD::SETUGE: return ARMCC::HS;
2021 case ISD::SETULT: return ARMCC::LO;
2022 case ISD::SETULE: return ARMCC::LS;
2023 }
2024}
2025
2026/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
2027static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
2028 ARMCC::CondCodes &CondCode2) {
2029 CondCode2 = ARMCC::AL;
2030 switch (CC) {
2031 default: llvm_unreachable("Unknown FP condition!")::llvm::llvm_unreachable_internal("Unknown FP condition!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2031)
;
2032 case ISD::SETEQ:
2033 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
2034 case ISD::SETGT:
2035 case ISD::SETOGT: CondCode = ARMCC::GT; break;
2036 case ISD::SETGE:
2037 case ISD::SETOGE: CondCode = ARMCC::GE; break;
2038 case ISD::SETOLT: CondCode = ARMCC::MI; break;
2039 case ISD::SETOLE: CondCode = ARMCC::LS; break;
2040 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
2041 case ISD::SETO: CondCode = ARMCC::VC; break;
2042 case ISD::SETUO: CondCode = ARMCC::VS; break;
2043 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
2044 case ISD::SETUGT: CondCode = ARMCC::HI; break;
2045 case ISD::SETUGE: CondCode = ARMCC::PL; break;
2046 case ISD::SETLT:
2047 case ISD::SETULT: CondCode = ARMCC::LT; break;
2048 case ISD::SETLE:
2049 case ISD::SETULE: CondCode = ARMCC::LE; break;
2050 case ISD::SETNE:
2051 case ISD::SETUNE: CondCode = ARMCC::NE; break;
2052 }
2053}
2054
2055//===----------------------------------------------------------------------===//
2056// Calling Convention Implementation
2057//===----------------------------------------------------------------------===//
2058
2059/// getEffectiveCallingConv - Get the effective calling convention, taking into
2060/// account presence of floating point hardware and calling convention
2061/// limitations, such as support for variadic functions.
2062CallingConv::ID
2063ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
2064 bool isVarArg) const {
2065 switch (CC) {
2066 default:
2067 report_fatal_error("Unsupported calling convention");
2068 case CallingConv::ARM_AAPCS:
2069 case CallingConv::ARM_APCS:
2070 case CallingConv::GHC:
2071 case CallingConv::CFGuard_Check:
2072 return CC;
2073 case CallingConv::PreserveMost:
2074 return CallingConv::PreserveMost;
2075 case CallingConv::ARM_AAPCS_VFP:
2076 case CallingConv::Swift:
2077 case CallingConv::SwiftTail:
2078 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
2079 case CallingConv::C:
2080 case CallingConv::Tail:
2081 if (!Subtarget->isAAPCS_ABI())
2082 return CallingConv::ARM_APCS;
2083 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
2084 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2085 !isVarArg)
2086 return CallingConv::ARM_AAPCS_VFP;
2087 else
2088 return CallingConv::ARM_AAPCS;
2089 case CallingConv::Fast:
2090 case CallingConv::CXX_FAST_TLS:
2091 if (!Subtarget->isAAPCS_ABI()) {
2092 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2093 return CallingConv::Fast;
2094 return CallingConv::ARM_APCS;
2095 } else if (Subtarget->hasVFP2Base() &&
2096 !Subtarget->isThumb1Only() && !isVarArg)
2097 return CallingConv::ARM_AAPCS_VFP;
2098 else
2099 return CallingConv::ARM_AAPCS;
2100 }
2101}
2102
2103CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2104 bool isVarArg) const {
2105 return CCAssignFnForNode(CC, false, isVarArg);
2106}
2107
2108CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2109 bool isVarArg) const {
2110 return CCAssignFnForNode(CC, true, isVarArg);
2111}
2112
2113/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2114/// CallingConvention.
2115CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2116 bool Return,
2117 bool isVarArg) const {
2118 switch (getEffectiveCallingConv(CC, isVarArg)) {
2119 default:
2120 report_fatal_error("Unsupported calling convention");
2121 case CallingConv::ARM_APCS:
2122 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2123 case CallingConv::ARM_AAPCS:
2124 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2125 case CallingConv::ARM_AAPCS_VFP:
2126 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2127 case CallingConv::Fast:
2128 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2129 case CallingConv::GHC:
2130 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2131 case CallingConv::PreserveMost:
2132 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2133 case CallingConv::CFGuard_Check:
2134 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2135 }
2136}
2137
2138SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2139 MVT LocVT, MVT ValVT, SDValue Val) const {
2140 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2141 Val);
2142 if (Subtarget->hasFullFP16()) {
2143 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2144 } else {
2145 Val = DAG.getNode(ISD::TRUNCATE, dl,
2146 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2147 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2148 }
2149 return Val;
2150}
2151
2152SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2153 MVT LocVT, MVT ValVT,
2154 SDValue Val) const {
2155 if (Subtarget->hasFullFP16()) {
2156 Val = DAG.getNode(ARMISD::VMOVrh, dl,
2157 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2158 } else {
2159 Val = DAG.getNode(ISD::BITCAST, dl,
2160 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2161 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2162 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2163 }
2164 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2165}
2166
2167/// LowerCallResult - Lower the result values of a call into the
2168/// appropriate copies out of appropriate physical registers.
2169SDValue ARMTargetLowering::LowerCallResult(
2170 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2171 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2172 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2173 SDValue ThisVal) const {
2174 // Assign locations to each value returned by this call.
2175 SmallVector<CCValAssign, 16> RVLocs;
2176 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2177 *DAG.getContext());
2178 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2179
2180 // Copy all of the result registers out of their specified physreg.
2181 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2182 CCValAssign VA = RVLocs[i];
2183
2184 // Pass 'this' value directly from the argument to return value, to avoid
2185 // reg unit interference
2186 if (i == 0 && isThisReturn) {
2187 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&(static_cast <bool> (!VA.needsCustom() && VA.getLocVT
() == MVT::i32 && "unexpected return calling convention register assignment"
) ? void (0) : __assert_fail ("!VA.needsCustom() && VA.getLocVT() == MVT::i32 && \"unexpected return calling convention register assignment\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2188, __extension__
__PRETTY_FUNCTION__))
2188 "unexpected return calling convention register assignment")(static_cast <bool> (!VA.needsCustom() && VA.getLocVT
() == MVT::i32 && "unexpected return calling convention register assignment"
) ? void (0) : __assert_fail ("!VA.needsCustom() && VA.getLocVT() == MVT::i32 && \"unexpected return calling convention register assignment\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2188, __extension__
__PRETTY_FUNCTION__))
;
2189 InVals.push_back(ThisVal);
2190 continue;
2191 }
2192
2193 SDValue Val;
2194 if (VA.needsCustom() &&
2195 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2196 // Handle f64 or half of a v2f64.
2197 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2198 InFlag);
2199 Chain = Lo.getValue(1);
2200 InFlag = Lo.getValue(2);
2201 VA = RVLocs[++i]; // skip ahead to next loc
2202 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2203 InFlag);
2204 Chain = Hi.getValue(1);
2205 InFlag = Hi.getValue(2);
2206 if (!Subtarget->isLittle())
2207 std::swap (Lo, Hi);
2208 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2209
2210 if (VA.getLocVT() == MVT::v2f64) {
2211 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2212 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2213 DAG.getConstant(0, dl, MVT::i32));
2214
2215 VA = RVLocs[++i]; // skip ahead to next loc
2216 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2217 Chain = Lo.getValue(1);
2218 InFlag = Lo.getValue(2);
2219 VA = RVLocs[++i]; // skip ahead to next loc
2220 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2221 Chain = Hi.getValue(1);
2222 InFlag = Hi.getValue(2);
2223 if (!Subtarget->isLittle())
2224 std::swap (Lo, Hi);
2225 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2226 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2227 DAG.getConstant(1, dl, MVT::i32));
2228 }
2229 } else {
2230 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2231 InFlag);
2232 Chain = Val.getValue(1);
2233 InFlag = Val.getValue(2);
2234 }
2235
2236 switch (VA.getLocInfo()) {
2237 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2237)
;
2238 case CCValAssign::Full: break;
2239 case CCValAssign::BCvt:
2240 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2241 break;
2242 }
2243
2244 // f16 arguments have their size extended to 4 bytes and passed as if they
2245 // had been copied to the LSBs of a 32-bit register.
2246 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2247 if (VA.needsCustom() &&
2248 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2249 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2250
2251 InVals.push_back(Val);
2252 }
2253
2254 return Chain;
2255}
2256
2257std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
2258 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
2259 bool IsTailCall, int SPDiff) const {
2260 SDValue DstAddr;
2261 MachinePointerInfo DstInfo;
2262 int32_t Offset = VA.getLocMemOffset();
2263 MachineFunction &MF = DAG.getMachineFunction();
2264
2265 if (IsTailCall) {
2266 Offset += SPDiff;
2267 auto PtrVT = getPointerTy(DAG.getDataLayout());
2268 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
2269 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
2270 DstAddr = DAG.getFrameIndex(FI, PtrVT);
2271 DstInfo =
2272 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
2273 } else {
2274 SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
2275 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2276 StackPtr, PtrOff);
2277 DstInfo =
2278 MachinePointerInfo::getStack(DAG.getMachineFunction(), Offset);
2279 }
2280
2281 return std::make_pair(DstAddr, DstInfo);
2282}
2283
2284void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2285 SDValue Chain, SDValue &Arg,
2286 RegsToPassVector &RegsToPass,
2287 CCValAssign &VA, CCValAssign &NextVA,
2288 SDValue &StackPtr,
2289 SmallVectorImpl<SDValue> &MemOpChains,
2290 bool IsTailCall,
2291 int SPDiff) const {
2292 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2293 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2294 unsigned id = Subtarget->isLittle() ? 0 : 1;
2295 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2296
2297 if (NextVA.isRegLoc())
2298 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2299 else {
2300 assert(NextVA.isMemLoc())(static_cast <bool> (NextVA.isMemLoc()) ? void (0) : __assert_fail
("NextVA.isMemLoc()", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2300, __extension__ __PRETTY_FUNCTION__))
;
2301 if (!StackPtr.getNode())
2302 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2303 getPointerTy(DAG.getDataLayout()));
2304
2305 SDValue DstAddr;
2306 MachinePointerInfo DstInfo;
2307 std::tie(DstAddr, DstInfo) =
2308 computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
2309 MemOpChains.push_back(
2310 DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
2311 }
2312}
2313
2314static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2315 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2316 CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
2317}
2318
2319/// LowerCall - Lowering a call into a callseq_start <-
2320/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2321/// nodes.
2322SDValue
2323ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2324 SmallVectorImpl<SDValue> &InVals) const {
2325 SelectionDAG &DAG = CLI.DAG;
2326 SDLoc &dl = CLI.DL;
2327 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2328 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2329 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2330 SDValue Chain = CLI.Chain;
2331 SDValue Callee = CLI.Callee;
2332 bool &isTailCall = CLI.IsTailCall;
2333 CallingConv::ID CallConv = CLI.CallConv;
2334 bool doesNotRet = CLI.DoesNotReturn;
2335 bool isVarArg = CLI.IsVarArg;
2336
2337 MachineFunction &MF = DAG.getMachineFunction();
2338 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2339 MachineFunction::CallSiteInfo CSInfo;
2340 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1
'?' condition is false
2341 bool isThisReturn = false;
2342 bool isCmseNSCall = false;
2343 bool isSibCall = false;
2344 bool PreferIndirect = false;
2345 bool GuardWithBTI = false;
2346
2347 // Lower 'returns_twice' calls to a pseudo-instruction.
2348 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
2
Assuming field 'CB' is null
2349 !Subtarget->noBTIAtReturnTwice())
2350 GuardWithBTI = AFI->branchTargetEnforcement();
2351
2352 // Determine whether this is a non-secure function call.
2353 if (CLI.CB
2.1
Field 'CB' is null
&& CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
3
Taking false branch
2354 isCmseNSCall = true;
2355
2356 // Disable tail calls if they're not supported.
2357 if (!Subtarget->supportsTailCall())
4
Assuming the condition is false
2358 isTailCall = false;
2359
2360 // For both the non-secure calls and the returns from a CMSE entry function,
2361 // the function needs to do some extra work afte r the call, or before the
2362 // return, respectively, thus it cannot end with atail call
2363 if (isCmseNSCall
4.1
'isCmseNSCall' is false
|| AFI->isCmseNSEntryFunction())
5
Assuming the condition is false
6
Taking false branch
2364 isTailCall = false;
2365
2366 if (isa<GlobalAddressSDNode>(Callee)) {
7
Assuming 'Callee' is not a 'GlobalAddressSDNode'
8
Taking false branch
2367 // If we're optimizing for minimum size and the function is called three or
2368 // more times in this block, we can improve codesize by calling indirectly
2369 // as BLXr has a 16-bit encoding.
2370 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2371 if (CLI.CB) {
2372 auto *BB = CLI.CB->getParent();
2373 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2374 count_if(GV->users(), [&BB](const User *U) {
2375 return isa<Instruction>(U) &&
2376 cast<Instruction>(U)->getParent() == BB;
2377 }) > 2;
2378 }
2379 }
2380 if (isTailCall) {
9
Assuming 'isTailCall' is false
2381 // Check if it's really possible to do a tail call.
2382 isTailCall = IsEligibleForTailCallOptimization(
2383 Callee, CallConv, isVarArg, isStructRet,
2384 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2385 PreferIndirect);
2386
2387 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2388 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2389 isSibCall = true;
2390
2391 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2392 // detected sibcalls.
2393 if (isTailCall)
2394 ++NumTailCalls;
2395 }
2396
2397 if (!isTailCall
9.1
'isTailCall' is false
&& CLI.CB
9.2
Field 'CB' is null
&& CLI.CB->isMustTailCall())
2398 report_fatal_error("failed to perform tail call elimination on a call "
2399 "site marked musttail");
2400 // Analyze operands of the call, assigning locations to each operand.
2401 SmallVector<CCValAssign, 16> ArgLocs;
2402 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2403 *DAG.getContext());
2404 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2405
2406 // Get a count of how many bytes are to be pushed on the stack.
2407 unsigned NumBytes = CCInfo.getNextStackOffset();
2408
2409 // SPDiff is the byte offset of the call's argument area from the callee's.
2410 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2411 // by this amount for a tail call. In a sibling call it must be 0 because the
2412 // caller will deallocate the entire stack and the callee still expects its
2413 // arguments to begin at SP+0. Completely unused for non-tail calls.
2414 int SPDiff = 0;
2415
2416 if (isTailCall && !isSibCall) {
10
Assuming 'isTailCall' is false
2417 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2418 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2419
2420 // Since callee will pop argument stack as a tail call, we must keep the
2421 // popped size 16-byte aligned.
2422 Align StackAlign = DAG.getDataLayout().getStackAlignment();
2423 NumBytes = alignTo(NumBytes, StackAlign);
2424
2425 // SPDiff will be negative if this tail call requires more space than we
2426 // would automatically have in our incoming argument space. Positive if we
2427 // can actually shrink the stack.
2428 SPDiff = NumReusableBytes - NumBytes;
2429
2430 // If this call requires more stack than we have available from
2431 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2432 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2433 AFI->setArgRegsSaveSize(-SPDiff);
2434 }
2435
2436 if (isSibCall
10.1
'isSibCall' is false
) {
11
Taking false branch
2437 // For sibling tail calls, memory operands are available in our caller's stack.
2438 NumBytes = 0;
2439 } else {
2440 // Adjust the stack pointer for the new arguments...
2441 // These operations are automatically eliminated by the prolog/epilog pass
2442 Chain = DAG.getCALLSEQ_START(Chain, isTailCall
11.1
'isTailCall' is false
? 0 : NumBytes, 0, dl);
12
'?' condition is false
2443 }
2444
2445 SDValue StackPtr =
2446 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2447
2448 RegsToPassVector RegsToPass;
2449 SmallVector<SDValue, 8> MemOpChains;
2450
2451 // During a tail call, stores to the argument area must happen after all of
2452 // the function's incoming arguments have been loaded because they may alias.
2453 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2454 // there's no point in doing so repeatedly so this tracks whether that's
2455 // happened yet.
2456 bool AfterFormalArgLoads = false;
2457
2458 // Walk the register/memloc assignments, inserting copies/loads. In the case
2459 // of tail call optimization, arguments are handled later.
2460 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
14
Loop condition is false. Execution continues on line 2614
2461 i != e;
13
Assuming 'i' is equal to 'e'
2462 ++i, ++realArgIdx) {
2463 CCValAssign &VA = ArgLocs[i];
2464 SDValue Arg = OutVals[realArgIdx];
2465 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2466 bool isByVal = Flags.isByVal();
2467
2468 // Promote the value if needed.
2469 switch (VA.getLocInfo()) {
2470 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2470)
;
2471 case CCValAssign::Full: break;
2472 case CCValAssign::SExt:
2473 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2474 break;
2475 case CCValAssign::ZExt:
2476 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2477 break;
2478 case CCValAssign::AExt:
2479 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2480 break;
2481 case CCValAssign::BCvt:
2482 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2483 break;
2484 }
2485
2486 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2487 Chain = DAG.getStackArgumentTokenFactor(Chain);
2488 AfterFormalArgLoads = true;
2489 }
2490
2491 // f16 arguments have their size extended to 4 bytes and passed as if they
2492 // had been copied to the LSBs of a 32-bit register.
2493 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2494 if (VA.needsCustom() &&
2495 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2496 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2497 } else {
2498 // f16 arguments could have been extended prior to argument lowering.
2499 // Mask them arguments if this is a CMSE nonsecure call.
2500 auto ArgVT = Outs[realArgIdx].ArgVT;
2501 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2502 auto LocBits = VA.getLocVT().getSizeInBits();
2503 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2504 SDValue Mask =
2505 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2506 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2507 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2508 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2509 }
2510 }
2511
2512 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2513 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2514 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2515 DAG.getConstant(0, dl, MVT::i32));
2516 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2517 DAG.getConstant(1, dl, MVT::i32));
2518
2519 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2520 StackPtr, MemOpChains, isTailCall, SPDiff);
2521
2522 VA = ArgLocs[++i]; // skip ahead to next loc
2523 if (VA.isRegLoc()) {
2524 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2525 StackPtr, MemOpChains, isTailCall, SPDiff);
2526 } else {
2527 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "llvm/lib/Target/ARM/ARMISelLowering.cpp",
2527, __extension__ __PRETTY_FUNCTION__))
;
2528 SDValue DstAddr;
2529 MachinePointerInfo DstInfo;
2530 std::tie(DstAddr, DstInfo) =
2531 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2532 MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2533 }
2534 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2535 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2536 StackPtr, MemOpChains, isTailCall, SPDiff);
2537 } else if (VA.isRegLoc()) {
2538 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2539 Outs[0].VT == MVT::i32) {
2540 assert(VA.getLocVT() == MVT::i32 &&(static_cast <bool> (VA.getLocVT() == MVT::i32 &&
"unexpected calling convention register assignment") ? void (
0) : __assert_fail ("VA.getLocVT() == MVT::i32 && \"unexpected calling convention register assignment\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2541, __extension__
__PRETTY_FUNCTION__))
2541 "unexpected calling convention register assignment")(static_cast <bool> (VA.getLocVT() == MVT::i32 &&
"unexpected calling convention register assignment") ? void (
0) : __assert_fail ("VA.getLocVT() == MVT::i32 && \"unexpected calling convention register assignment\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2541, __extension__
__PRETTY_FUNCTION__))
;
2542 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&(static_cast <bool> (!Ins.empty() && Ins[0].VT ==
MVT::i32 && "unexpected use of 'returned'") ? void (
0) : __assert_fail ("!Ins.empty() && Ins[0].VT == MVT::i32 && \"unexpected use of 'returned'\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2543, __extension__
__PRETTY_FUNCTION__))
2543 "unexpected use of 'returned'")(static_cast <bool> (!Ins.empty() && Ins[0].VT ==
MVT::i32 && "unexpected use of 'returned'") ? void (
0) : __assert_fail ("!Ins.empty() && Ins[0].VT == MVT::i32 && \"unexpected use of 'returned'\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2543, __extension__
__PRETTY_FUNCTION__))
;
2544 isThisReturn = true;
2545 }
2546 const TargetOptions &Options = DAG.getTarget().Options;
2547 if (Options.EmitCallSiteInfo)
2548 CSInfo.emplace_back(VA.getLocReg(), i);
2549 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2550 } else if (isByVal) {
2551 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "llvm/lib/Target/ARM/ARMISelLowering.cpp",
2551, __extension__ __PRETTY_FUNCTION__))
;
2552 unsigned offset = 0;
2553
2554 // True if this byval aggregate will be split between registers
2555 // and memory.
2556 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2557 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2558
2559 if (CurByValIdx < ByValArgsCount) {
2560
2561 unsigned RegBegin, RegEnd;
2562 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2563
2564 EVT PtrVT =
2565 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2566 unsigned int i, j;
2567 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2568 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2569 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2570 SDValue Load =
2571 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2572 DAG.InferPtrAlign(AddArg));
2573 MemOpChains.push_back(Load.getValue(1));
2574 RegsToPass.push_back(std::make_pair(j, Load));
2575 }
2576
2577 // If parameter size outsides register area, "offset" value
2578 // helps us to calculate stack slot for remained part properly.
2579 offset = RegEnd - RegBegin;
2580
2581 CCInfo.nextInRegsParam();
2582 }
2583
2584 if (Flags.getByValSize() > 4*offset) {
2585 auto PtrVT = getPointerTy(DAG.getDataLayout());
2586 SDValue Dst;
2587 MachinePointerInfo DstInfo;
2588 std::tie(Dst, DstInfo) =
2589 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2590 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2591 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2592 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2593 MVT::i32);
2594 SDValue AlignNode =
2595 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2596
2597 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2598 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2599 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2600 Ops));
2601 }
2602 } else {
2603 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "llvm/lib/Target/ARM/ARMISelLowering.cpp",
2603, __extension__ __PRETTY_FUNCTION__))
;
2604 SDValue DstAddr;
2605 MachinePointerInfo DstInfo;
2606 std::tie(DstAddr, DstInfo) =
2607 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2608
2609 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2610 MemOpChains.push_back(Store);
2611 }
2612 }
2613
2614 if (!MemOpChains.empty())
15
Taking true branch
2615 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2616
2617 // Build a sequence of copy-to-reg nodes chained together with token chain
2618 // and flag operands which copy the outgoing args into the appropriate regs.
2619 SDValue InFlag;
2620 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
16
Assuming 'i' is equal to 'e'
17
Loop condition is false. Execution continues on line 2629
2621 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2622 RegsToPass[i].second, InFlag);
2623 InFlag = Chain.getValue(1);
2624 }
2625
2626 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2627 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2628 // node so that legalize doesn't hack it.
2629 bool isDirect = false;
2630
2631 const TargetMachine &TM = getTargetMachine();
2632 const Module *Mod = MF.getFunction().getParent();
2633 const GlobalValue *GV = nullptr;
18
'GV' initialized to a null pointer value
2634 if (GlobalAddressSDNode *G
18.1
'G' is null
= dyn_cast<GlobalAddressSDNode>(Callee))
2635 GV = G->getGlobal();
2636 bool isStub =
2637 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
19
Assuming the condition is false
2638
2639 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
20
Assuming the condition is true
2640 bool isLocalARMFunc = false;
2641 auto PtrVt = getPointerTy(DAG.getDataLayout());
2642
2643 if (Subtarget->genLongCalls()) {
21
Assuming the condition is false
22
Taking false branch
2644 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&(static_cast <bool> ((!isPositionIndependent() || Subtarget
->isTargetWindows()) && "long-calls codegen is not position independent!"
) ? void (0) : __assert_fail ("(!isPositionIndependent() || Subtarget->isTargetWindows()) && \"long-calls codegen is not position independent!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2645, __extension__
__PRETTY_FUNCTION__))
2645 "long-calls codegen is not position independent!")(static_cast <bool> ((!isPositionIndependent() || Subtarget
->isTargetWindows()) && "long-calls codegen is not position independent!"
) ? void (0) : __assert_fail ("(!isPositionIndependent() || Subtarget->isTargetWindows()) && \"long-calls codegen is not position independent!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2645, __extension__
__PRETTY_FUNCTION__))
;
2646 // Handle a global address or an external symbol. If it's not one of
2647 // those, the target's already in a register, so we don't need to do
2648 // anything extra.
2649 if (isa<GlobalAddressSDNode>(Callee)) {
2650 // Create a constant pool entry for the callee address
2651 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2652 ARMConstantPoolValue *CPV =
2653 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2654
2655 // Get the address of the callee into a register
2656 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2657 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2658 Callee = DAG.getLoad(
2659 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2660 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2661 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2662 const char *Sym = S->getSymbol();
2663
2664 // Create a constant pool entry for the callee address
2665 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2666 ARMConstantPoolValue *CPV =
2667 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2668 ARMPCLabelIndex, 0);
2669 // Get the address of the callee into a register
2670 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2671 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2672 Callee = DAG.getLoad(
2673 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2674 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2675 }
2676 } else if (isa<GlobalAddressSDNode>(Callee)) {
23
Assuming 'Callee' is a 'class llvm::GlobalAddressSDNode &'
24
Taking true branch
2677 if (!PreferIndirect
24.1
'PreferIndirect' is false
) {
25
Taking true branch
2678 isDirect = true;
2679 bool isDef = GV->isStrongDefinitionForLinker();
26
Called C++ object pointer is null
2680
2681 // ARM call to a local ARM function is predicable.
2682 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2683 // tBX takes a register source operand.
2684 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2685 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?")(static_cast <bool> (Subtarget->isTargetMachO() &&
"WrapperPIC use on non-MachO?") ? void (0) : __assert_fail (
"Subtarget->isTargetMachO() && \"WrapperPIC use on non-MachO?\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2685, __extension__
__PRETTY_FUNCTION__))
;
2686 Callee = DAG.getNode(
2687 ARMISD::WrapperPIC, dl, PtrVt,
2688 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2689 Callee = DAG.getLoad(
2690 PtrVt, dl, DAG.getEntryNode(), Callee,
2691 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2692 MachineMemOperand::MODereferenceable |
2693 MachineMemOperand::MOInvariant);
2694 } else if (Subtarget->isTargetCOFF()) {
2695 assert(Subtarget->isTargetWindows() &&(static_cast <bool> (Subtarget->isTargetWindows() &&
"Windows is the only supported COFF target") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"Windows is the only supported COFF target\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2696, __extension__
__PRETTY_FUNCTION__))
2696 "Windows is the only supported COFF target")(static_cast <bool> (Subtarget->isTargetWindows() &&
"Windows is the only supported COFF target") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"Windows is the only supported COFF target\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2696, __extension__
__PRETTY_FUNCTION__))
;
2697 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2698 if (GV->hasDLLImportStorageClass())
2699 TargetFlags = ARMII::MO_DLLIMPORT;
2700 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2701 TargetFlags = ARMII::MO_COFFSTUB;
2702 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2703 TargetFlags);
2704 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2705 Callee =
2706 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2707 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2708 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2709 } else {
2710 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2711 }
2712 }
2713 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2714 isDirect = true;
2715 // tBX takes a register source operand.
2716 const char *Sym = S->getSymbol();
2717 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2718 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2719 ARMConstantPoolValue *CPV =
2720 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2721 ARMPCLabelIndex, 4);
2722 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2723 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2724 Callee = DAG.getLoad(
2725 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2726 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2727 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2728 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2729 } else {
2730 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2731 }
2732 }
2733
2734 if (isCmseNSCall) {
2735 assert(!isARMFunc && !isDirect &&(static_cast <bool> (!isARMFunc && !isDirect &&
"Cannot handle call to ARM function or direct call") ? void (
0) : __assert_fail ("!isARMFunc && !isDirect && \"Cannot handle call to ARM function or direct call\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2736, __extension__
__PRETTY_FUNCTION__))
2736 "Cannot handle call to ARM function or direct call")(static_cast <bool> (!isARMFunc && !isDirect &&
"Cannot handle call to ARM function or direct call") ? void (
0) : __assert_fail ("!isARMFunc && !isDirect && \"Cannot handle call to ARM function or direct call\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2736, __extension__
__PRETTY_FUNCTION__))
;
2737 if (NumBytes > 0) {
2738 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2739 "call to non-secure function would "
2740 "require passing arguments on stack",
2741 dl.getDebugLoc());
2742 DAG.getContext()->diagnose(Diag);
2743 }
2744 if (isStructRet) {
2745 DiagnosticInfoUnsupported Diag(
2746 DAG.getMachineFunction().getFunction(),
2747 "call to non-secure function would return value through pointer",
2748 dl.getDebugLoc());
2749 DAG.getContext()->diagnose(Diag);
2750 }
2751 }
2752
2753 // FIXME: handle tail calls differently.
2754 unsigned CallOpc;
2755 if (Subtarget->isThumb()) {
2756 if (GuardWithBTI)
2757 CallOpc = ARMISD::t2CALL_BTI;
2758 else if (isCmseNSCall)
2759 CallOpc = ARMISD::tSECALL;
2760 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2761 CallOpc = ARMISD::CALL_NOLINK;
2762 else
2763 CallOpc = ARMISD::CALL;
2764 } else {
2765 if (!isDirect && !Subtarget->hasV5TOps())
2766 CallOpc = ARMISD::CALL_NOLINK;
2767 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2768 // Emit regular call when code size is the priority
2769 !Subtarget->hasMinSize())
2770 // "mov lr, pc; b _foo" to avoid confusing the RSP
2771 CallOpc = ARMISD::CALL_NOLINK;
2772 else
2773 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2774 }
2775
2776 // We don't usually want to end the call-sequence here because we would tidy
2777 // the frame up *after* the call, however in the ABI-changing tail-call case
2778 // we've carefully laid out the parameters so that when sp is reset they'll be
2779 // in the correct location.
2780 if (isTailCall && !isSibCall) {
2781 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, dl);
2782 InFlag = Chain.getValue(1);
2783 }
2784
2785 std::vector<SDValue> Ops;
2786 Ops.push_back(Chain);
2787 Ops.push_back(Callee);
2788
2789 if (isTailCall) {
2790 Ops.push_back(DAG.getTargetConstant(SPDiff, dl, MVT::i32));
2791 }
2792
2793 // Add argument registers to the end of the list so that they are known live
2794 // into the call.
2795 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2796 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2797 RegsToPass[i].second.getValueType()));
2798
2799 // Add a register mask operand representing the call-preserved registers.
2800 const uint32_t *Mask;
2801 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2802 if (isThisReturn) {
2803 // For 'this' returns, use the R0-preserving mask if applicable
2804 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2805 if (!Mask) {
2806 // Set isThisReturn to false if the calling convention is not one that
2807 // allows 'returned' to be modeled in this way, so LowerCallResult does
2808 // not try to pass 'this' straight through
2809 isThisReturn = false;
2810 Mask = ARI->getCallPreservedMask(MF, CallConv);
2811 }
2812 } else
2813 Mask = ARI->getCallPreservedMask(MF, CallConv);
2814
2815 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2815, __extension__
__PRETTY_FUNCTION__))
;
2816 Ops.push_back(DAG.getRegisterMask(Mask));
2817
2818 if (InFlag.getNode())
2819 Ops.push_back(InFlag);
2820
2821 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2822 if (isTailCall) {
2823 MF.getFrameInfo().setHasTailCall();
2824 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2825 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2826 return Ret;
2827 }
2828
2829 // Returns a chain and a flag for retval copy to use.
2830 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2831 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2832 InFlag = Chain.getValue(1);
2833 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2834
2835 // If we're guaranteeing tail-calls will be honoured, the callee must
2836 // pop its own argument stack on return. But this call is *not* a tail call so
2837 // we need to undo that after it returns to restore the status-quo.
2838 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2839 uint64_t CalleePopBytes =
2840 canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1ULL;
2841
2842 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InFlag, dl);
2843 if (!Ins.empty())
2844 InFlag = Chain.getValue(1);
2845
2846 // Handle result values, copying them out of physregs into vregs that we
2847 // return.
2848 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2849 InVals, isThisReturn,
2850 isThisReturn ? OutVals[0] : SDValue());
2851}
2852
2853/// HandleByVal - Every parameter *after* a byval parameter is passed
2854/// on the stack. Remember the next parameter register to allocate,
2855/// and then confiscate the rest of the parameter registers to insure
2856/// this.
2857void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2858 Align Alignment) const {
2859 // Byval (as with any stack) slots are always at least 4 byte aligned.
2860 Alignment = std::max(Alignment, Align(4));
2861
2862 unsigned Reg = State->AllocateReg(GPRArgRegs);
2863 if (!Reg)
2864 return;
2865
2866 unsigned AlignInRegs = Alignment.value() / 4;
2867 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2868 for (unsigned i = 0; i < Waste; ++i)
2869 Reg = State->AllocateReg(GPRArgRegs);
2870
2871 if (!Reg)
2872 return;
2873
2874 unsigned Excess = 4 * (ARM::R4 - Reg);
2875
2876 // Special case when NSAA != SP and parameter size greater than size of
2877 // all remained GPR regs. In that case we can't split parameter, we must
2878 // send it to stack. We also must set NCRN to R4, so waste all
2879 // remained registers.
2880 const unsigned NSAAOffset = State->getNextStackOffset();
2881 if (NSAAOffset != 0 && Size > Excess) {
2882 while (State->AllocateReg(GPRArgRegs))
2883 ;
2884 return;
2885 }
2886
2887 // First register for byval parameter is the first register that wasn't
2888 // allocated before this method call, so it would be "reg".
2889 // If parameter is small enough to be saved in range [reg, r4), then
2890 // the end (first after last) register would be reg + param-size-in-regs,
2891 // else parameter would be splitted between registers and stack,
2892 // end register would be r4 in this case.
2893 unsigned ByValRegBegin = Reg;
2894 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2895 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2896 // Note, first register is allocated in the beginning of function already,
2897 // allocate remained amount of registers we need.
2898 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2899 State->AllocateReg(GPRArgRegs);
2900 // A byval parameter that is split between registers and memory needs its
2901 // size truncated here.
2902 // In the case where the entire structure fits in registers, we set the
2903 // size in memory to zero.
2904 Size = std::max<int>(Size - Excess, 0);
2905}
2906
2907/// MatchingStackOffset - Return true if the given stack call argument is
2908/// already available in the same position (relatively) of the caller's
2909/// incoming argument stack.
2910static
2911bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2912 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2913 const TargetInstrInfo *TII) {
2914 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2915 int FI = std::numeric_limits<int>::max();
2916 if (Arg.getOpcode() == ISD::CopyFromReg) {
2917 Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2918 if (!Register::isVirtualRegister(VR))
2919 return false;
2920 MachineInstr *Def = MRI->getVRegDef(VR);
2921 if (!Def)
2922 return false;
2923 if (!Flags.isByVal()) {
2924 if (!TII->isLoadFromStackSlot(*Def, FI))
2925 return false;
2926 } else {
2927 return false;
2928 }
2929 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2930 if (Flags.isByVal())
2931 // ByVal argument is passed in as a pointer but it's now being
2932 // dereferenced. e.g.
2933 // define @foo(%struct.X* %A) {
2934 // tail call @bar(%struct.X* byval %A)
2935 // }
2936 return false;
2937 SDValue Ptr = Ld->getBasePtr();
2938 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2939 if (!FINode)
2940 return false;
2941 FI = FINode->getIndex();
2942 } else
2943 return false;
2944
2945 assert(FI != std::numeric_limits<int>::max())(static_cast <bool> (FI != std::numeric_limits<int>
::max()) ? void (0) : __assert_fail ("FI != std::numeric_limits<int>::max()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2945, __extension__
__PRETTY_FUNCTION__))
;
2946 if (!MFI.isFixedObjectIndex(FI))
2947 return false;
2948 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2949}
2950
2951/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2952/// for tail call optimization. Targets which want to do tail call
2953/// optimization should implement this function.
2954bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2955 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2956 bool isCalleeStructRet, bool isCallerStructRet,
2957 const SmallVectorImpl<ISD::OutputArg> &Outs,
2958 const SmallVectorImpl<SDValue> &OutVals,
2959 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2960 const bool isIndirect) const {
2961 MachineFunction &MF = DAG.getMachineFunction();
2962 const Function &CallerF = MF.getFunction();
2963 CallingConv::ID CallerCC = CallerF.getCallingConv();
2964
2965 assert(Subtarget->supportsTailCall())(static_cast <bool> (Subtarget->supportsTailCall()) ?
void (0) : __assert_fail ("Subtarget->supportsTailCall()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 2965, __extension__
__PRETTY_FUNCTION__))
;
2966
2967 // Indirect tail calls cannot be optimized for Thumb1 if the args
2968 // to the call take up r0-r3. The reason is that there are no legal registers
2969 // left to hold the pointer to the function to be called.
2970 // Similarly, if the function uses return address sign and authentication,
2971 // r12 is needed to hold the PAC and is not available to hold the callee
2972 // address.
2973 if (Outs.size() >= 4 &&
2974 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) {
2975 if (Subtarget->isThumb1Only())
2976 return false;
2977 // Conservatively assume the function spills LR.
2978 if (MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(true))
2979 return false;
2980 }
2981
2982 // Look for obvious safe cases to perform tail call optimization that do not
2983 // require ABI changes. This is what gcc calls sibcall.
2984
2985 // Exception-handling functions need a special set of instructions to indicate
2986 // a return to the hardware. Tail-calling another function would probably
2987 // break this.
2988 if (CallerF.hasFnAttribute("interrupt"))
2989 return false;
2990
2991 if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
2992 return CalleeCC == CallerCC;
2993
2994 // Also avoid sibcall optimization if either caller or callee uses struct
2995 // return semantics.
2996 if (isCalleeStructRet || isCallerStructRet)
2997 return false;
2998
2999 // Externally-defined functions with weak linkage should not be
3000 // tail-called on ARM when the OS does not support dynamic
3001 // pre-emption of symbols, as the AAELF spec requires normal calls
3002 // to undefined weak functions to be replaced with a NOP or jump to the
3003 // next instruction. The behaviour of branch instructions in this
3004 // situation (as used for tail calls) is implementation-defined, so we
3005 // cannot rely on the linker replacing the tail call with a return.
3006 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3007 const GlobalValue *GV = G->getGlobal();
3008 const Triple &TT = getTargetMachine().getTargetTriple();
3009 if (GV->hasExternalWeakLinkage() &&
3010 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3011 return false;
3012 }
3013
3014 // Check that the call results are passed in the same way.
3015 LLVMContext &C = *DAG.getContext();
3016 if (!CCState::resultsCompatible(
3017 getEffectiveCallingConv(CalleeCC, isVarArg),
3018 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
3019 CCAssignFnForReturn(CalleeCC, isVarArg),
3020 CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
3021 return false;
3022 // The callee has to preserve all registers the caller needs to preserve.
3023 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3024 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3025 if (CalleeCC != CallerCC) {
3026 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3027 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3028 return false;
3029 }
3030
3031 // If Caller's vararg or byval argument has been split between registers and
3032 // stack, do not perform tail call, since part of the argument is in caller's
3033 // local frame.
3034 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
3035 if (AFI_Caller->getArgRegsSaveSize())
3036 return false;
3037
3038 // If the callee takes no arguments then go on to check the results of the
3039 // call.
3040 if (!Outs.empty()) {
3041 // Check if stack adjustment is needed. For now, do not do this if any
3042 // argument is passed on the stack.
3043 SmallVector<CCValAssign, 16> ArgLocs;
3044 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3045 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3046 if (CCInfo.getNextStackOffset()) {
3047 // Check if the arguments are already laid out in the right way as
3048 // the caller's fixed stack objects.
3049 MachineFrameInfo &MFI = MF.getFrameInfo();
3050 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3051 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3052 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
3053 i != e;
3054 ++i, ++realArgIdx) {
3055 CCValAssign &VA = ArgLocs[i];
3056 EVT RegVT = VA.getLocVT();
3057 SDValue Arg = OutVals[realArgIdx];
3058 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3059 if (VA.getLocInfo() == CCValAssign::Indirect)
3060 return false;
3061 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
3062 // f64 and vector types are split into multiple registers or
3063 // register/stack-slot combinations. The types will not match
3064 // the registers; give up on memory f64 refs until we figure
3065 // out what to do about this.
3066 if (!VA.isRegLoc())
3067 return false;
3068 if (!ArgLocs[++i].isRegLoc())
3069 return false;
3070 if (RegVT == MVT::v2f64) {
3071 if (!ArgLocs[++i].isRegLoc())
3072 return false;
3073 if (!ArgLocs[++i].isRegLoc())
3074 return false;
3075 }
3076 } else if (!VA.isRegLoc()) {
3077 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3078 MFI, MRI, TII))
3079 return false;
3080 }
3081 }
3082 }
3083
3084 const MachineRegisterInfo &MRI = MF.getRegInfo();
3085 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3086 return false;
3087 }
3088
3089 return true;
3090}
3091
3092bool
3093ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3094 MachineFunction &MF, bool isVarArg,
3095 const SmallVectorImpl<ISD::OutputArg> &Outs,
3096 LLVMContext &Context) const {
3097 SmallVector<CCValAssign, 16> RVLocs;
3098 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3099 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3100}
3101
3102static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3103 const SDLoc &DL, SelectionDAG &DAG) {
3104 const MachineFunction &MF = DAG.getMachineFunction();
3105 const Function &F = MF.getFunction();
3106
3107 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
3108
3109 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
3110 // version of the "preferred return address". These offsets affect the return
3111 // instruction if this is a return from PL1 without hypervisor extensions.
3112 // IRQ/FIQ: +4 "subs pc, lr, #4"
3113 // SWI: 0 "subs pc, lr, #0"
3114 // ABORT: +4 "subs pc, lr, #4"
3115 // UNDEF: +4/+2 "subs pc, lr, #0"
3116 // UNDEF varies depending on where the exception came from ARM or Thumb
3117 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
3118
3119 int64_t LROffset;
3120 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
3121 IntKind == "ABORT")
3122 LROffset = 4;
3123 else if (IntKind == "SWI" || IntKind == "UNDEF")
3124 LROffset = 0;
3125 else
3126 report_fatal_error("Unsupported interrupt attribute. If present, value "
3127 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
3128
3129 RetOps.insert(RetOps.begin() + 1,
3130 DAG.getConstant(LROffset, DL, MVT::i32, false));
3131
3132 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
3133}
3134
3135SDValue
3136ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3137 bool isVarArg,
3138 const SmallVectorImpl<ISD::OutputArg> &Outs,
3139 const SmallVectorImpl<SDValue> &OutVals,
3140 const SDLoc &dl, SelectionDAG &DAG) const {
3141 // CCValAssign - represent the assignment of the return value to a location.
3142 SmallVector<CCValAssign, 16> RVLocs;
3143
3144 // CCState - Info about the registers and stack slots.
3145 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3146 *DAG.getContext());
3147
3148 // Analyze outgoing return values.
3149 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3150
3151 SDValue Flag;
3152 SmallVector<SDValue, 4> RetOps;
3153 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3154 bool isLittleEndian = Subtarget->isLittle();
3155
3156 MachineFunction &MF = DAG.getMachineFunction();
3157 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3158 AFI->setReturnRegsCount(RVLocs.size());
3159
3160 // Report error if cmse entry function returns structure through first ptr arg.
3161 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
3162 // Note: using an empty SDLoc(), as the first line of the function is a
3163 // better place to report than the last line.
3164 DiagnosticInfoUnsupported Diag(
3165 DAG.getMachineFunction().getFunction(),
3166 "secure entry function would return value through pointer",
3167 SDLoc().getDebugLoc());
3168 DAG.getContext()->diagnose(Diag);
3169 }
3170
3171 // Copy the result values into the output registers.
3172 for (unsigned i = 0, realRVLocIdx = 0;
3173 i != RVLocs.size();
3174 ++i, ++realRVLocIdx) {
3175 CCValAssign &VA = RVLocs[i];
3176 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3176, __extension__
__PRETTY_FUNCTION__))
;
3177
3178 SDValue Arg = OutVals[realRVLocIdx];
3179 bool ReturnF16 = false;
3180
3181 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
3182 // Half-precision return values can be returned like this:
3183 //
3184 // t11 f16 = fadd ...
3185 // t12: i16 = bitcast t11
3186 // t13: i32 = zero_extend t12
3187 // t14: f32 = bitcast t13 <~~~~~~~ Arg
3188 //
3189 // to avoid code generation for bitcasts, we simply set Arg to the node
3190 // that produces the f16 value, t11 in this case.
3191 //
3192 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3193 SDValue ZE = Arg.getOperand(0);
3194 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3195 SDValue BC = ZE.getOperand(0);
3196 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3197 Arg = BC.getOperand(0);
3198 ReturnF16 = true;
3199 }
3200 }
3201 }
3202 }
3203
3204 switch (VA.getLocInfo()) {
3205 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3205)
;
3206 case CCValAssign::Full: break;
3207 case CCValAssign::BCvt:
3208 if (!ReturnF16)
3209 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3210 break;
3211 }
3212
3213 // Mask f16 arguments if this is a CMSE nonsecure entry.
3214 auto RetVT = Outs[realRVLocIdx].ArgVT;
3215 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3216 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3217 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3218 } else {
3219 auto LocBits = VA.getLocVT().getSizeInBits();
3220 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3221 SDValue Mask =
3222 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3223 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3224 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3225 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3226 }
3227 }
3228
3229 if (VA.needsCustom() &&
3230 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3231 if (VA.getLocVT() == MVT::v2f64) {
3232 // Extract the first half and return it in two registers.
3233 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3234 DAG.getConstant(0, dl, MVT::i32));
3235 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3236 DAG.getVTList(MVT::i32, MVT::i32), Half);
3237
3238 Chain =
3239 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3240 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag);
3241 Flag = Chain.getValue(1);
3242 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3243 VA = RVLocs[++i]; // skip ahead to next loc
3244 Chain =
3245 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3246 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag);
3247 Flag = Chain.getValue(1);
3248 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3249 VA = RVLocs[++i]; // skip ahead to next loc
3250
3251 // Extract the 2nd half and fall through to handle it as an f64 value.
3252 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3253 DAG.getConstant(1, dl, MVT::i32));
3254 }
3255 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3256 // available.
3257 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3258 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3259 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3260 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag);
3261 Flag = Chain.getValue(1);
3262 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3263 VA = RVLocs[++i]; // skip ahead to next loc
3264 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3265 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag);
3266 } else
3267 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
3268
3269 // Guarantee that all emitted copies are
3270 // stuck together, avoiding something bad.
3271 Flag = Chain.getValue(1);
3272 RetOps.push_back(DAG.getRegister(
3273 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3274 }
3275 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3276 const MCPhysReg *I =
3277 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3278 if (I) {
3279 for (; *I; ++I) {
3280 if (ARM::GPRRegClass.contains(*I))
3281 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3282 else if (ARM::DPRRegClass.contains(*I))
3283 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3284 else
3285 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3285)
;
3286 }
3287 }
3288
3289 // Update chain and glue.
3290 RetOps[0] = Chain;
3291 if (Flag.getNode())
3292 RetOps.push_back(Flag);
3293
3294 // CPUs which aren't M-class use a special sequence to return from
3295 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3296 // though we use "subs pc, lr, #N").
3297 //
3298 // M-class CPUs actually use a normal return sequence with a special
3299 // (hardware-provided) value in LR, so the normal code path works.
3300 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3301 !Subtarget->isMClass()) {
3302 if (Subtarget->isThumb1Only())
3303 report_fatal_error("interrupt attribute is not supported in Thumb1");
3304 return LowerInterruptReturn(RetOps, dl, DAG);
3305 }
3306
3307 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
3308 ARMISD::RET_FLAG;
3309 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3310}
3311
3312bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3313 if (N->getNumValues() != 1)
3314 return false;
3315 if (!N->hasNUsesOfValue(1, 0))
3316 return false;
3317
3318 SDValue TCChain = Chain;
3319 SDNode *Copy = *N->use_begin();
3320 if (Copy->getOpcode() == ISD::CopyToReg) {
3321 // If the copy has a glue operand, we conservatively assume it isn't safe to
3322 // perform a tail call.
3323 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3324 return false;
3325 TCChain = Copy->getOperand(0);
3326 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3327 SDNode *VMov = Copy;
3328 // f64 returned in a pair of GPRs.
3329 SmallPtrSet<SDNode*, 2> Copies;
3330 for (SDNode *U : VMov->uses()) {
3331 if (U->getOpcode() != ISD::CopyToReg)
3332 return false;
3333 Copies.insert(U);
3334 }
3335 if (Copies.size() > 2)
3336 return false;
3337
3338 for (SDNode *U : VMov->uses()) {
3339 SDValue UseChain = U->getOperand(0);
3340 if (Copies.count(UseChain.getNode()))
3341 // Second CopyToReg
3342 Copy = U;
3343 else {
3344 // We are at the top of this chain.
3345 // If the copy has a glue operand, we conservatively assume it
3346 // isn't safe to perform a tail call.
3347 if (U->getOperand(U->getNumOperands() - 1).getValueType() == MVT::Glue)
3348 return false;
3349 // First CopyToReg
3350 TCChain = UseChain;
3351 }
3352 }
3353 } else if (Copy->getOpcode() == ISD::BITCAST) {
3354 // f32 returned in a single GPR.
3355 if (!Copy->hasOneUse())
3356 return false;
3357 Copy = *Copy->use_begin();
3358 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3359 return false;
3360 // If the copy has a glue operand, we conservatively assume it isn't safe to
3361 // perform a tail call.
3362 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3363 return false;
3364 TCChain = Copy->getOperand(0);
3365 } else {
3366 return false;
3367 }
3368
3369 bool HasRet = false;
3370 for (const SDNode *U : Copy->uses()) {
3371 if (U->getOpcode() != ARMISD::RET_FLAG &&
3372 U->getOpcode() != ARMISD::INTRET_FLAG)
3373 return false;
3374 HasRet = true;
3375 }
3376
3377 if (!HasRet)
3378 return false;
3379
3380 Chain = TCChain;
3381 return true;
3382}
3383
3384bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3385 if (!Subtarget->supportsTailCall())
3386 return false;
3387
3388 if (!CI->isTailCall())
3389 return false;
3390
3391 return true;
3392}
3393
3394// Trying to write a 64 bit value so need to split into two 32 bit values first,
3395// and pass the lower and high parts through.
3396static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3397 SDLoc DL(Op);
3398 SDValue WriteValue = Op->getOperand(2);
3399
3400 // This function is only supposed to be called for i64 type argument.
3401 assert(WriteValue.getValueType() == MVT::i64(static_cast <bool> (WriteValue.getValueType() == MVT::
i64 && "LowerWRITE_REGISTER called for non-i64 type argument."
) ? void (0) : __assert_fail ("WriteValue.getValueType() == MVT::i64 && \"LowerWRITE_REGISTER called for non-i64 type argument.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3402, __extension__
__PRETTY_FUNCTION__))
3402 && "LowerWRITE_REGISTER called for non-i64 type argument.")(static_cast <bool> (WriteValue.getValueType() == MVT::
i64 && "LowerWRITE_REGISTER called for non-i64 type argument."
) ? void (0) : __assert_fail ("WriteValue.getValueType() == MVT::i64 && \"LowerWRITE_REGISTER called for non-i64 type argument.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3402, __extension__
__PRETTY_FUNCTION__))
;
3403
3404 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3405 DAG.getConstant(0, DL, MVT::i32));
3406 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3407 DAG.getConstant(1, DL, MVT::i32));
3408 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3409 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3410}
3411
3412// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3413// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3414// one of the above mentioned nodes. It has to be wrapped because otherwise
3415// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3416// be used to form addressing mode. These wrapped nodes will be selected
3417// into MOVi.
3418SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3419 SelectionDAG &DAG) const {
3420 EVT PtrVT = Op.getValueType();
3421 // FIXME there is no actual debug info here
3422 SDLoc dl(Op);
3423 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3424 SDValue Res;
3425
3426 // When generating execute-only code Constant Pools must be promoted to the
3427 // global data section. It's a bit ugly that we can't share them across basic
3428 // blocks, but this way we guarantee that execute-only behaves correct with
3429 // position-independent addressing modes.
3430 if (Subtarget->genExecuteOnly()) {
3431 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3432 auto T = const_cast<Type*>(CP->getType());
3433 auto C = const_cast<Constant*>(CP->getConstVal());
3434 auto M = const_cast<Module*>(DAG.getMachineFunction().
3435 getFunction().getParent());
3436 auto GV = new GlobalVariable(
3437 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3438 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3439 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3440 Twine(AFI->createPICLabelUId())
3441 );
3442 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3443 dl, PtrVT);
3444 return LowerGlobalAddress(GA, DAG);
3445 }
3446
3447 // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3448 // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3449 Align CPAlign = CP->getAlign();
3450 if (Subtarget->isThumb1Only())
3451 CPAlign = std::max(CPAlign, Align(4));
3452 if (CP->isMachineConstantPoolEntry())
3453 Res =
3454 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CPAlign);
3455 else
3456 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CPAlign);
3457 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3458}
3459
3460unsigned ARMTargetLowering::getJumpTableEncoding() const {
3461 return MachineJumpTableInfo::EK_Inline;
3462}
3463
3464SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3465 SelectionDAG &DAG) const {
3466 MachineFunction &MF = DAG.getMachineFunction();
3467 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3468 unsigned ARMPCLabelIndex = 0;
3469 SDLoc DL(Op);
3470 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3471 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3472 SDValue CPAddr;
3473 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3474 if (!IsPositionIndependent) {
3475 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3476 } else {
3477 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3478 ARMPCLabelIndex = AFI->createPICLabelUId();
3479 ARMConstantPoolValue *CPV =
3480 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3481 ARMCP::CPBlockAddress, PCAdj);
3482 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3483 }
3484 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3485 SDValue Result = DAG.getLoad(
3486 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3487 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3488 if (!IsPositionIndependent)
3489 return Result;
3490 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3491 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3492}
3493
3494/// Convert a TLS address reference into the correct sequence of loads
3495/// and calls to compute the variable's address for Darwin, and return an
3496/// SDValue containing the final node.
3497
3498/// Darwin only has one TLS scheme which must be capable of dealing with the
3499/// fully general situation, in the worst case. This means:
3500/// + "extern __thread" declaration.
3501/// + Defined in a possibly unknown dynamic library.
3502///
3503/// The general system is that each __thread variable has a [3 x i32] descriptor
3504/// which contains information used by the runtime to calculate the address. The
3505/// only part of this the compiler needs to know about is the first word, which
3506/// contains a function pointer that must be called with the address of the
3507/// entire descriptor in "r0".
3508///
3509/// Since this descriptor may be in a different unit, in general access must
3510/// proceed along the usual ARM rules. A common sequence to produce is:
3511///
3512/// movw rT1, :lower16:_var$non_lazy_ptr
3513/// movt rT1, :upper16:_var$non_lazy_ptr
3514/// ldr r0, [rT1]
3515/// ldr rT2, [r0]
3516/// blx rT2
3517/// [...address now in r0...]
3518SDValue
3519ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3520 SelectionDAG &DAG) const {
3521 assert(Subtarget->isTargetDarwin() &&(static_cast <bool> (Subtarget->isTargetDarwin() &&
"This function expects a Darwin target") ? void (0) : __assert_fail
("Subtarget->isTargetDarwin() && \"This function expects a Darwin target\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3522, __extension__
__PRETTY_FUNCTION__))
3522 "This function expects a Darwin target")(static_cast <bool> (Subtarget->isTargetDarwin() &&
"This function expects a Darwin target") ? void (0) : __assert_fail
("Subtarget->isTargetDarwin() && \"This function expects a Darwin target\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3522, __extension__
__PRETTY_FUNCTION__))
;
3523 SDLoc DL(Op);
3524
3525 // First step is to get the address of the actua global symbol. This is where
3526 // the TLS descriptor lives.
3527 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3528
3529 // The first entry in the descriptor is a function pointer that we must call
3530 // to obtain the address of the variable.
3531 SDValue Chain = DAG.getEntryNode();
3532 SDValue FuncTLVGet = DAG.getLoad(
3533 MVT::i32, DL, Chain, DescAddr,
3534 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3535 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3536 MachineMemOperand::MOInvariant);
3537 Chain = FuncTLVGet.getValue(1);
3538
3539 MachineFunction &F = DAG.getMachineFunction();
3540 MachineFrameInfo &MFI = F.getFrameInfo();
3541 MFI.setAdjustsStack(true);
3542
3543 // TLS calls preserve all registers except those that absolutely must be
3544 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3545 // silly).
3546 auto TRI =
3547 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3548 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3549 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3550
3551 // Finally, we can make the call. This is just a degenerate version of a
3552 // normal AArch64 call node: r0 takes the address of the descriptor, and
3553 // returns the address of the variable in this thread.
3554 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3555 Chain =
3556 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3557 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3558 DAG.getRegisterMask(Mask), Chain.getValue(1));
3559 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3560}
3561
3562SDValue
3563ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3564 SelectionDAG &DAG) const {
3565 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering")(static_cast <bool> (Subtarget->isTargetWindows() &&
"Windows specific TLS lowering") ? void (0) : __assert_fail (
"Subtarget->isTargetWindows() && \"Windows specific TLS lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3565, __extension__
__PRETTY_FUNCTION__))
;
3566
3567 SDValue Chain = DAG.getEntryNode();
3568 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3569 SDLoc DL(Op);
3570
3571 // Load the current TEB (thread environment block)
3572 SDValue Ops[] = {Chain,
3573 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3574 DAG.getTargetConstant(15, DL, MVT::i32),
3575 DAG.getTargetConstant(0, DL, MVT::i32),
3576 DAG.getTargetConstant(13, DL, MVT::i32),
3577 DAG.getTargetConstant(0, DL, MVT::i32),
3578 DAG.getTargetConstant(2, DL, MVT::i32)};
3579 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3580 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3581
3582 SDValue TEB = CurrentTEB.getValue(0);
3583 Chain = CurrentTEB.getValue(1);
3584
3585 // Load the ThreadLocalStoragePointer from the TEB
3586 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3587 SDValue TLSArray =
3588 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3589 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3590
3591 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3592 // offset into the TLSArray.
3593
3594 // Load the TLS index from the C runtime
3595 SDValue TLSIndex =
3596 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3597 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3598 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3599
3600 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3601 DAG.getConstant(2, DL, MVT::i32));
3602 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3603 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3604 MachinePointerInfo());
3605
3606 // Get the offset of the start of the .tls section (section base)
3607 const auto *GA = cast<GlobalAddressSDNode>(Op);
3608 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3609 SDValue Offset = DAG.getLoad(
3610 PtrVT, DL, Chain,
3611 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3612 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3613 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3614
3615 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3616}
3617
3618// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3619SDValue
3620ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3621 SelectionDAG &DAG) const {
3622 SDLoc dl(GA);
3623 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3624 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3625 MachineFunction &MF = DAG.getMachineFunction();
3626 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3627 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3628 ARMConstantPoolValue *CPV =
3629 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3630 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3631 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3632 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3633 Argument = DAG.getLoad(
3634 PtrVT, dl, DAG.getEntryNode(), Argument,
3635 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3636 SDValue Chain = Argument.getValue(1);
3637
3638 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3639 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3640
3641 // call __tls_get_addr.
3642 ArgListTy Args;
3643 ArgListEntry Entry;
3644 Entry.Node = Argument;
3645 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3646 Args.push_back(Entry);
3647
3648 // FIXME: is there useful debug info available here?
3649 TargetLowering::CallLoweringInfo CLI(DAG);
3650 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3651 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3652 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3653
3654 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3655 return CallResult.first;
3656}
3657
3658// Lower ISD::GlobalTLSAddress using the "initial exec" or
3659// "local exec" model.
3660SDValue
3661ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3662 SelectionDAG &DAG,
3663 TLSModel::Model model) const {
3664 const GlobalValue *GV = GA->getGlobal();
3665 SDLoc dl(GA);
3666 SDValue Offset;
3667 SDValue Chain = DAG.getEntryNode();
3668 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3669 // Get the Thread Pointer
3670 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3671
3672 if (model == TLSModel::InitialExec) {
3673 MachineFunction &MF = DAG.getMachineFunction();
3674 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3675 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3676 // Initial exec model.
3677 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3678 ARMConstantPoolValue *CPV =
3679 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3680 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3681 true);
3682 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3683 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3684 Offset = DAG.getLoad(
3685 PtrVT, dl, Chain, Offset,
3686 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3687 Chain = Offset.getValue(1);
3688
3689 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3690 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3691
3692 Offset = DAG.getLoad(
3693 PtrVT, dl, Chain, Offset,
3694 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3695 } else {
3696 // local exec model
3697 assert(model == TLSModel::LocalExec)(static_cast <bool> (model == TLSModel::LocalExec) ? void
(0) : __assert_fail ("model == TLSModel::LocalExec", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3697, __extension__ __PRETTY_FUNCTION__))
;
3698 ARMConstantPoolValue *CPV =
3699 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3700 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3701 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3702 Offset = DAG.getLoad(
3703 PtrVT, dl, Chain, Offset,
3704 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3705 }
3706
3707 // The address of the thread local variable is the add of the thread
3708 // pointer with the offset of the variable.
3709 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3710}
3711
3712SDValue
3713ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3714 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3715 if (DAG.getTarget().useEmulatedTLS())
3716 return LowerToTLSEmulatedModel(GA, DAG);
3717
3718 if (Subtarget->isTargetDarwin())
3719 return LowerGlobalTLSAddressDarwin(Op, DAG);
3720
3721 if (Subtarget->isTargetWindows())
3722 return LowerGlobalTLSAddressWindows(Op, DAG);
3723
3724 // TODO: implement the "local dynamic" model
3725 assert(Subtarget->isTargetELF() && "Only ELF implemented here")(static_cast <bool> (Subtarget->isTargetELF() &&
"Only ELF implemented here") ? void (0) : __assert_fail ("Subtarget->isTargetELF() && \"Only ELF implemented here\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3725, __extension__
__PRETTY_FUNCTION__))
;
3726 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3727
3728 switch (model) {
3729 case TLSModel::GeneralDynamic:
3730 case TLSModel::LocalDynamic:
3731 return LowerToTLSGeneralDynamicModel(GA, DAG);
3732 case TLSModel::InitialExec:
3733 case TLSModel::LocalExec:
3734 return LowerToTLSExecModels(GA, DAG, model);
3735 }
3736 llvm_unreachable("bogus TLS model")::llvm::llvm_unreachable_internal("bogus TLS model", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3736)
;
3737}
3738
3739/// Return true if all users of V are within function F, looking through
3740/// ConstantExprs.
3741static bool allUsersAreInFunction(const Value *V, const Function *F) {
3742 SmallVector<const User*,4> Worklist(V->users());
3743 while (!Worklist.empty()) {
3744 auto *U = Worklist.pop_back_val();
3745 if (isa<ConstantExpr>(U)) {
3746 append_range(Worklist, U->users());
3747 continue;
3748 }
3749
3750 auto *I = dyn_cast<Instruction>(U);
3751 if (!I || I->getParent()->getParent() != F)
3752 return false;
3753 }
3754 return true;
3755}
3756
3757static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3758 const GlobalValue *GV, SelectionDAG &DAG,
3759 EVT PtrVT, const SDLoc &dl) {
3760 // If we're creating a pool entry for a constant global with unnamed address,
3761 // and the global is small enough, we can emit it inline into the constant pool
3762 // to save ourselves an indirection.
3763 //
3764 // This is a win if the constant is only used in one function (so it doesn't
3765 // need to be duplicated) or duplicating the constant wouldn't increase code
3766 // size (implying the constant is no larger than 4 bytes).
3767 const Function &F = DAG.getMachineFunction().getFunction();
3768
3769 // We rely on this decision to inline being idemopotent and unrelated to the
3770 // use-site. We know that if we inline a variable at one use site, we'll
3771 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3772 // doesn't know about this optimization, so bail out if it's enabled else
3773 // we could decide to inline here (and thus never emit the GV) but require
3774 // the GV from fast-isel generated code.
3775 if (!EnableConstpoolPromotion ||
3776 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3777 return SDValue();
3778
3779 auto *GVar = dyn_cast<GlobalVariable>(GV);
3780 if (!GVar || !GVar->hasInitializer() ||
3781 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3782 !GVar->hasLocalLinkage())
3783 return SDValue();
3784
3785 // If we inline a value that contains relocations, we move the relocations
3786 // from .data to .text. This is not allowed in position-independent code.
3787 auto *Init = GVar->getInitializer();
3788 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3789 Init->needsDynamicRelocation())
3790 return SDValue();
3791
3792 // The constant islands pass can only really deal with alignment requests
3793 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3794 // any type wanting greater alignment requirements than 4 bytes. We also
3795 // can only promote constants that are multiples of 4 bytes in size or
3796 // are paddable to a multiple of 4. Currently we only try and pad constants
3797 // that are strings for simplicity.
3798 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3799 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3800 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3801 unsigned RequiredPadding = 4 - (Size % 4);
3802 bool PaddingPossible =
3803 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3804 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3805 Size == 0)
3806 return SDValue();
3807
3808 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3809 MachineFunction &MF = DAG.getMachineFunction();
3810 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3811
3812 // We can't bloat the constant pool too much, else the ConstantIslands pass
3813 // may fail to converge. If we haven't promoted this global yet (it may have
3814 // multiple uses), and promoting it would increase the constant pool size (Sz
3815 // > 4), ensure we have space to do so up to MaxTotal.
3816 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3817 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3818 ConstpoolPromotionMaxTotal)
3819 return SDValue();
3820
3821 // This is only valid if all users are in a single function; we can't clone
3822 // the constant in general. The LLVM IR unnamed_addr allows merging
3823 // constants, but not cloning them.
3824 //
3825 // We could potentially allow cloning if we could prove all uses of the
3826 // constant in the current function don't care about the address, like
3827 // printf format strings. But that isn't implemented for now.
3828 if (!allUsersAreInFunction(GVar, &F))
3829 return SDValue();
3830
3831 // We're going to inline this global. Pad it out if needed.
3832 if (RequiredPadding != 4) {
3833 StringRef S = CDAInit->getAsString();
3834
3835 SmallVector<uint8_t,16> V(S.size());
3836 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3837 while (RequiredPadding--)
3838 V.push_back(0);
3839 Init = ConstantDataArray::get(*DAG.getContext(), V);
3840 }
3841
3842 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3843 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3844 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3845 AFI->markGlobalAsPromotedToConstantPool(GVar);
3846 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3847 PaddedSize - 4);
3848 }
3849 ++NumConstpoolPromoted;
3850 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3851}
3852
3853bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3854 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3855 if (!(GV = GA->getAliaseeObject()))
3856 return false;
3857 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3858 return V->isConstant();
3859 return isa<Function>(GV);
3860}
3861
3862SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3863 SelectionDAG &DAG) const {
3864 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3865 default: llvm_unreachable("unknown object format")::llvm::llvm_unreachable_internal("unknown object format", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3865)
;
3866 case Triple::COFF:
3867 return LowerGlobalAddressWindows(Op, DAG);
3868 case Triple::ELF:
3869 return LowerGlobalAddressELF(Op, DAG);
3870 case Triple::MachO:
3871 return LowerGlobalAddressDarwin(Op, DAG);
3872 }
3873}
3874
3875SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3876 SelectionDAG &DAG) const {
3877 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3878 SDLoc dl(Op);
3879 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3880 const TargetMachine &TM = getTargetMachine();
3881 bool IsRO = isReadOnly(GV);
3882
3883 // promoteToConstantPool only if not generating XO text section
3884 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3885 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3886 return V;
3887
3888 if (isPositionIndependent()) {
3889 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3890 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3891 UseGOT_PREL ? ARMII::MO_GOT : 0);
3892 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3893 if (UseGOT_PREL)
3894 Result =
3895 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3896 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3897 return Result;
3898 } else if (Subtarget->isROPI() && IsRO) {
3899 // PC-relative.
3900 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3901 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3902 return Result;
3903 } else if (Subtarget->isRWPI() && !IsRO) {
3904 // SB-relative.
3905 SDValue RelAddr;
3906 if (Subtarget->useMovt()) {
3907 ++NumMovwMovt;
3908 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3909 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3910 } else { // use literal pool for address constant
3911 ARMConstantPoolValue *CPV =
3912 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3913 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3914 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3915 RelAddr = DAG.getLoad(
3916 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3917 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3918 }
3919 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3920 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3921 return Result;
3922 }
3923
3924 // If we have T2 ops, we can materialize the address directly via movt/movw
3925 // pair. This is always cheaper.
3926 if (Subtarget->useMovt()) {
3927 ++NumMovwMovt;
3928 // FIXME: Once remat is capable of dealing with instructions with register
3929 // operands, expand this into two nodes.
3930 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3931 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3932 } else {
3933 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3934 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3935 return DAG.getLoad(
3936 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3937 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3938 }
3939}
3940
3941SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3942 SelectionDAG &DAG) const {
3943 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Darwin"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Darwin\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3944, __extension__
__PRETTY_FUNCTION__))
3944 "ROPI/RWPI not currently supported for Darwin")(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Darwin"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Darwin\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3944, __extension__
__PRETTY_FUNCTION__))
;
3945 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3946 SDLoc dl(Op);
3947 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3948
3949 if (Subtarget->useMovt())
3950 ++NumMovwMovt;
3951
3952 // FIXME: Once remat is capable of dealing with instructions with register
3953 // operands, expand this into multiple nodes
3954 unsigned Wrapper =
3955 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3956
3957 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3958 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3959
3960 if (Subtarget->isGVIndirectSymbol(GV))
3961 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3962 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3963 return Result;
3964}
3965
3966SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3967 SelectionDAG &DAG) const {
3968 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported")(static_cast <bool> (Subtarget->isTargetWindows() &&
"non-Windows COFF is not supported") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"non-Windows COFF is not supported\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3968, __extension__
__PRETTY_FUNCTION__))
;
3969 assert(Subtarget->useMovt() &&(static_cast <bool> (Subtarget->useMovt() &&
"Windows on ARM expects to use movw/movt") ? void (0) : __assert_fail
("Subtarget->useMovt() && \"Windows on ARM expects to use movw/movt\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3970, __extension__
__PRETTY_FUNCTION__))
3970 "Windows on ARM expects to use movw/movt")(static_cast <bool> (Subtarget->useMovt() &&
"Windows on ARM expects to use movw/movt") ? void (0) : __assert_fail
("Subtarget->useMovt() && \"Windows on ARM expects to use movw/movt\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3970, __extension__
__PRETTY_FUNCTION__))
;
3971 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Windows"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Windows\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3972, __extension__
__PRETTY_FUNCTION__))
3972 "ROPI/RWPI not currently supported for Windows")(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Windows"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Windows\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 3972, __extension__
__PRETTY_FUNCTION__))
;
3973
3974 const TargetMachine &TM = getTargetMachine();
3975 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3976 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3977 if (GV->hasDLLImportStorageClass())
3978 TargetFlags = ARMII::MO_DLLIMPORT;
3979 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3980 TargetFlags = ARMII::MO_COFFSTUB;
3981 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3982 SDValue Result;
3983 SDLoc DL(Op);
3984
3985 ++NumMovwMovt;
3986
3987 // FIXME: Once remat is capable of dealing with instructions with register
3988 // operands, expand this into two nodes.
3989 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3990 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3991 TargetFlags));
3992 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3993 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3994 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3995 return Result;
3996}
3997
3998SDValue
3999ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
4000 SDLoc dl(Op);
4001 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
4002 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
4003 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
4004 Op.getOperand(1), Val);
4005}
4006
4007SDValue
4008ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
4009 SDLoc dl(Op);
4010 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
4011 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
4012}
4013
4014SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
4015 SelectionDAG &DAG) const {
4016 SDLoc dl(Op);
4017 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
4018 Op.getOperand(0));
4019}
4020
4021SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
4022 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
4023 unsigned IntNo =
4024 cast<ConstantSDNode>(
4025 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
4026 ->getZExtValue();
4027 switch (IntNo) {
4028 default:
4029 return SDValue(); // Don't custom lower most intrinsics.
4030 case Intrinsic::arm_gnu_eabi_mcount: {
4031 MachineFunction &MF = DAG.getMachineFunction();
4032 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4033 SDLoc dl(Op);
4034 SDValue Chain = Op.getOperand(0);
4035 // call "\01__gnu_mcount_nc"
4036 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
4037 const uint32_t *Mask =
4038 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4039 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4039, __extension__
__PRETTY_FUNCTION__))
;
4040 // Mark LR an implicit live-in.
4041 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4042 SDValue ReturnAddress =
4043 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
4044 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
4045 SDValue Callee =
4046 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
4047 SDValue RegisterMask = DAG.getRegisterMask(Mask);
4048 if (Subtarget->isThumb())
4049 return SDValue(
4050 DAG.getMachineNode(
4051 ARM::tBL_PUSHLR, dl, ResultTys,
4052 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
4053 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
4054 0);
4055 return SDValue(
4056 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
4057 {ReturnAddress, Callee, RegisterMask, Chain}),
4058 0);
4059 }
4060 }
4061}
4062
4063SDValue
4064ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
4065 const ARMSubtarget *Subtarget) const {
4066 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4067 SDLoc dl(Op);
4068 switch (IntNo) {
4069 default: return SDValue(); // Don't custom lower most intrinsics.
4070 case Intrinsic::thread_pointer: {
4071 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4072 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
4073 }
4074 case Intrinsic::arm_cls: {
4075 const SDValue &Operand = Op.getOperand(1);
4076 const EVT VTy = Op.getValueType();
4077 SDValue SRA =
4078 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
4079 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
4080 SDValue SHL =
4081 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
4082 SDValue OR =
4083 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
4084 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
4085 return Result;
4086 }
4087 case Intrinsic::arm_cls64: {
4088 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
4089 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
4090 const SDValue &Operand = Op.getOperand(1);
4091 const EVT VTy = Op.getValueType();
4092
4093 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
4094 DAG.getConstant(1, dl, VTy));
4095 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
4096 DAG.getConstant(0, dl, VTy));
4097 SDValue Constant0 = DAG.getConstant(0, dl, VTy);
4098 SDValue Constant1 = DAG.getConstant(1, dl, VTy);
4099 SDValue Constant31 = DAG.getConstant(31, dl, VTy);
4100 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
4101 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
4102 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
4103 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
4104 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
4105 SDValue CheckLo =
4106 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
4107 SDValue HiIsZero =
4108 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
4109 SDValue AdjustedLo =
4110 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
4111 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
4112 SDValue Result =
4113 DAG.getSelect(dl, VTy, CheckLo,
4114 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
4115 return Result;
4116 }
4117 case Intrinsic::eh_sjlj_lsda: {
4118 MachineFunction &MF = DAG.getMachineFunction();
4119 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4120 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
4121 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4122 SDValue CPAddr;
4123 bool IsPositionIndependent = isPositionIndependent();
4124 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
4125 ARMConstantPoolValue *CPV =
4126 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
4127 ARMCP::CPLSDA, PCAdj);
4128 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
4129 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
4130 SDValue Result = DAG.getLoad(
4131 PtrVT, dl, DAG.getEntryNode(), CPAddr,
4132 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
4133
4134 if (IsPositionIndependent) {
4135 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
4136 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
4137 }
4138 return Result;
4139 }
4140 case Intrinsic::arm_neon_vabs:
4141 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
4142 Op.getOperand(1));
4143 case Intrinsic::arm_neon_vmulls:
4144 case Intrinsic::arm_neon_vmullu: {
4145 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
4146 ? ARMISD::VMULLs : ARMISD::VMULLu;
4147 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4148 Op.getOperand(1), Op.getOperand(2));
4149 }
4150 case Intrinsic::arm_neon_vminnm:
4151 case Intrinsic::arm_neon_vmaxnm: {
4152 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
4153 ? ISD::FMINNUM : ISD::FMAXNUM;
4154 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4155 Op.getOperand(1), Op.getOperand(2));
4156 }
4157 case Intrinsic::arm_neon_vminu:
4158 case Intrinsic::arm_neon_vmaxu: {
4159 if (Op.getValueType().isFloatingPoint())
4160 return SDValue();
4161 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
4162 ? ISD::UMIN : ISD::UMAX;
4163 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4164 Op.getOperand(1), Op.getOperand(2));
4165 }
4166 case Intrinsic::arm_neon_vmins:
4167 case Intrinsic::arm_neon_vmaxs: {
4168 // v{min,max}s is overloaded between signed integers and floats.
4169 if (!Op.getValueType().isFloatingPoint()) {
4170 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4171 ? ISD::SMIN : ISD::SMAX;
4172 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4173 Op.getOperand(1), Op.getOperand(2));
4174 }
4175 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4176 ? ISD::FMINIMUM : ISD::FMAXIMUM;
4177 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4178 Op.getOperand(1), Op.getOperand(2));
4179 }
4180 case Intrinsic::arm_neon_vtbl1:
4181 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
4182 Op.getOperand(1), Op.getOperand(2));
4183 case Intrinsic::arm_neon_vtbl2:
4184 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4185 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4186 case Intrinsic::arm_mve_pred_i2v:
4187 case Intrinsic::arm_mve_pred_v2i:
4188 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4189 Op.getOperand(1));
4190 case Intrinsic::arm_mve_vreinterpretq:
4191 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4192 Op.getOperand(1));
4193 case Intrinsic::arm_mve_lsll:
4194 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4195 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4196 case Intrinsic::arm_mve_asrl:
4197 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4198 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4199 }
4200}
4201
4202static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4203 const ARMSubtarget *Subtarget) {
4204 SDLoc dl(Op);
4205 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
4206 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
4207 if (SSID == SyncScope::SingleThread)
4208 return Op;
4209
4210 if (!Subtarget->hasDataBarrier()) {
4211 // Some ARMv6 cpus can support data barriers with an mcr instruction.
4212 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4213 // here.
4214 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&(static_cast <bool> (Subtarget->hasV6Ops() &&
!Subtarget->isThumb() && "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"
) ? void (0) : __assert_fail ("Subtarget->hasV6Ops() && !Subtarget->isThumb() && \"Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4215, __extension__
__PRETTY_FUNCTION__))
4215 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!")(static_cast <bool> (Subtarget->hasV6Ops() &&
!Subtarget->isThumb() && "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"
) ? void (0) : __assert_fail ("Subtarget->hasV6Ops() && !Subtarget->isThumb() && \"Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4215, __extension__
__PRETTY_FUNCTION__))
;
4216 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4217 DAG.getConstant(0, dl, MVT::i32));
4218 }
4219
4220 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
4221 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
4222 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4223 if (Subtarget->isMClass()) {
4224 // Only a full system barrier exists in the M-class architectures.
4225 Domain = ARM_MB::SY;
4226 } else if (Subtarget->preferISHSTBarriers() &&
4227 Ord == AtomicOrdering::Release) {
4228 // Swift happens to implement ISHST barriers in a way that's compatible with
4229 // Release semantics but weaker than ISH so we'd be fools not to use
4230 // it. Beware: other processors probably don't!
4231 Domain = ARM_MB::ISHST;
4232 }
4233
4234 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4235 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4236 DAG.getConstant(Domain, dl, MVT::i32));
4237}
4238
4239static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4240 const ARMSubtarget *Subtarget) {
4241 // ARM pre v5TE and Thumb1 does not have preload instructions.
4242 if (!(Subtarget->isThumb2() ||
4243 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4244 // Just preserve the chain.
4245 return Op.getOperand(0);
4246
4247 SDLoc dl(Op);
4248 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
4249 if (!isRead &&
4250 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4251 // ARMv7 with MP extension has PLDW.
4252 return Op.getOperand(0);
4253
4254 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4255 if (Subtarget->isThumb()) {
4256 // Invert the bits.
4257 isRead = ~isRead & 1;
4258 isData = ~isData & 1;
4259 }
4260
4261 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4262 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4263 DAG.getConstant(isData, dl, MVT::i32));
4264}
4265
4266static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4267 MachineFunction &MF = DAG.getMachineFunction();
4268 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4269
4270 // vastart just stores the address of the VarArgsFrameIndex slot into the
4271 // memory location argument.
4272 SDLoc dl(Op);
4273 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4274 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4275 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4276 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4277 MachinePointerInfo(SV));
4278}
4279
4280SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4281 CCValAssign &NextVA,
4282 SDValue &Root,
4283 SelectionDAG &DAG,
4284 const SDLoc &dl) const {
4285 MachineFunction &MF = DAG.getMachineFunction();
4286 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4287
4288 const TargetRegisterClass *RC;
4289 if (AFI->isThumb1OnlyFunction())
4290 RC = &ARM::tGPRRegClass;
4291 else
4292 RC = &ARM::GPRRegClass;
4293
4294 // Transform the arguments stored in physical registers into virtual ones.
4295 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4296 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4297
4298 SDValue ArgValue2;
4299 if (NextVA.isMemLoc()) {
4300 MachineFrameInfo &MFI = MF.getFrameInfo();
4301 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4302
4303 // Create load node to retrieve arguments from the stack.
4304 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4305 ArgValue2 = DAG.getLoad(
4306 MVT::i32, dl, Root, FIN,
4307 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4308 } else {
4309 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4310 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4311 }
4312 if (!Subtarget->isLittle())
4313 std::swap (ArgValue, ArgValue2);
4314 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4315}
4316
4317// The remaining GPRs hold either the beginning of variable-argument
4318// data, or the beginning of an aggregate passed by value (usually
4319// byval). Either way, we allocate stack slots adjacent to the data
4320// provided by our caller, and store the unallocated registers there.
4321// If this is a variadic function, the va_list pointer will begin with
4322// these values; otherwise, this reassembles a (byval) structure that
4323// was split between registers and memory.
4324// Return: The frame index registers were stored into.
4325int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4326 const SDLoc &dl, SDValue &Chain,
4327 const Value *OrigArg,
4328 unsigned InRegsParamRecordIdx,
4329 int ArgOffset, unsigned ArgSize) const {
4330 // Currently, two use-cases possible:
4331 // Case #1. Non-var-args function, and we meet first byval parameter.
4332 // Setup first unallocated register as first byval register;
4333 // eat all remained registers
4334 // (these two actions are performed by HandleByVal method).
4335 // Then, here, we initialize stack frame with
4336 // "store-reg" instructions.
4337 // Case #2. Var-args function, that doesn't contain byval parameters.
4338 // The same: eat all remained unallocated registers,
4339 // initialize stack frame.
4340
4341 MachineFunction &MF = DAG.getMachineFunction();
4342 MachineFrameInfo &MFI = MF.getFrameInfo();
4343 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4344 unsigned RBegin, REnd;
4345 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4346 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4347 } else {
4348 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4349 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4350 REnd = ARM::R4;
4351 }
4352
4353 if (REnd != RBegin)
4354 ArgOffset = -4 * (ARM::R4 - RBegin);
4355
4356 auto PtrVT = getPointerTy(DAG.getDataLayout());
4357 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4358 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4359
4360 SmallVector<SDValue, 4> MemOps;
4361 const TargetRegisterClass *RC =
4362 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4363
4364 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4365 Register VReg = MF.addLiveIn(Reg, RC);
4366 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4367 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4368 MachinePointerInfo(OrigArg, 4 * i));
4369 MemOps.push_back(Store);
4370 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4371 }
4372
4373 if (!MemOps.empty())
4374 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4375 return FrameIndex;
4376}
4377
4378// Setup stack frame, the va_list pointer will start from.
4379void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4380 const SDLoc &dl, SDValue &Chain,
4381 unsigned ArgOffset,
4382 unsigned TotalArgRegsSaveSize,
4383 bool ForceMutable) const {
4384 MachineFunction &MF = DAG.getMachineFunction();
4385 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4386
4387 // Try to store any remaining integer argument regs
4388 // to their spots on the stack so that they may be loaded by dereferencing
4389 // the result of va_next.
4390 // If there is no regs to be stored, just point address after last
4391 // argument passed via stack.
4392 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4393 CCInfo.getInRegsParamsCount(),
4394 CCInfo.getNextStackOffset(),
4395 std::max(4U, TotalArgRegsSaveSize));
4396 AFI->setVarArgsFrameIndex(FrameIndex);
4397}
4398
4399bool ARMTargetLowering::splitValueIntoRegisterParts(
4400 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4401 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
4402 bool IsABIRegCopy = CC.has_value();
4403 EVT ValueVT = Val.getValueType();
4404 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4405 PartVT == MVT::f32) {
4406 unsigned ValueBits = ValueVT.getSizeInBits();
4407 unsigned PartBits = PartVT.getSizeInBits();
4408 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4409 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4410 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4411 Parts[0] = Val;
4412 return true;
4413 }
4414 return false;
4415}
4416
4417SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4418 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4419 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
4420 bool IsABIRegCopy = CC.has_value();
4421 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4422 PartVT == MVT::f32) {
4423 unsigned ValueBits = ValueVT.getSizeInBits();
4424 unsigned PartBits = PartVT.getSizeInBits();
4425 SDValue Val = Parts[0];
4426
4427 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4428 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4429 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4430 return Val;
4431 }
4432 return SDValue();
4433}
4434
4435SDValue ARMTargetLowering::LowerFormalArguments(
4436 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4437 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4438 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4439 MachineFunction &MF = DAG.getMachineFunction();
4440 MachineFrameInfo &MFI = MF.getFrameInfo();
4441
4442 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4443
4444 // Assign locations to all of the incoming arguments.
4445 SmallVector<CCValAssign, 16> ArgLocs;
4446 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4447 *DAG.getContext());
4448 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4449
4450 SmallVector<SDValue, 16> ArgValues;
4451 SDValue ArgValue;
4452 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4453 unsigned CurArgIdx = 0;
4454
4455 // Initially ArgRegsSaveSize is zero.
4456 // Then we increase this value each time we meet byval parameter.
4457 // We also increase this value in case of varargs function.
4458 AFI->setArgRegsSaveSize(0);
4459
4460 // Calculate the amount of stack space that we need to allocate to store
4461 // byval and variadic arguments that are passed in registers.
4462 // We need to know this before we allocate the first byval or variadic
4463 // argument, as they will be allocated a stack slot below the CFA (Canonical
4464 // Frame Address, the stack pointer at entry to the function).
4465 unsigned ArgRegBegin = ARM::R4;
4466 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4467 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4468 break;
4469
4470 CCValAssign &VA = ArgLocs[i];
4471 unsigned Index = VA.getValNo();
4472 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4473 if (!Flags.isByVal())
4474 continue;
4475
4476 assert(VA.isMemLoc() && "unexpected byval pointer in reg")(static_cast <bool> (VA.isMemLoc() && "unexpected byval pointer in reg"
) ? void (0) : __assert_fail ("VA.isMemLoc() && \"unexpected byval pointer in reg\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4476, __extension__
__PRETTY_FUNCTION__))
;
4477 unsigned RBegin, REnd;
4478 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4479 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4480
4481 CCInfo.nextInRegsParam();
4482 }
4483 CCInfo.rewindByValRegsInfo();
4484
4485 int lastInsIndex = -1;
4486 if (isVarArg && MFI.hasVAStart()) {
4487 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4488 if (RegIdx != std::size(GPRArgRegs))
4489 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4490 }
4491
4492 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4493 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4494 auto PtrVT = getPointerTy(DAG.getDataLayout());
4495
4496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4497 CCValAssign &VA = ArgLocs[i];
4498 if (Ins[VA.getValNo()].isOrigArg()) {
4499 std::advance(CurOrigArg,
4500 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4501 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4502 }
4503 // Arguments stored in registers.
4504 if (VA.isRegLoc()) {
4505 EVT RegVT = VA.getLocVT();
4506
4507 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4508 // f64 and vector types are split up into multiple registers or
4509 // combinations of registers and stack slots.
4510 SDValue ArgValue1 =
4511 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4512 VA = ArgLocs[++i]; // skip ahead to next loc
4513 SDValue ArgValue2;
4514 if (VA.isMemLoc()) {
4515 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4516 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4517 ArgValue2 = DAG.getLoad(
4518 MVT::f64, dl, Chain, FIN,
4519 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4520 } else {
4521 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4522 }
4523 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4524 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4525 ArgValue1, DAG.getIntPtrConstant(0, dl));
4526 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4527 ArgValue2, DAG.getIntPtrConstant(1, dl));
4528 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4529 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4530 } else {
4531 const TargetRegisterClass *RC;
4532
4533 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4534 RC = &ARM::HPRRegClass;
4535 else if (RegVT == MVT::f32)
4536 RC = &ARM::SPRRegClass;
4537 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4538 RegVT == MVT::v4bf16)
4539 RC = &ARM::DPRRegClass;
4540 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4541 RegVT == MVT::v8bf16)
4542 RC = &ARM::QPRRegClass;
4543 else if (RegVT == MVT::i32)
4544 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4545 : &ARM::GPRRegClass;
4546 else
4547 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering")::llvm::llvm_unreachable_internal("RegVT not supported by FORMAL_ARGUMENTS Lowering"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4547)
;
4548
4549 // Transform the arguments in physical registers into virtual ones.
4550 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4551 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4552
4553 // If this value is passed in r0 and has the returned attribute (e.g.
4554 // C++ 'structors), record this fact for later use.
4555 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4556 AFI->setPreservesR0();
4557 }
4558 }
4559
4560 // If this is an 8 or 16-bit value, it is really passed promoted
4561 // to 32 bits. Insert an assert[sz]ext to capture this, then
4562 // truncate to the right size.
4563 switch (VA.getLocInfo()) {
4564 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4564)
;
4565 case CCValAssign::Full: break;
4566 case CCValAssign::BCvt:
4567 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4568 break;
4569 case CCValAssign::SExt:
4570 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4571 DAG.getValueType(VA.getValVT()));
4572 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4573 break;
4574 case CCValAssign::ZExt:
4575 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4576 DAG.getValueType(VA.getValVT()));
4577 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4578 break;
4579 }
4580
4581 // f16 arguments have their size extended to 4 bytes and passed as if they
4582 // had been copied to the LSBs of a 32-bit register.
4583 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4584 if (VA.needsCustom() &&
4585 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4586 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4587
4588 InVals.push_back(ArgValue);
4589 } else { // VA.isRegLoc()
4590 // Only arguments passed on the stack should make it here.
4591 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "llvm/lib/Target/ARM/ARMISelLowering.cpp",
4591, __extension__ __PRETTY_FUNCTION__))
;
4592 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered")(static_cast <bool> (VA.getValVT() != MVT::i64 &&
"i64 should already be lowered") ? void (0) : __assert_fail (
"VA.getValVT() != MVT::i64 && \"i64 should already be lowered\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4592, __extension__
__PRETTY_FUNCTION__))
;
4593
4594 int index = VA.getValNo();
4595
4596 // Some Ins[] entries become multiple ArgLoc[] entries.
4597 // Process them only once.
4598 if (index != lastInsIndex)
4599 {
4600 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4601 // FIXME: For now, all byval parameter objects are marked mutable.
4602 // This can be changed with more analysis.
4603 // In case of tail call optimization mark all arguments mutable.
4604 // Since they could be overwritten by lowering of arguments in case of
4605 // a tail call.
4606 if (Flags.isByVal()) {
4607 assert(Ins[index].isOrigArg() &&(static_cast <bool> (Ins[index].isOrigArg() && "Byval arguments cannot be implicit"
) ? void (0) : __assert_fail ("Ins[index].isOrigArg() && \"Byval arguments cannot be implicit\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4608, __extension__
__PRETTY_FUNCTION__))
4608 "Byval arguments cannot be implicit")(static_cast <bool> (Ins[index].isOrigArg() && "Byval arguments cannot be implicit"
) ? void (0) : __assert_fail ("Ins[index].isOrigArg() && \"Byval arguments cannot be implicit\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4608, __extension__
__PRETTY_FUNCTION__))
;
4609 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4610
4611 int FrameIndex = StoreByValRegs(
4612 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4613 VA.getLocMemOffset(), Flags.getByValSize());
4614 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4615 CCInfo.nextInRegsParam();
4616 } else {
4617 unsigned FIOffset = VA.getLocMemOffset();
4618 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4619 FIOffset, true);
4620
4621 // Create load nodes to retrieve arguments from the stack.
4622 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4623 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4624 MachinePointerInfo::getFixedStack(
4625 DAG.getMachineFunction(), FI)));
4626 }
4627 lastInsIndex = index;
4628 }
4629 }
4630 }
4631
4632 // varargs
4633 if (isVarArg && MFI.hasVAStart()) {
4634 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(),
4635 TotalArgRegsSaveSize);
4636 if (AFI->isCmseNSEntryFunction()) {
4637 DiagnosticInfoUnsupported Diag(
4638 DAG.getMachineFunction().getFunction(),
4639 "secure entry function must not be variadic", dl.getDebugLoc());
4640 DAG.getContext()->diagnose(Diag);
4641 }
4642 }
4643
4644 unsigned StackArgSize = CCInfo.getNextStackOffset();
4645 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4646 if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4647 // The only way to guarantee a tail call is if the callee restores its
4648 // argument area, but it must also keep the stack aligned when doing so.
4649 const DataLayout &DL = DAG.getDataLayout();
4650 StackArgSize = alignTo(StackArgSize, DL.getStackAlignment());
4651
4652 AFI->setArgumentStackToRestore(StackArgSize);
4653 }
4654 AFI->setArgumentStackSize(StackArgSize);
4655
4656 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) {
4657 DiagnosticInfoUnsupported Diag(
4658 DAG.getMachineFunction().getFunction(),
4659 "secure entry function requires arguments on stack", dl.getDebugLoc());
4660 DAG.getContext()->diagnose(Diag);
4661 }
4662
4663 return Chain;
4664}
4665
4666/// isFloatingPointZero - Return true if this is +0.0.
4667static bool isFloatingPointZero(SDValue Op) {
4668 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4669 return CFP->getValueAPF().isPosZero();
4670 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4671 // Maybe this has already been legalized into the constant pool?
4672 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4673 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4674 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4675 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4676 return CFP->getValueAPF().isPosZero();
4677 }
4678 } else if (Op->getOpcode() == ISD::BITCAST &&
4679 Op->getValueType(0) == MVT::f64) {
4680 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4681 // created by LowerConstantFP().
4682 SDValue BitcastOp = Op->getOperand(0);
4683 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4684 isNullConstant(BitcastOp->getOperand(0)))
4685 return true;
4686 }
4687 return false;
4688}
4689
4690/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4691/// the given operands.
4692SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4693 SDValue &ARMcc, SelectionDAG &DAG,
4694 const SDLoc &dl) const {
4695 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4696 unsigned C = RHSC->getZExtValue();
4697 if (!isLegalICmpImmediate((int32_t)C)) {
4698 // Constant does not fit, try adjusting it by one.
4699 switch (CC) {
4700 default: break;
4701 case ISD::SETLT:
4702 case ISD::SETGE:
4703 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4704 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4705 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4706 }
4707 break;
4708 case ISD::SETULT:
4709 case ISD::SETUGE:
4710 if (C != 0 && isLegalICmpImmediate(C-1)) {
4711 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4712 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4713 }
4714 break;
4715 case ISD::SETLE:
4716 case ISD::SETGT:
4717 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4718 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4719 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4720 }
4721 break;
4722 case ISD::SETULE:
4723 case ISD::SETUGT:
4724 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4725 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4726 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4727 }
4728 break;
4729 }
4730 }
4731 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4732 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4733 // In ARM and Thumb-2, the compare instructions can shift their second
4734 // operand.
4735 CC = ISD::getSetCCSwappedOperands(CC);
4736 std::swap(LHS, RHS);
4737 }
4738
4739 // Thumb1 has very limited immediate modes, so turning an "and" into a
4740 // shift can save multiple instructions.
4741 //
4742 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4743 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4744 // own. If it's the operand to an unsigned comparison with an immediate,
4745 // we can eliminate one of the shifts: we transform
4746 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4747 //
4748 // We avoid transforming cases which aren't profitable due to encoding
4749 // details:
4750 //
4751 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4752 // would not; in that case, we're essentially trading one immediate load for
4753 // another.
4754 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4755 // 3. C2 is zero; we have other code for this special case.
4756 //
4757 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4758 // instruction, since the AND is always one instruction anyway, but we could
4759 // use narrow instructions in some cases.
4760 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4761 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4762 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4763 !isSignedIntSetCC(CC)) {
4764 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4765 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4766 uint64_t RHSV = RHSC->getZExtValue();
4767 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4768 unsigned ShiftBits = countLeadingZeros(Mask);
4769 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4770 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4771 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4772 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4773 }
4774 }
4775 }
4776
4777 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4778 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4779 // way a cmp would.
4780 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4781 // some tweaks to the heuristics for the previous and->shift transform.
4782 // FIXME: Optimize cases where the LHS isn't a shift.
4783 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4784 isa<ConstantSDNode>(RHS) &&
4785 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4786 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4787 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4788 unsigned ShiftAmt =
4789 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4790 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4791 DAG.getVTList(MVT::i32, MVT::i32),
4792 LHS.getOperand(0),
4793 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4794 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4795 Shift.getValue(1), SDValue());
4796 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4797 return Chain.getValue(1);
4798 }
4799
4800 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4801
4802 // If the RHS is a constant zero then the V (overflow) flag will never be
4803 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4804 // simpler for other passes (like the peephole optimiser) to deal with.
4805 if (isNullConstant(RHS)) {
4806 switch (CondCode) {
4807 default: break;
4808 case ARMCC::GE:
4809 CondCode = ARMCC::PL;
4810 break;
4811 case ARMCC::LT:
4812 CondCode = ARMCC::MI;
4813 break;
4814 }
4815 }
4816
4817 ARMISD::NodeType CompareType;
4818 switch (CondCode) {
4819 default:
4820 CompareType = ARMISD::CMP;
4821 break;
4822 case ARMCC::EQ:
4823 case ARMCC::NE:
4824 // Uses only Z Flag
4825 CompareType = ARMISD::CMPZ;
4826 break;
4827 }
4828 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4829 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4830}
4831
4832/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4833SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4834 SelectionDAG &DAG, const SDLoc &dl,
4835 bool Signaling) const {
4836 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64)(static_cast <bool> (Subtarget->hasFP64() || RHS.getValueType
() != MVT::f64) ? void (0) : __assert_fail ("Subtarget->hasFP64() || RHS.getValueType() != MVT::f64"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4836, __extension__
__PRETTY_FUNCTION__))
;
4837 SDValue Cmp;
4838 if (!isFloatingPointZero(RHS))
4839 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4840 dl, MVT::Glue, LHS, RHS);
4841 else
4842 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4843 dl, MVT::Glue, LHS);
4844 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4845}
4846
4847/// duplicateCmp - Glue values can have only one use, so this function
4848/// duplicates a comparison node.
4849SDValue
4850ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4851 unsigned Opc = Cmp.getOpcode();
4852 SDLoc DL(Cmp);
4853 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4854 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4855
4856 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation")(static_cast <bool> (Opc == ARMISD::FMSTAT && "unexpected comparison operation"
) ? void (0) : __assert_fail ("Opc == ARMISD::FMSTAT && \"unexpected comparison operation\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4856, __extension__
__PRETTY_FUNCTION__))
;
4857 Cmp = Cmp.getOperand(0);
4858 Opc = Cmp.getOpcode();
4859 if (Opc == ARMISD::CMPFP)
4860 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4861 else {
4862 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT")(static_cast <bool> (Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"
) ? void (0) : __assert_fail ("Opc == ARMISD::CMPFPw0 && \"unexpected operand of FMSTAT\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4862, __extension__
__PRETTY_FUNCTION__))
;
4863 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4864 }
4865 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4866}
4867
4868// This function returns three things: the arithmetic computation itself
4869// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4870// comparison and the condition code define the case in which the arithmetic
4871// computation *does not* overflow.
4872std::pair<SDValue, SDValue>
4873ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4874 SDValue &ARMcc) const {
4875 assert(Op.getValueType() == MVT::i32 && "Unsupported value type")(static_cast <bool> (Op.getValueType() == MVT::i32 &&
"Unsupported value type") ? void (0) : __assert_fail ("Op.getValueType() == MVT::i32 && \"Unsupported value type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4875, __extension__
__PRETTY_FUNCTION__))
;
4876
4877 SDValue Value, OverflowCmp;
4878 SDValue LHS = Op.getOperand(0);
4879 SDValue RHS = Op.getOperand(1);
4880 SDLoc dl(Op);
4881
4882 // FIXME: We are currently always generating CMPs because we don't support
4883 // generating CMN through the backend. This is not as good as the natural
4884 // CMP case because it causes a register dependency and cannot be folded
4885 // later.
4886
4887 switch (Op.getOpcode()) {
4888 default:
4889 llvm_unreachable("Unknown overflow instruction!")::llvm::llvm_unreachable_internal("Unknown overflow instruction!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 4889)
;
4890 case ISD::SADDO:
4891 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4892 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4893 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4894 break;
4895 case ISD::UADDO:
4896 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4897 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4898 // We do not use it in the USUBO case as Value may not be used.
4899 Value = DAG.getNode(ARMISD::ADDC, dl,
4900 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4901 .getValue(0);
4902 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4903 break;
4904 case ISD::SSUBO:
4905 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4906 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4907 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4908 break;
4909 case ISD::USUBO:
4910 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4911 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4912 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4913 break;
4914 case ISD::UMULO:
4915 // We generate a UMUL_LOHI and then check if the high word is 0.
4916 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4917 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4918 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4919 LHS, RHS);
4920 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4921 DAG.getConstant(0, dl, MVT::i32));
4922 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4923 break;
4924 case ISD::SMULO:
4925 // We generate a SMUL_LOHI and then check if all the bits of the high word
4926 // are the same as the sign bit of the low word.
4927 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4928 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4929 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4930 LHS, RHS);
4931 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4932 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4933 Value.getValue(0),
4934 DAG.getConstant(31, dl, MVT::i32)));
4935 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4936 break;
4937 } // switch (...)
4938
4939 return std::make_pair(Value, OverflowCmp);
4940}
4941
4942SDValue
4943ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4944 // Let legalize expand this if it isn't a legal type yet.
4945 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4946 return SDValue();
4947
4948 SDValue Value, OverflowCmp;
4949 SDValue ARMcc;
4950 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4951 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4952 SDLoc dl(Op);
4953 // We use 0 and 1 as false and true values.
4954 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4955 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4956 EVT VT = Op.getValueType();
4957
4958 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4959 ARMcc, CCR, OverflowCmp);
4960
4961 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4962 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4963}
4964
4965static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4966 SelectionDAG &DAG) {
4967 SDLoc DL(BoolCarry);
4968 EVT CarryVT = BoolCarry.getValueType();
4969
4970 // This converts the boolean value carry into the carry flag by doing
4971 // ARMISD::SUBC Carry, 1
4972 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4973 DAG.getVTList(CarryVT, MVT::i32),
4974 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4975 return Carry.getValue(1);
4976}
4977
4978static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4979 SelectionDAG &DAG) {
4980 SDLoc DL(Flags);
4981
4982 // Now convert the carry flag into a boolean carry. We do this
4983 // using ARMISD:ADDE 0, 0, Carry
4984 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4985 DAG.getConstant(0, DL, MVT::i32),
4986 DAG.getConstant(0, DL, MVT::i32), Flags);
4987}
4988
4989SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4990 SelectionDAG &DAG) const {
4991 // Let legalize expand this if it isn't a legal type yet.
4992 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4993 return SDValue();
4994
4995 SDValue LHS = Op.getOperand(0);
4996 SDValue RHS = Op.getOperand(1);
4997 SDLoc dl(Op);
4998
4999 EVT VT = Op.getValueType();
5000 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5001 SDValue Value;
5002 SDValue Overflow;
5003 switch (Op.getOpcode()) {
5004 default:
5005 llvm_unreachable("Unknown overflow instruction!")::llvm::llvm_unreachable_internal("Unknown overflow instruction!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 5005)
;
5006 case ISD::UADDO:
5007 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
5008 // Convert the carry flag into a boolean value.
5009 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
5010 break;
5011 case ISD::USUBO: {
5012 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
5013 // Convert the carry flag into a boolean value.
5014 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
5015 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
5016 // value. So compute 1 - C.
5017 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
5018 DAG.getConstant(1, dl, MVT::i32), Overflow);
5019 break;
5020 }
5021 }
5022
5023 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
5024}
5025
5026static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG,
5027 const ARMSubtarget *Subtarget) {
5028 EVT VT = Op.getValueType();
5029 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
5030 return SDValue();
5031 if (!VT.isSimple())
5032 return SDValue();
5033
5034 unsigned NewOpcode;
5035 switch (VT.getSimpleVT().SimpleTy) {
5036 default:
5037 return SDValue();
5038 case MVT::i8:
5039 switch (Op->getOpcode()) {
5040 case ISD::UADDSAT:
5041 NewOpcode = ARMISD::UQADD8b;
5042 break;
5043 case ISD::SADDSAT:
5044 NewOpcode = ARMISD::QADD8b;
5045 break;
5046 case ISD::USUBSAT:
5047 NewOpcode = ARMISD::UQSUB8b;
5048 break;
5049 case ISD::SSUBSAT:
5050 NewOpcode = ARMISD::QSUB8b;
5051 break;
5052 }
5053 break;
5054 case MVT::i16:
5055 switch (Op->getOpcode()) {
5056 case ISD::UADDSAT:
5057 NewOpcode = ARMISD::UQADD16b;
5058 break;
5059 case ISD::SADDSAT:
5060 NewOpcode = ARMISD::QADD16b;
5061 break;
5062 case ISD::USUBSAT:
5063 NewOpcode = ARMISD::UQSUB16b;
5064 break;
5065 case ISD::SSUBSAT:
5066 NewOpcode = ARMISD::QSUB16b;
5067 break;
5068 }
5069 break;
5070 }
5071
5072 SDLoc dl(Op);
5073 SDValue Add =
5074 DAG.getNode(NewOpcode, dl, MVT::i32,
5075 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
5076 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
5077 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
5078}
5079
5080SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5081 SDValue Cond = Op.getOperand(0);
5082 SDValue SelectTrue = Op.getOperand(1);
5083 SDValue SelectFalse = Op.getOperand(2);
5084 SDLoc dl(Op);
5085 unsigned Opc = Cond.getOpcode();
5086
5087 if (Cond.getResNo() == 1 &&
5088 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5089 Opc == ISD::USUBO)) {
5090 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5091 return SDValue();
5092
5093 SDValue Value, OverflowCmp;
5094 SDValue ARMcc;
5095 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5096 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5097 EVT VT = Op.getValueType();
5098
5099 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
5100 OverflowCmp, DAG);
5101 }
5102
5103 // Convert:
5104 //
5105 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
5106 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
5107 //
5108 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
5109 const ConstantSDNode *CMOVTrue =
5110 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
5111 const ConstantSDNode *CMOVFalse =
5112 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5113
5114 if (CMOVTrue && CMOVFalse) {
5115 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
5116 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
5117
5118 SDValue True;
5119 SDValue False;
5120 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5121 True = SelectTrue;
5122 False = SelectFalse;
5123 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5124 True = SelectFalse;
5125 False = SelectTrue;
5126 }
5127
5128 if (True.getNode() && False.getNode()) {
5129 EVT VT = Op.getValueType();
5130 SDValue ARMcc = Cond.getOperand(2);
5131 SDValue CCR = Cond.getOperand(3);
5132 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
5133 assert(True.getValueType() == VT)(static_cast <bool> (True.getValueType() == VT) ? void (
0) : __assert_fail ("True.getValueType() == VT", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5133, __extension__ __PRETTY_FUNCTION__))
;
5134 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
5135 }
5136 }
5137 }
5138
5139 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
5140 // undefined bits before doing a full-word comparison with zero.
5141 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
5142 DAG.getConstant(1, dl, Cond.getValueType()));
5143
5144 return DAG.getSelectCC(dl, Cond,
5145 DAG.getConstant(0, dl, Cond.getValueType()),
5146 SelectTrue, SelectFalse, ISD::SETNE);
5147}
5148
5149static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
5150 bool &swpCmpOps, bool &swpVselOps) {
5151 // Start by selecting the GE condition code for opcodes that return true for
5152 // 'equality'
5153 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5154 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
5155 CondCode = ARMCC::GE;
5156
5157 // and GT for opcodes that return false for 'equality'.
5158 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5159 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
5160 CondCode = ARMCC::GT;
5161
5162 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5163 // to swap the compare operands.
5164 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5165 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
5166 swpCmpOps = true;
5167
5168 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5169 // If we have an unordered opcode, we need to swap the operands to the VSEL
5170 // instruction (effectively negating the condition).
5171 //
5172 // This also has the effect of swapping which one of 'less' or 'greater'
5173 // returns true, so we also swap the compare operands. It also switches
5174 // whether we return true for 'equality', so we compensate by picking the
5175 // opposite condition code to our original choice.
5176 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5177 CC == ISD::SETUGT) {
5178 swpCmpOps = !swpCmpOps;
5179 swpVselOps = !swpVselOps;
5180 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5181 }
5182
5183 // 'ordered' is 'anything but unordered', so use the VS condition code and
5184 // swap the VSEL operands.
5185 if (CC == ISD::SETO) {
5186 CondCode = ARMCC::VS;
5187 swpVselOps = true;
5188 }
5189
5190 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5191 // code and swap the VSEL operands. Also do this if we don't care about the
5192 // unordered case.
5193 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5194 CondCode = ARMCC::EQ;
5195 swpVselOps = true;
5196 }
5197}
5198
5199SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5200 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
5201 SDValue Cmp, SelectionDAG &DAG) const {
5202 if (!Subtarget->hasFP64() && VT == MVT::f64) {
5203 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5204 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5205 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5206 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5207
5208 SDValue TrueLow = TrueVal.getValue(0);
5209 SDValue TrueHigh = TrueVal.getValue(1);
5210 SDValue FalseLow = FalseVal.getValue(0);
5211 SDValue FalseHigh = FalseVal.getValue(1);
5212
5213 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5214 ARMcc, CCR, Cmp);
5215 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5216 ARMcc, CCR, duplicateCmp(Cmp, DAG));
5217
5218 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5219 } else {
5220 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
5221 Cmp);
5222 }
5223}
5224
5225static bool isGTorGE(ISD::CondCode CC) {
5226 return CC == ISD::SETGT || CC == ISD::SETGE;
5227}
5228
5229static bool isLTorLE(ISD::CondCode CC) {
5230 return CC == ISD::SETLT || CC == ISD::SETLE;
5231}
5232
5233// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5234// All of these conditions (and their <= and >= counterparts) will do:
5235// x < k ? k : x
5236// x > k ? x : k
5237// k < x ? x : k
5238// k > x ? k : x
5239static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5240 const SDValue TrueVal, const SDValue FalseVal,
5241 const ISD::CondCode CC, const SDValue K) {
5242 return (isGTorGE(CC) &&
5243 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5244 (isLTorLE(CC) &&
5245 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5246}
5247
5248// Check if two chained conditionals could be converted into SSAT or USAT.
5249//
5250// SSAT can replace a set of two conditional selectors that bound a number to an
5251// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5252//
5253// x < -k ? -k : (x > k ? k : x)
5254// x < -k ? -k : (x < k ? x : k)
5255// x > -k ? (x > k ? k : x) : -k
5256// x < k ? (x < -k ? -k : x) : k
5257// etc.
5258//
5259// LLVM canonicalizes these to either a min(max()) or a max(min())
5260// pattern. This function tries to match one of these and will return a SSAT
5261// node if successful.
5262//
5263// USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1
5264// is a power of 2.
5265static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) {
5266 EVT VT = Op.getValueType();
5267 SDValue V1 = Op.getOperand(0);
5268 SDValue K1 = Op.getOperand(1);
5269 SDValue TrueVal1 = Op.getOperand(2);
5270 SDValue FalseVal1 = Op.getOperand(3);
5271 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5272
5273 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5274 if (Op2.getOpcode() != ISD::SELECT_CC)
5275 return SDValue();
5276
5277 SDValue V2 = Op2.getOperand(0);
5278 SDValue K2 = Op2.getOperand(1);
5279 SDValue TrueVal2 = Op2.getOperand(2);
5280 SDValue FalseVal2 = Op2.getOperand(3);
5281 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5282
5283 SDValue V1Tmp = V1;
5284 SDValue V2Tmp = V2;
5285
5286 // Check that the registers and the constants match a max(min()) or min(max())
5287 // pattern
5288 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5289 K2 != FalseVal2 ||
5290 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5291 return SDValue();
5292
5293 // Check that the constant in the lower-bound check is
5294 // the opposite of the constant in the upper-bound check
5295 // in 1's complement.
5296 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5297 return SDValue();
5298
5299 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5300 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5301 int64_t PosVal = std::max(Val1, Val2);
5302 int64_t NegVal = std::min(Val1, Val2);
5303
5304 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5305 !isPowerOf2_64(PosVal + 1))
5306 return SDValue();
5307
5308 // Handle the difference between USAT (unsigned) and SSAT (signed)
5309 // saturation
5310 // At this point, PosVal is guaranteed to be positive
5311 uint64_t K = PosVal;
5312 SDLoc dl(Op);
5313 if (Val1 == ~Val2)
5314 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5315 DAG.getConstant(countTrailingOnes(K), dl, VT));
5316 if (NegVal == 0)
5317 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5318 DAG.getConstant(countTrailingOnes(K), dl, VT));
5319
5320 return SDValue();
5321}
5322
5323// Check if a condition of the type x < k ? k : x can be converted into a
5324// bit operation instead of conditional moves.
5325// Currently this is allowed given:
5326// - The conditions and values match up
5327// - k is 0 or -1 (all ones)
5328// This function will not check the last condition, thats up to the caller
5329// It returns true if the transformation can be made, and in such case
5330// returns x in V, and k in SatK.
5331static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5332 SDValue &SatK)
5333{
5334 SDValue LHS = Op.getOperand(0);
5335 SDValue RHS = Op.getOperand(1);
5336 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5337 SDValue TrueVal = Op.getOperand(2);
5338 SDValue FalseVal = Op.getOperand(3);
5339
5340 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5341 ? &RHS
5342 : nullptr;
5343
5344 // No constant operation in comparison, early out
5345 if (!K)
5346 return false;
5347
5348 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5349 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5350 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5351
5352 // If the constant on left and right side, or variable on left and right,
5353 // does not match, early out
5354 if (*K != KTmp || V != VTmp)
5355 return false;
5356
5357 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5358 SatK = *K;
5359 return true;
5360 }
5361
5362 return false;
5363}
5364
5365bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5366 if (VT == MVT::f32)
5367 return !Subtarget->hasVFP2Base();
5368 if (VT == MVT::f64)
5369 return !Subtarget->hasFP64();
5370 if (VT == MVT::f16)
5371 return !Subtarget->hasFullFP16();
5372 return false;
5373}
5374
5375SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5376 EVT VT = Op.getValueType();
5377 SDLoc dl(Op);
5378
5379 // Try to convert two saturating conditional selects into a single SSAT
5380 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5381 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5382 return SatValue;
5383
5384 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5385 // into more efficient bit operations, which is possible when k is 0 or -1
5386 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5387 // single instructions. On Thumb the shift and the bit operation will be two
5388 // instructions.
5389 // Only allow this transformation on full-width (32-bit) operations
5390 SDValue LowerSatConstant;
5391 SDValue SatValue;
5392 if (VT == MVT::i32 &&
5393 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5394 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5395 DAG.getConstant(31, dl, VT));
5396 if (isNullConstant(LowerSatConstant)) {
5397 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5398 DAG.getAllOnesConstant(dl, VT));
5399 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5400 } else if (isAllOnesConstant(LowerSatConstant))
5401 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5402 }
5403
5404 SDValue LHS = Op.getOperand(0);
5405 SDValue RHS = Op.getOperand(1);
5406 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5407 SDValue TrueVal = Op.getOperand(2);
5408 SDValue FalseVal = Op.getOperand(3);
5409 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5410 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5411
5412 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5413 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5414 unsigned TVal = CTVal->getZExtValue();
5415 unsigned FVal = CFVal->getZExtValue();
5416 unsigned Opcode = 0;
5417
5418 if (TVal == ~FVal) {
5419 Opcode = ARMISD::CSINV;
5420 } else if (TVal == ~FVal + 1) {
5421 Opcode = ARMISD::CSNEG;
5422 } else if (TVal + 1 == FVal) {
5423 Opcode = ARMISD::CSINC;
5424 } else if (TVal == FVal + 1) {
5425 Opcode = ARMISD::CSINC;
5426 std::swap(TrueVal, FalseVal);
5427 std::swap(TVal, FVal);
5428 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5429 }
5430
5431 if (Opcode) {
5432 // If one of the constants is cheaper than another, materialise the
5433 // cheaper one and let the csel generate the other.
5434 if (Opcode != ARMISD::CSINC &&
5435 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5436 std::swap(TrueVal, FalseVal);
5437 std::swap(TVal, FVal);
5438 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5439 }
5440
5441 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5442 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5443 // -(-a) == a, but (a+1)+1 != a).
5444 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5445 std::swap(TrueVal, FalseVal);
5446 std::swap(TVal, FVal);
5447 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5448 }
5449
5450 // Drops F's value because we can get it by inverting/negating TVal.
5451 FalseVal = TrueVal;
5452
5453 SDValue ARMcc;
5454 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5455 EVT VT = TrueVal.getValueType();
5456 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5457 }
5458 }
5459
5460 if (isUnsupportedFloatingType(LHS.getValueType())) {
5461 DAG.getTargetLoweringInfo().softenSetCCOperands(
5462 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5463
5464 // If softenSetCCOperands only returned one value, we should compare it to
5465 // zero.
5466 if (!RHS.getNode()) {
5467 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5468 CC = ISD::SETNE;
5469 }
5470 }
5471
5472 if (LHS.getValueType() == MVT::i32) {
5473 // Try to generate VSEL on ARMv8.
5474 // The VSEL instruction can't use all the usual ARM condition
5475 // codes: it only has two bits to select the condition code, so it's
5476 // constrained to use only GE, GT, VS and EQ.
5477 //
5478 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5479 // swap the operands of the previous compare instruction (effectively
5480 // inverting the compare condition, swapping 'less' and 'greater') and
5481 // sometimes need to swap the operands to the VSEL (which inverts the
5482 // condition in the sense of firing whenever the previous condition didn't)
5483 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5484 TrueVal.getValueType() == MVT::f32 ||
5485 TrueVal.getValueType() == MVT::f64)) {
5486 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5487 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5488 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5489 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5490 std::swap(TrueVal, FalseVal);
5491 }
5492 }
5493
5494 SDValue ARMcc;
5495 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5496 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5497 // Choose GE over PL, which vsel does now support
5498 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5499 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5500 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5501 }
5502
5503 ARMCC::CondCodes CondCode, CondCode2;
5504 FPCCToARMCC(CC, CondCode, CondCode2);
5505
5506 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5507 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5508 // must use VSEL (limited condition codes), due to not having conditional f16
5509 // moves.
5510 if (Subtarget->hasFPARMv8Base() &&
5511 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5512 (TrueVal.getValueType() == MVT::f16 ||
5513 TrueVal.getValueType() == MVT::f32 ||
5514 TrueVal.getValueType() == MVT::f64)) {
5515 bool swpCmpOps = false;
5516 bool swpVselOps = false;
5517 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5518
5519 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5520 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5521 if (swpCmpOps)
5522 std::swap(LHS, RHS);
5523 if (swpVselOps)
5524 std::swap(TrueVal, FalseVal);
5525 }
5526 }
5527
5528 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5529 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5530 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5531 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5532 if (CondCode2 != ARMCC::AL) {
5533 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5534 // FIXME: Needs another CMP because flag can have but one use.
5535 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5536 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5537 }
5538 return Result;
5539}
5540
5541/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5542/// to morph to an integer compare sequence.
5543static bool canChangeToInt(SDValue Op, bool &SeenZero,
5544 const ARMSubtarget *Subtarget) {
5545 SDNode *N = Op.getNode();
5546 if (!N->hasOneUse())
5547 // Otherwise it requires moving the value from fp to integer registers.
5548 return false;
5549 if (!N->getNumValues())
5550 return false;
5551 EVT VT = Op.getValueType();
5552 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5553 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5554 // vmrs are very slow, e.g. cortex-a8.
5555 return false;
5556
5557 if (isFloatingPointZero(Op)) {
5558 SeenZero = true;
5559 return true;
5560 }
5561 return ISD::isNormalLoad(N);
5562}
5563
5564static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5565 if (isFloatingPointZero(Op))
5566 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5567
5568 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5569 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5570 Ld->getPointerInfo(), Ld->getAlign(),
5571 Ld->getMemOperand()->getFlags());
5572
5573 llvm_unreachable("Unknown VFP cmp argument!")::llvm::llvm_unreachable_internal("Unknown VFP cmp argument!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 5573)
;
5574}
5575
5576static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5577 SDValue &RetVal1, SDValue &RetVal2) {
5578 SDLoc dl(Op);
5579
5580 if (isFloatingPointZero(Op)) {
5581 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5582 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5583 return;
5584 }
5585
5586 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5587 SDValue Ptr = Ld->getBasePtr();
5588 RetVal1 =
5589 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5590 Ld->getAlign(), Ld->getMemOperand()->getFlags());
5591
5592 EVT PtrType = Ptr.getValueType();
5593 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5594 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5595 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5596 Ld->getPointerInfo().getWithOffset(4),
5597 commonAlignment(Ld->getAlign(), 4),
5598 Ld->getMemOperand()->getFlags());
5599 return;
5600 }
5601
5602 llvm_unreachable("Unknown VFP cmp argument!")::llvm::llvm_unreachable_internal("Unknown VFP cmp argument!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 5602)
;
5603}
5604
5605/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5606/// f32 and even f64 comparisons to integer ones.
5607SDValue
5608ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5609 SDValue Chain = Op.getOperand(0);
5610 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5611 SDValue LHS = Op.getOperand(2);
5612 SDValue RHS = Op.getOperand(3);
5613 SDValue Dest = Op.getOperand(4);
5614 SDLoc dl(Op);
5615
5616 bool LHSSeenZero = false;
5617 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5618 bool RHSSeenZero = false;
5619 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5620 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5621 // If unsafe fp math optimization is enabled and there are no other uses of
5622 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5623 // to an integer comparison.
5624 if (CC == ISD::SETOEQ)
5625 CC = ISD::SETEQ;
5626 else if (CC == ISD::SETUNE)
5627 CC = ISD::SETNE;
5628
5629 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5630 SDValue ARMcc;
5631 if (LHS.getValueType() == MVT::f32) {
5632 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5633 bitcastf32Toi32(LHS, DAG), Mask);
5634 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5635 bitcastf32Toi32(RHS, DAG), Mask);
5636 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5637 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5638 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5639 Chain, Dest, ARMcc, CCR, Cmp);
5640 }
5641
5642 SDValue LHS1, LHS2;
5643 SDValue RHS1, RHS2;
5644 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5645 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5646 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5647 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5648 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5649 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5650 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5651 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5652 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5653 }
5654
5655 return SDValue();
5656}
5657
5658SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5659 SDValue Chain = Op.getOperand(0);
5660 SDValue Cond = Op.getOperand(1);
5661 SDValue Dest = Op.getOperand(2);
5662 SDLoc dl(Op);
5663
5664 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5665 // instruction.
5666 unsigned Opc = Cond.getOpcode();
5667 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5668 !Subtarget->isThumb1Only();
5669 if (Cond.getResNo() == 1 &&
5670 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5671 Opc == ISD::USUBO || OptimizeMul)) {
5672 // Only lower legal XALUO ops.
5673 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5674 return SDValue();
5675
5676 // The actual operation with overflow check.
5677 SDValue Value, OverflowCmp;
5678 SDValue ARMcc;
5679 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5680
5681 // Reverse the condition code.
5682 ARMCC::CondCodes CondCode =
5683 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5684 CondCode = ARMCC::getOppositeCondition(CondCode);
5685 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5686 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5687
5688 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5689 OverflowCmp);
5690 }
5691
5692 return SDValue();
5693}
5694
5695SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5696 SDValue Chain = Op.getOperand(0);
5697 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5698 SDValue LHS = Op.getOperand(2);
5699 SDValue RHS = Op.getOperand(3);
5700 SDValue Dest = Op.getOperand(4);
5701 SDLoc dl(Op);
5702
5703 if (isUnsupportedFloatingType(LHS.getValueType())) {
5704 DAG.getTargetLoweringInfo().softenSetCCOperands(
5705 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5706
5707 // If softenSetCCOperands only returned one value, we should compare it to
5708 // zero.
5709 if (!RHS.getNode()) {
5710 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5711 CC = ISD::SETNE;
5712 }
5713 }
5714
5715 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5716 // instruction.
5717 unsigned Opc = LHS.getOpcode();
5718 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5719 !Subtarget->isThumb1Only();
5720 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5721 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5722 Opc == ISD::USUBO || OptimizeMul) &&
5723 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5724 // Only lower legal XALUO ops.
5725 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5726 return SDValue();
5727
5728 // The actual operation with overflow check.
5729 SDValue Value, OverflowCmp;
5730 SDValue ARMcc;
5731 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5732
5733 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5734 // Reverse the condition code.
5735 ARMCC::CondCodes CondCode =
5736 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5737 CondCode = ARMCC::getOppositeCondition(CondCode);
5738 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5739 }
5740 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5741
5742 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5743 OverflowCmp);
5744 }
5745
5746 if (LHS.getValueType() == MVT::i32) {
5747 SDValue ARMcc;
5748 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5749 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5750 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5751 Chain, Dest, ARMcc, CCR, Cmp);
5752 }
5753
5754 if (getTargetMachine().Options.UnsafeFPMath &&
5755 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5756 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5757 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5758 return Result;
5759 }
5760
5761 ARMCC::CondCodes CondCode, CondCode2;
5762 FPCCToARMCC(CC, CondCode, CondCode2);
5763
5764 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5765 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5766 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5767 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5768 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5769 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5770 if (CondCode2 != ARMCC::AL) {
5771 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5772 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5773 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5774 }
5775 return Res;
5776}
5777
5778SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5779 SDValue Chain = Op.getOperand(0);
5780 SDValue Table = Op.getOperand(1);
5781 SDValue Index = Op.getOperand(2);
5782 SDLoc dl(Op);
5783
5784 EVT PTy = getPointerTy(DAG.getDataLayout());
5785 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5786 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5787 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5788 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5789 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5790 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5791 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5792 // which does another jump to the destination. This also makes it easier
5793 // to translate it to TBB / TBH later (Thumb2 only).
5794 // FIXME: This might not work if the function is extremely large.
5795 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5796 Addr, Op.getOperand(2), JTI);
5797 }
5798 if (isPositionIndependent() || Subtarget->isROPI()) {
5799 Addr =
5800 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5801 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5802 Chain = Addr.getValue(1);
5803 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5804 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5805 } else {
5806 Addr =
5807 DAG.getLoad(PTy, dl, Chain, Addr,
5808 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5809 Chain = Addr.getValue(1);
5810 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5811 }
5812}
5813
5814static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5815 EVT VT = Op.getValueType();
5816 SDLoc dl(Op);
5817
5818 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5819 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5820 return Op;
5821 return DAG.UnrollVectorOp(Op.getNode());
5822 }
5823
5824 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5825
5826 EVT NewTy;
5827 const EVT OpTy = Op.getOperand(0).getValueType();
5828 if (OpTy == MVT::v4f32)
5829 NewTy = MVT::v4i32;
5830 else if (OpTy == MVT::v4f16 && HasFullFP16)
5831 NewTy = MVT::v4i16;
5832 else if (OpTy == MVT::v8f16 && HasFullFP16)
5833 NewTy = MVT::v8i16;
5834 else
5835 llvm_unreachable("Invalid type for custom lowering!")::llvm::llvm_unreachable_internal("Invalid type for custom lowering!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 5835)
;
5836
5837 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5838 return DAG.UnrollVectorOp(Op.getNode());
5839
5840 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5841 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5842}
5843
5844SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5845 EVT VT = Op.getValueType();
5846 if (VT.isVector())
5847 return LowerVectorFP_TO_INT(Op, DAG);
5848
5849 bool IsStrict = Op->isStrictFPOpcode();
5850 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5851
5852 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5853 RTLIB::Libcall LC;
5854 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5855 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5856 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5857 Op.getValueType());
5858 else
5859 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5860 Op.getValueType());
5861 SDLoc Loc(Op);
5862 MakeLibCallOptions CallOptions;
5863 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5864 SDValue Result;
5865 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5866 CallOptions, Loc, Chain);
5867 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5868 }
5869
5870 // FIXME: Remove this when we have strict fp instruction selection patterns
5871 if (IsStrict) {
5872 SDLoc Loc(Op);
5873 SDValue Result =
5874 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5875 : ISD::FP_TO_UINT,
5876 Loc, Op.getValueType(), SrcVal);
5877 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5878 }
5879
5880 return Op;
5881}
5882
5883static SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
5884 const ARMSubtarget *Subtarget) {
5885 EVT VT = Op.getValueType();
5886 EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5887 EVT FromVT = Op.getOperand(0).getValueType();
5888
5889 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5890 return Op;
5891 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5892 Subtarget->hasFP64())
5893 return Op;
5894 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5895 Subtarget->hasFullFP16())
5896 return Op;
5897 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5898 Subtarget->hasMVEFloatOps())
5899 return Op;
5900 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5901 Subtarget->hasMVEFloatOps())
5902 return Op;
5903
5904 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5905 return SDValue();
5906
5907 SDLoc DL(Op);
5908 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5909 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5910 SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
5911 DAG.getValueType(VT.getScalarType()));
5912 SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
5913 DAG.getConstant((1 << BW) - 1, DL, VT));
5914 if (IsSigned)
5915 Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
5916 DAG.getConstant(-(1 << BW), DL, VT));
5917 return Max;
5918}
5919
5920static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5921 EVT VT = Op.getValueType();
5922 SDLoc dl(Op);
5923
5924 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5925 if (VT.getVectorElementType() == MVT::f32)
5926 return Op;
5927 return DAG.UnrollVectorOp(Op.getNode());
5928 }
5929
5930 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||(static_cast <bool> ((Op.getOperand(0).getValueType() ==
MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16)
&& "Invalid type for custom lowering!") ? void (0) :
__assert_fail ("(Op.getOperand(0).getValueType() == MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16) && \"Invalid type for custom lowering!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 5932, __extension__
__PRETTY_FUNCTION__))
5931 Op.getOperand(0).getValueType() == MVT::v8i16) &&(static_cast <bool> ((Op.getOperand(0).getValueType() ==
MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16)
&& "Invalid type for custom lowering!") ? void (0) :
__assert_fail ("(Op.getOperand(0).getValueType() == MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16) && \"Invalid type for custom lowering!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 5932, __extension__
__PRETTY_FUNCTION__))
5932 "Invalid type for custom lowering!")(static_cast <bool> ((Op.getOperand(0).getValueType() ==
MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16)
&& "Invalid type for custom lowering!") ? void (0) :
__assert_fail ("(Op.getOperand(0).getValueType() == MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16) && \"Invalid type for custom lowering!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 5932, __extension__
__PRETTY_FUNCTION__))
;
5933
5934 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5935
5936 EVT DestVecType;
5937 if (VT == MVT::v4f32)
5938 DestVecType = MVT::v4i32;
5939 else if (VT == MVT::v4f16 && HasFullFP16)
5940 DestVecType = MVT::v4i16;
5941 else if (VT == MVT::v8f16 && HasFullFP16)
5942 DestVecType = MVT::v8i16;
5943 else
5944 return DAG.UnrollVectorOp(Op.getNode());
5945
5946 unsigned CastOpc;
5947 unsigned Opc;
5948 switch (Op.getOpcode()) {
5949 default: llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5949)
;
5950 case ISD::SINT_TO_FP:
5951 CastOpc = ISD::SIGN_EXTEND;
5952 Opc = ISD::SINT_TO_FP;
5953 break;
5954 case ISD::UINT_TO_FP:
5955 CastOpc = ISD::ZERO_EXTEND;
5956 Opc = ISD::UINT_TO_FP;
5957 break;
5958 }
5959
5960 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5961 return DAG.getNode(Opc, dl, VT, Op);
5962}
5963
5964SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5965 EVT VT = Op.getValueType();
5966 if (VT.isVector())
5967 return LowerVectorINT_TO_FP(Op, DAG);
5968 if (isUnsupportedFloatingType(VT)) {
5969 RTLIB::Libcall LC;
5970 if (Op.getOpcode() == ISD::SINT_TO_FP)
5971 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5972 Op.getValueType());
5973 else
5974 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5975 Op.getValueType());
5976 MakeLibCallOptions CallOptions;
5977 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5978 CallOptions, SDLoc(Op)).first;
5979 }
5980
5981 return Op;
5982}
5983
5984SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5985 // Implement fcopysign with a fabs and a conditional fneg.
5986 SDValue Tmp0 = Op.getOperand(0);
5987 SDValue Tmp1 = Op.getOperand(1);
5988 SDLoc dl(Op);
5989 EVT VT = Op.getValueType();
5990 EVT SrcVT = Tmp1.getValueType();
5991 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5992 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5993 bool UseNEON = !InGPR && Subtarget->hasNEON();
5994
5995 if (UseNEON) {
5996 // Use VBSL to copy the sign bit.
5997 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5998 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5999 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
6000 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
6001 if (VT == MVT::f64)
6002 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6003 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
6004 DAG.getConstant(32, dl, MVT::i32));
6005 else /*if (VT == MVT::f32)*/
6006 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
6007 if (SrcVT == MVT::f32) {
6008 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
6009 if (VT == MVT::f64)
6010 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6011 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
6012 DAG.getConstant(32, dl, MVT::i32));
6013 } else if (VT == MVT::f32)
6014 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
6015 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
6016 DAG.getConstant(32, dl, MVT::i32));
6017 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
6018 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
6019
6020 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
6021 dl, MVT::i32);
6022 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
6023 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
6024 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
6025
6026 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
6027 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
6028 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
6029 if (VT == MVT::f32) {
6030 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
6031 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
6032 DAG.getConstant(0, dl, MVT::i32));
6033 } else {
6034 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
6035 }
6036
6037 return Res;
6038 }
6039
6040 // Bitcast operand 1 to i32.
6041 if (SrcVT == MVT::f64)
6042 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6043 Tmp1).getValue(1);
6044 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
6045
6046 // Or in the signbit with integer operations.
6047 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
6048 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
6049 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
6050 if (VT == MVT::f32) {
6051 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
6052 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
6053 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
6054 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
6055 }
6056
6057 // f64: Or the high part with signbit and then combine two parts.
6058 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6059 Tmp0);
6060 SDValue Lo = Tmp0.getValue(0);
6061 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
6062 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
6063 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
6064}
6065
6066SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
6067 MachineFunction &MF = DAG.getMachineFunction();
6068 MachineFrameInfo &MFI = MF.getFrameInfo();
6069 MFI.setReturnAddressIsTaken(true);
6070
6071 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
6072 return SDValue();
6073
6074 EVT VT = Op.getValueType();
6075 SDLoc dl(Op);
6076 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6077 if (Depth) {
6078 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6079 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
6080 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
6081 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
6082 MachinePointerInfo());
6083 }
6084
6085 // Return LR, which contains the return address. Mark it an implicit live-in.
6086 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
6087 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
6088}
6089
6090SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6091 const ARMBaseRegisterInfo &ARI =
6092 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
6093 MachineFunction &MF = DAG.getMachineFunction();
6094 MachineFrameInfo &MFI = MF.getFrameInfo();
6095 MFI.setFrameAddressIsTaken(true);
6096
6097 EVT VT = Op.getValueType();
6098 SDLoc dl(Op); // FIXME probably not meaningful
6099 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6100 Register FrameReg = ARI.getFrameRegister(MF);
6101 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6102 while (Depth--)
6103 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6104 MachinePointerInfo());
6105 return FrameAddr;
6106}
6107
6108// FIXME? Maybe this could be a TableGen attribute on some registers and
6109// this table could be generated automatically from RegInfo.
6110Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6111 const MachineFunction &MF) const {
6112 Register Reg = StringSwitch<unsigned>(RegName)
6113 .Case("sp", ARM::SP)
6114 .Default(0);
6115 if (Reg)
6116 return Reg;
6117 report_fatal_error(Twine("Invalid register name \""
6118 + StringRef(RegName) + "\"."));
6119}
6120
6121// Result is 64 bit value so split into two 32 bit values and return as a
6122// pair of values.
6123static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
6124 SelectionDAG &DAG) {
6125 SDLoc DL(N);
6126
6127 // This function is only supposed to be called for i64 type destination.
6128 assert(N->getValueType(0) == MVT::i64(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"ExpandREAD_REGISTER called for non-i64 type result.") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"ExpandREAD_REGISTER called for non-i64 type result.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6129, __extension__
__PRETTY_FUNCTION__))
6129 && "ExpandREAD_REGISTER called for non-i64 type result.")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"ExpandREAD_REGISTER called for non-i64 type result.") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"ExpandREAD_REGISTER called for non-i64 type result.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6129, __extension__
__PRETTY_FUNCTION__))
;
6130
6131 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
6132 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6133 N->getOperand(0),
6134 N->getOperand(1));
6135
6136 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6137 Read.getValue(1)));
6138 Results.push_back(Read.getOperand(0));
6139}
6140
6141/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6142/// When \p DstVT, the destination type of \p BC, is on the vector
6143/// register bank and the source of bitcast, \p Op, operates on the same bank,
6144/// it might be possible to combine them, such that everything stays on the
6145/// vector register bank.
6146/// \p return The node that would replace \p BT, if the combine
6147/// is possible.
6148static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
6149 SelectionDAG &DAG) {
6150 SDValue Op = BC->getOperand(0);
6151 EVT DstVT = BC->getValueType(0);
6152
6153 // The only vector instruction that can produce a scalar (remember,
6154 // since the bitcast was about to be turned into VMOVDRR, the source
6155 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6156 // Moreover, we can do this combine only if there is one use.
6157 // Finally, if the destination type is not a vector, there is not
6158 // much point on forcing everything on the vector bank.
6159 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6160 !Op.hasOneUse())
6161 return SDValue();
6162
6163 // If the index is not constant, we will introduce an additional
6164 // multiply that will stick.
6165 // Give up in that case.
6166 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6167 if (!Index)
6168 return SDValue();
6169 unsigned DstNumElt = DstVT.getVectorNumElements();
6170
6171 // Compute the new index.
6172 const APInt &APIntIndex = Index->getAPIntValue();
6173 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6174 NewIndex *= APIntIndex;
6175 // Check if the new constant index fits into i32.
6176 if (NewIndex.getBitWidth() > 32)
6177 return SDValue();
6178
6179 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6180 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6181 SDLoc dl(Op);
6182 SDValue ExtractSrc = Op.getOperand(0);
6183 EVT VecVT = EVT::getVectorVT(
6184 *DAG.getContext(), DstVT.getScalarType(),
6185 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6186 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6187 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6188 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6189}
6190
6191/// ExpandBITCAST - If the target supports VFP, this function is called to
6192/// expand a bit convert where either the source or destination type is i64 to
6193/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
6194/// operand type is illegal (e.g., v2f32 for a target that doesn't support
6195/// vectors), since the legalizer won't know what to do with that.
6196SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6197 const ARMSubtarget *Subtarget) const {
6198 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6199 SDLoc dl(N);
6200 SDValue Op = N->getOperand(0);
6201
6202 // This function is only supposed to be called for i16 and i64 types, either
6203 // as the source or destination of the bit convert.
6204 EVT SrcVT = Op.getValueType();
6205 EVT DstVT = N->getValueType(0);
6206
6207 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6208 (DstVT == MVT::f16 || DstVT == MVT::bf16))
6209 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6210 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6211
6212 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6213 (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
6214 return DAG.getNode(
6215 ISD::TRUNCATE, SDLoc(N), DstVT,
6216 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6217
6218 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6219 return SDValue();
6220
6221 // Turn i64->f64 into VMOVDRR.
6222 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
6223 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6224 // if we can combine the bitcast with its source.
6225 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
6226 return Val;
6227
6228 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
6229 DAG.getConstant(0, dl, MVT::i32));
6230 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
6231 DAG.getConstant(1, dl, MVT::i32));
6232 return DAG.getNode(ISD::BITCAST, dl, DstVT,
6233 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6234 }
6235
6236 // Turn f64->i64 into VMOVRRD.
6237 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
6238 SDValue Cvt;
6239 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6240 SrcVT.getVectorNumElements() > 1)
6241 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6242 DAG.getVTList(MVT::i32, MVT::i32),
6243 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6244 else
6245 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6246 DAG.getVTList(MVT::i32, MVT::i32), Op);
6247 // Merge the pieces into a single i64 value.
6248 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6249 }
6250
6251 return SDValue();
6252}
6253
6254/// getZeroVector - Returns a vector of specified type with all zero elements.
6255/// Zero vectors are used to represent vector negation and in those cases
6256/// will be implemented with the NEON VNEG instruction. However, VNEG does
6257/// not support i64 elements, so sometimes the zero vectors will need to be
6258/// explicitly constructed. Regardless, use a canonical VMOV to create the
6259/// zero vector.
6260static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6261 assert(VT.isVector() && "Expected a vector type")(static_cast <bool> (VT.isVector() && "Expected a vector type"
) ? void (0) : __assert_fail ("VT.isVector() && \"Expected a vector type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6261, __extension__
__PRETTY_FUNCTION__))
;
6262 // The canonical modified immediate encoding of a zero vector is....0!
6263 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6264 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6265 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6266 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6267}
6268
6269/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6270/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6271SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6272 SelectionDAG &DAG) const {
6273 assert(Op.getNumOperands() == 3 && "Not a double-shift!")(static_cast <bool> (Op.getNumOperands() == 3 &&
"Not a double-shift!") ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && \"Not a double-shift!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6273, __extension__
__PRETTY_FUNCTION__))
;
6274 EVT VT = Op.getValueType();
6275 unsigned VTBits = VT.getSizeInBits();
6276 SDLoc dl(Op);
6277 SDValue ShOpLo = Op.getOperand(0);
6278 SDValue ShOpHi = Op.getOperand(1);
6279 SDValue ShAmt = Op.getOperand(2);
6280 SDValue ARMcc;
6281 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6282 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6283
6284 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS)(static_cast <bool> (Op.getOpcode() == ISD::SRA_PARTS ||
Op.getOpcode() == ISD::SRL_PARTS) ? void (0) : __assert_fail
("Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6284, __extension__
__PRETTY_FUNCTION__))
;
6285
6286 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6287 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6288 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6289 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6290 DAG.getConstant(VTBits, dl, MVT::i32));
6291 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6292 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6293 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6294 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6295 ISD::SETGE, ARMcc, DAG, dl);
6296 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6297 ARMcc, CCR, CmpLo);
6298
6299 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6300 SDValue HiBigShift = Opc == ISD::SRA
6301 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6302 DAG.getConstant(VTBits - 1, dl, VT))
6303 : DAG.getConstant(0, dl, VT);
6304 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6305 ISD::SETGE, ARMcc, DAG, dl);
6306 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6307 ARMcc, CCR, CmpHi);
6308
6309 SDValue Ops[2] = { Lo, Hi };
6310 return DAG.getMergeValues(Ops, dl);
6311}
6312
6313/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6314/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6315SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6316 SelectionDAG &DAG) const {
6317 assert(Op.getNumOperands() == 3 && "Not a double-shift!")(static_cast <bool> (Op.getNumOperands() == 3 &&
"Not a double-shift!") ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && \"Not a double-shift!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6317, __extension__
__PRETTY_FUNCTION__))
;
6318 EVT VT = Op.getValueType();
6319 unsigned VTBits = VT.getSizeInBits();
6320 SDLoc dl(Op);
6321 SDValue ShOpLo = Op.getOperand(0);
6322 SDValue ShOpHi = Op.getOperand(1);
6323 SDValue ShAmt = Op.getOperand(2);
6324 SDValue ARMcc;
6325 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6326
6327 assert(Op.getOpcode() == ISD::SHL_PARTS)(static_cast <bool> (Op.getOpcode() == ISD::SHL_PARTS) ?
void (0) : __assert_fail ("Op.getOpcode() == ISD::SHL_PARTS"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6327, __extension__
__PRETTY_FUNCTION__))
;
6328 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6329 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6330 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6331 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6332 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6333
6334 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6335 DAG.getConstant(VTBits, dl, MVT::i32));
6336 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6337 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6338 ISD::SETGE, ARMcc, DAG, dl);
6339 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6340 ARMcc, CCR, CmpHi);
6341
6342 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6343 ISD::SETGE, ARMcc, DAG, dl);
6344 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6345 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6346 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6347
6348 SDValue Ops[2] = { Lo, Hi };
6349 return DAG.getMergeValues(Ops, dl);
6350}
6351
6352SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6353 SelectionDAG &DAG) const {
6354 // The rounding mode is in bits 23:22 of the FPSCR.
6355 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6356 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6357 // so that the shift + and get folded into a bitfield extract.
6358 SDLoc dl(Op);
6359 SDValue Chain = Op.getOperand(0);
6360 SDValue Ops[] = {Chain,
6361 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6362
6363 SDValue FPSCR =
6364 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6365 Chain = FPSCR.getValue(1);
6366 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6367 DAG.getConstant(1U << 22, dl, MVT::i32));
6368 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6369 DAG.getConstant(22, dl, MVT::i32));
6370 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6371 DAG.getConstant(3, dl, MVT::i32));
6372 return DAG.getMergeValues({And, Chain}, dl);
6373}
6374
6375SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6376 SelectionDAG &DAG) const {
6377 SDLoc DL(Op);
6378 SDValue Chain = Op->getOperand(0);
6379 SDValue RMValue = Op->getOperand(1);
6380
6381 // The rounding mode is in bits 23:22 of the FPSCR.
6382 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6383 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6384 // ((arg - 1) & 3) << 22).
6385 //
6386 // It is expected that the argument of llvm.set.rounding is within the
6387 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6388 // responsibility of the code generated llvm.set.rounding to ensure this
6389 // condition.
6390
6391 // Calculate new value of FPSCR[23:22].
6392 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6393 DAG.getConstant(1, DL, MVT::i32));
6394 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6395 DAG.getConstant(0x3, DL, MVT::i32));
6396 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6397 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6398
6399 // Get current value of FPSCR.
6400 SDValue Ops[] = {Chain,
6401 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6402 SDValue FPSCR =
6403 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6404 Chain = FPSCR.getValue(1);
6405 FPSCR = FPSCR.getValue(0);
6406
6407 // Put new rounding mode into FPSCR[23:22].
6408 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6409 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6410 DAG.getConstant(RMMask, DL, MVT::i32));
6411 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6412 SDValue Ops2[] = {
6413 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6414 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6415}
6416
6417static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6418 const ARMSubtarget *ST) {
6419 SDLoc dl(N);
6420 EVT VT = N->getValueType(0);
6421 if (VT.isVector() && ST->hasNEON()) {
6422
6423 // Compute the least significant set bit: LSB = X & -X
6424 SDValue X = N->getOperand(0);
6425 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6426 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6427
6428 EVT ElemTy = VT.getVectorElementType();
6429
6430 if (ElemTy == MVT::i8) {
6431 // Compute with: cttz(x) = ctpop(lsb - 1)
6432 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6433 DAG.getTargetConstant(1, dl, ElemTy));
6434 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6435 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6436 }
6437
6438 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6439 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6440 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6441 unsigned NumBits = ElemTy.getSizeInBits();
6442 SDValue WidthMinus1 =
6443 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6444 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6445 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6446 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6447 }
6448
6449 // Compute with: cttz(x) = ctpop(lsb - 1)
6450
6451 // Compute LSB - 1.
6452 SDValue Bits;
6453 if (ElemTy == MVT::i64) {
6454 // Load constant 0xffff'ffff'ffff'ffff to register.
6455 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6456 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6457 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6458 } else {
6459 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6460 DAG.getTargetConstant(1, dl, ElemTy));
6461 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6462 }
6463 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6464 }
6465
6466 if (!ST->hasV6T2Ops())
6467 return SDValue();
6468
6469 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6470 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6471}
6472
6473static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6474 const ARMSubtarget *ST) {
6475 EVT VT = N->getValueType(0);
6476 SDLoc DL(N);
6477
6478 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.")(static_cast <bool> (ST->hasNEON() && "Custom ctpop lowering requires NEON."
) ? void (0) : __assert_fail ("ST->hasNEON() && \"Custom ctpop lowering requires NEON.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6478, __extension__
__PRETTY_FUNCTION__))
;
6479 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||(static_cast <bool> ((VT == MVT::v1i64 || VT == MVT::v2i64
|| VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 ||
VT == MVT::v8i16) && "Unexpected type for custom ctpop lowering"
) ? void (0) : __assert_fail ("(VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && \"Unexpected type for custom ctpop lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6481, __extension__
__PRETTY_FUNCTION__))
6480 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&(static_cast <bool> ((VT == MVT::v1i64 || VT == MVT::v2i64
|| VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 ||
VT == MVT::v8i16) && "Unexpected type for custom ctpop lowering"
) ? void (0) : __assert_fail ("(VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && \"Unexpected type for custom ctpop lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6481, __extension__
__PRETTY_FUNCTION__))
6481 "Unexpected type for custom ctpop lowering")(static_cast <bool> ((VT == MVT::v1i64 || VT == MVT::v2i64
|| VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 ||
VT == MVT::v8i16) && "Unexpected type for custom ctpop lowering"
) ? void (0) : __assert_fail ("(VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && \"Unexpected type for custom ctpop lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6481, __extension__
__PRETTY_FUNCTION__))
;
6482
6483 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6484 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6485 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6486 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6487
6488 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6489 unsigned EltSize = 8;
6490 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6491 while (EltSize != VT.getScalarSizeInBits()) {
6492 SmallVector<SDValue, 8> Ops;
6493 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6494 TLI.getPointerTy(DAG.getDataLayout())));
6495 Ops.push_back(Res);
6496
6497 EltSize *= 2;
6498 NumElts /= 2;
6499 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6500 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6501 }
6502
6503 return Res;
6504}
6505
6506/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6507/// operand of a vector shift operation, where all the elements of the
6508/// build_vector must have the same constant integer value.
6509static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6510 // Ignore bit_converts.
6511 while (Op.getOpcode() == ISD::BITCAST)
6512 Op = Op.getOperand(0);
6513 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6514 APInt SplatBits, SplatUndef;
6515 unsigned SplatBitSize;
6516 bool HasAnyUndefs;
6517 if (!BVN ||
6518 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6519 ElementBits) ||
6520 SplatBitSize > ElementBits)
6521 return false;
6522 Cnt = SplatBits.getSExtValue();
6523 return true;
6524}
6525
6526/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6527/// operand of a vector shift left operation. That value must be in the range:
6528/// 0 <= Value < ElementBits for a left shift; or
6529/// 0 <= Value <= ElementBits for a long left shift.
6530static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6531 assert(VT.isVector() && "vector shift count is not a vector type")(static_cast <bool> (VT.isVector() && "vector shift count is not a vector type"
) ? void (0) : __assert_fail ("VT.isVector() && \"vector shift count is not a vector type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6531, __extension__
__PRETTY_FUNCTION__))
;
6532 int64_t ElementBits = VT.getScalarSizeInBits();
6533 if (!getVShiftImm(Op, ElementBits, Cnt))
6534 return false;
6535 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6536}
6537
6538/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6539/// operand of a vector shift right operation. For a shift opcode, the value
6540/// is positive, but for an intrinsic the value count must be negative. The
6541/// absolute value must be in the range:
6542/// 1 <= |Value| <= ElementBits for a right shift; or
6543/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6544static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6545 int64_t &Cnt) {
6546 assert(VT.isVector() && "vector shift count is not a vector type")(static_cast <bool> (VT.isVector() && "vector shift count is not a vector type"
) ? void (0) : __assert_fail ("VT.isVector() && \"vector shift count is not a vector type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6546, __extension__
__PRETTY_FUNCTION__))
;
6547 int64_t ElementBits = VT.getScalarSizeInBits();
6548 if (!getVShiftImm(Op, ElementBits, Cnt))
6549 return false;
6550 if (!isIntrinsic)
6551 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6552 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6553 Cnt = -Cnt;
6554 return true;
6555 }
6556 return false;
6557}
6558
6559static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6560 const ARMSubtarget *ST) {
6561 EVT VT = N->getValueType(0);
6562 SDLoc dl(N);
6563 int64_t Cnt;
6564
6565 if (!VT.isVector())
6566 return SDValue();
6567
6568 // We essentially have two forms here. Shift by an immediate and shift by a
6569 // vector register (there are also shift by a gpr, but that is just handled
6570 // with a tablegen pattern). We cannot easily match shift by an immediate in
6571 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6572 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6573 // signed or unsigned, and a negative shift indicates a shift right).
6574 if (N->getOpcode() == ISD::SHL) {
6575 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6576 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6577 DAG.getConstant(Cnt, dl, MVT::i32));
6578 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6579 N->getOperand(1));
6580 }
6581
6582 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&(static_cast <bool> ((N->getOpcode() == ISD::SRA || N
->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && \"unexpected vector shift opcode\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6583, __extension__
__PRETTY_FUNCTION__))
6583 "unexpected vector shift opcode")(static_cast <bool> ((N->getOpcode() == ISD::SRA || N
->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && \"unexpected vector shift opcode\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6583, __extension__
__PRETTY_FUNCTION__))
;
6584
6585 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6586 unsigned VShiftOpc =
6587 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6588 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6589 DAG.getConstant(Cnt, dl, MVT::i32));
6590 }
6591
6592 // Other right shifts we don't have operations for (we use a shift left by a
6593 // negative number).
6594 EVT ShiftVT = N->getOperand(1).getValueType();
6595 SDValue NegatedCount = DAG.getNode(
6596 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6597 unsigned VShiftOpc =
6598 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6599 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6600}
6601
6602static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6603 const ARMSubtarget *ST) {
6604 EVT VT = N->getValueType(0);
6605 SDLoc dl(N);
6606
6607 // We can get here for a node like i32 = ISD::SHL i32, i64
6608 if (VT != MVT::i64)
6609 return SDValue();
6610
6611 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL
) && "Unknown shift to lower!") ? void (0) : __assert_fail
("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL) && \"Unknown shift to lower!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6613, __extension__
__PRETTY_FUNCTION__))
6612 N->getOpcode() == ISD::SHL) &&(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL
) && "Unknown shift to lower!") ? void (0) : __assert_fail
("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL) && \"Unknown shift to lower!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6613, __extension__
__PRETTY_FUNCTION__))
6613 "Unknown shift to lower!")(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL
) && "Unknown shift to lower!") ? void (0) : __assert_fail
("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL) && \"Unknown shift to lower!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6613, __extension__
__PRETTY_FUNCTION__))
;
6614
6615 unsigned ShOpc = N->getOpcode();
6616 if (ST->hasMVEIntegerOps()) {
6617 SDValue ShAmt = N->getOperand(1);
6618 unsigned ShPartsOpc = ARMISD::LSLL;
6619 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6620
6621 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6622 // then do the default optimisation
6623 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6624 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6625 return SDValue();
6626
6627 // Extract the lower 32 bits of the shift amount if it's not an i32
6628 if (ShAmt->getValueType(0) != MVT::i32)
6629 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6630
6631 if (ShOpc == ISD::SRL) {
6632 if (!Con)
6633 // There is no t2LSRLr instruction so negate and perform an lsll if the
6634 // shift amount is in a register, emulating a right shift.
6635 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6636 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6637 else
6638 // Else generate an lsrl on the immediate shift amount
6639 ShPartsOpc = ARMISD::LSRL;
6640 } else if (ShOpc == ISD::SRA)
6641 ShPartsOpc = ARMISD::ASRL;
6642
6643 // Lower 32 bits of the destination/source
6644 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6645 DAG.getConstant(0, dl, MVT::i32));
6646 // Upper 32 bits of the destination/source
6647 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6648 DAG.getConstant(1, dl, MVT::i32));
6649
6650 // Generate the shift operation as computed above
6651 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6652 ShAmt);
6653 // The upper 32 bits come from the second return value of lsll
6654 Hi = SDValue(Lo.getNode(), 1);
6655 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6656 }
6657
6658 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6659 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6660 return SDValue();
6661
6662 // If we are in thumb mode, we don't have RRX.
6663 if (ST->isThumb1Only())
6664 return SDValue();
6665
6666 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6667 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6668 DAG.getConstant(0, dl, MVT::i32));
6669 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6670 DAG.getConstant(1, dl, MVT::i32));
6671
6672 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6673 // captures the result into a carry flag.
6674 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6675 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6676
6677 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6678 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6679
6680 // Merge the pieces into a single i64 value.
6681 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6682}
6683
6684static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6685 const ARMSubtarget *ST) {
6686 bool Invert = false;
6687 bool Swap = false;
6688 unsigned Opc = ARMCC::AL;
6689
6690 SDValue Op0 = Op.getOperand(0);
6691 SDValue Op1 = Op.getOperand(1);
6692 SDValue CC = Op.getOperand(2);
6693 EVT VT = Op.getValueType();
6694 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6695 SDLoc dl(Op);
6696
6697 EVT CmpVT;
6698 if (ST->hasNEON())
6699 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6700 else {
6701 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No hardware support for integer vector comparison!") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No hardware support for integer vector comparison!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6702, __extension__
__PRETTY_FUNCTION__))
6702 "No hardware support for integer vector comparison!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No hardware support for integer vector comparison!") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No hardware support for integer vector comparison!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6702, __extension__
__PRETTY_FUNCTION__))
;
6703
6704 if (Op.getValueType().getVectorElementType() != MVT::i1)
6705 return SDValue();
6706
6707 // Make sure we expand floating point setcc to scalar if we do not have
6708 // mve.fp, so that we can handle them from there.
6709 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6710 return SDValue();
6711
6712 CmpVT = VT;
6713 }
6714
6715 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6716 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6717 // Special-case integer 64-bit equality comparisons. They aren't legal,
6718 // but they can be lowered with a few vector instructions.
6719 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6720 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6721 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6722 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6723 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6724 DAG.getCondCode(ISD::SETEQ));
6725 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6726 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6727 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6728 if (SetCCOpcode == ISD::SETNE)
6729 Merged = DAG.getNOT(dl, Merged, CmpVT);
6730 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6731 return Merged;
6732 }
6733
6734 if (CmpVT.getVectorElementType() == MVT::i64)
6735 // 64-bit comparisons are not legal in general.
6736 return SDValue();
6737
6738 if (Op1.getValueType().isFloatingPoint()) {
6739 switch (SetCCOpcode) {
6740 default: llvm_unreachable("Illegal FP comparison")::llvm::llvm_unreachable_internal("Illegal FP comparison", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6740)
;
6741 case ISD::SETUNE:
6742 case ISD::SETNE:
6743 if (ST->hasMVEFloatOps()) {
6744 Opc = ARMCC::NE; break;
6745 } else {
6746 Invert = true; [[fallthrough]];
6747 }
6748 case ISD::SETOEQ:
6749 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6750 case ISD::SETOLT:
6751 case ISD::SETLT: Swap = true; [[fallthrough]];
6752 case ISD::SETOGT:
6753 case ISD::SETGT: Opc = ARMCC::GT; break;
6754 case ISD::SETOLE:
6755 case ISD::SETLE: Swap = true; [[fallthrough]];
6756 case ISD::SETOGE:
6757 case ISD::SETGE: Opc = ARMCC::GE; break;
6758 case ISD::SETUGE: Swap = true; [[fallthrough]];
6759 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6760 case ISD::SETUGT: Swap = true; [[fallthrough]];
6761 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6762 case ISD::SETUEQ: Invert = true; [[fallthrough]];
6763 case ISD::SETONE: {
6764 // Expand this to (OLT | OGT).
6765 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6766 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6767 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6768 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6769 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6770 if (Invert)
6771 Result = DAG.getNOT(dl, Result, VT);
6772 return Result;
6773 }
6774 case ISD::SETUO: Invert = true; [[fallthrough]];
6775 case ISD::SETO: {
6776 // Expand this to (OLT | OGE).
6777 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6778 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6779 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6780 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6781 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6782 if (Invert)
6783 Result = DAG.getNOT(dl, Result, VT);
6784 return Result;
6785 }
6786 }
6787 } else {
6788 // Integer comparisons.
6789 switch (SetCCOpcode) {
6790 default: llvm_unreachable("Illegal integer comparison")::llvm::llvm_unreachable_internal("Illegal integer comparison"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6790)
;
6791 case ISD::SETNE:
6792 if (ST->hasMVEIntegerOps()) {
6793 Opc = ARMCC::NE; break;
6794 } else {
6795 Invert = true; [[fallthrough]];
6796 }
6797 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6798 case ISD::SETLT: Swap = true; [[fallthrough]];
6799 case ISD::SETGT: Opc = ARMCC::GT; break;
6800 case ISD::SETLE: Swap = true; [[fallthrough]];
6801 case ISD::SETGE: Opc = ARMCC::GE; break;
6802 case ISD::SETULT: Swap = true; [[fallthrough]];
6803 case ISD::SETUGT: Opc = ARMCC::HI; break;
6804 case ISD::SETULE: Swap = true; [[fallthrough]];
6805 case ISD::SETUGE: Opc = ARMCC::HS; break;
6806 }
6807
6808 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6809 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6810 SDValue AndOp;
6811 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6812 AndOp = Op0;
6813 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6814 AndOp = Op1;
6815
6816 // Ignore bitconvert.
6817 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6818 AndOp = AndOp.getOperand(0);
6819
6820 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6821 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6822 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6823 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6824 if (!Invert)
6825 Result = DAG.getNOT(dl, Result, VT);
6826 return Result;
6827 }
6828 }
6829 }
6830
6831 if (Swap)
6832 std::swap(Op0, Op1);
6833
6834 // If one of the operands is a constant vector zero, attempt to fold the
6835 // comparison to a specialized compare-against-zero form.
6836 SDValue SingleOp;
6837 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6838 SingleOp = Op0;
6839 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6840 if (Opc == ARMCC::GE)
6841 Opc = ARMCC::LE;
6842 else if (Opc == ARMCC::GT)
6843 Opc = ARMCC::LT;
6844 SingleOp = Op1;
6845 }
6846
6847 SDValue Result;
6848 if (SingleOp.getNode()) {
6849 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6850 DAG.getConstant(Opc, dl, MVT::i32));
6851 } else {
6852 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6853 DAG.getConstant(Opc, dl, MVT::i32));
6854 }
6855
6856 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6857
6858 if (Invert)
6859 Result = DAG.getNOT(dl, Result, VT);
6860
6861 return Result;
6862}
6863
6864static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6865 SDValue LHS = Op.getOperand(0);
6866 SDValue RHS = Op.getOperand(1);
6867 SDValue Carry = Op.getOperand(2);
6868 SDValue Cond = Op.getOperand(3);
6869 SDLoc DL(Op);
6870
6871 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.")(static_cast <bool> (LHS.getSimpleValueType().isInteger
() && "SETCCCARRY is integer only.") ? void (0) : __assert_fail
("LHS.getSimpleValueType().isInteger() && \"SETCCCARRY is integer only.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6871, __extension__
__PRETTY_FUNCTION__))
;
6872
6873 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6874 // have to invert the carry first.
6875 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6876 DAG.getConstant(1, DL, MVT::i32), Carry);
6877 // This converts the boolean value carry into the carry flag.
6878 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6879
6880 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6881 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6882
6883 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6884 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6885 SDValue ARMcc = DAG.getConstant(
6886 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6887 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6888 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6889 Cmp.getValue(1), SDValue());
6890 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6891 CCR, Chain.getValue(1));
6892}
6893
6894/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6895/// valid vector constant for a NEON or MVE instruction with a "modified
6896/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6897static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6898 unsigned SplatBitSize, SelectionDAG &DAG,
6899 const SDLoc &dl, EVT &VT, EVT VectorVT,
6900 VMOVModImmType type) {
6901 unsigned OpCmode, Imm;
6902 bool is128Bits = VectorVT.is128BitVector();
6903
6904 // SplatBitSize is set to the smallest size that splats the vector, so a
6905 // zero vector will always have SplatBitSize == 8. However, NEON modified
6906 // immediate instructions others than VMOV do not support the 8-bit encoding
6907 // of a zero vector, and the default encoding of zero is supposed to be the
6908 // 32-bit version.
6909 if (SplatBits == 0)
6910 SplatBitSize = 32;
6911
6912 switch (SplatBitSize) {
6913 case 8:
6914 if (type != VMOVModImm)
6915 return SDValue();
6916 // Any 1-byte value is OK. Op=0, Cmode=1110.
6917 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big")(static_cast <bool> ((SplatBits & ~0xff) == 0 &&
"one byte splat value is too big") ? void (0) : __assert_fail
("(SplatBits & ~0xff) == 0 && \"one byte splat value is too big\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 6917, __extension__
__PRETTY_FUNCTION__))
;
6918 OpCmode = 0xe;
6919 Imm = SplatBits;
6920 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6921 break;
6922
6923 case 16:
6924 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6925 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6926 if ((SplatBits & ~0xff) == 0) {
6927 // Value = 0x00nn: Op=x, Cmode=100x.
6928 OpCmode = 0x8;
6929 Imm = SplatBits;
6930 break;
6931 }
6932 if ((SplatBits & ~0xff00) == 0) {
6933 // Value = 0xnn00: Op=x, Cmode=101x.
6934 OpCmode = 0xa;
6935 Imm = SplatBits >> 8;
6936 break;
6937 }
6938 return SDValue();
6939
6940 case 32:
6941 // NEON's 32-bit VMOV supports splat values where:
6942 // * only one byte is nonzero, or
6943 // * the least significant byte is 0xff and the second byte is nonzero, or
6944 // * the least significant 2 bytes are 0xff and the third is nonzero.
6945 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6946 if ((SplatBits & ~0xff) == 0) {
6947 // Value = 0x000000nn: Op=x, Cmode=000x.
6948 OpCmode = 0;
6949 Imm = SplatBits;
6950 break;
6951 }
6952 if ((SplatBits & ~0xff00) == 0) {
6953 // Value = 0x0000nn00: Op=x, Cmode=001x.
6954 OpCmode = 0x2;
6955 Imm = SplatBits >> 8;
6956 break;
6957 }
6958 if ((SplatBits & ~0xff0000) == 0) {
6959 // Value = 0x00nn0000: Op=x, Cmode=010x.
6960 OpCmode = 0x4;
6961 Imm = SplatBits >> 16;
6962 break;
6963 }
6964 if ((SplatBits & ~0xff000000) == 0) {
6965 // Value = 0xnn000000: Op=x, Cmode=011x.
6966 OpCmode = 0x6;
6967 Imm = SplatBits >> 24;
6968 break;
6969 }
6970
6971 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6972 if (type == OtherModImm) return SDValue();
6973
6974 if ((SplatBits & ~0xffff) == 0 &&
6975 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6976 // Value = 0x0000nnff: Op=x, Cmode=1100.
6977 OpCmode = 0xc;
6978 Imm = SplatBits >> 8;
6979 break;
6980 }
6981
6982 // cmode == 0b1101 is not supported for MVE VMVN
6983 if (type == MVEVMVNModImm)
6984 return SDValue();
6985
6986 if ((SplatBits & ~0xffffff) == 0 &&
6987 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6988 // Value = 0x00nnffff: Op=x, Cmode=1101.
6989 OpCmode = 0xd;
6990 Imm = SplatBits >> 16;
6991 break;
6992 }
6993
6994 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6995 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6996 // VMOV.I32. A (very) minor optimization would be to replicate the value
6997 // and fall through here to test for a valid 64-bit splat. But, then the
6998 // caller would also need to check and handle the change in size.
6999 return SDValue();
7000
7001 case 64: {
7002 if (type != VMOVModImm)
7003 return SDValue();
7004 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
7005 uint64_t BitMask = 0xff;
7006 unsigned ImmMask = 1;
7007 Imm = 0;
7008 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
7009 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
7010 Imm |= ImmMask;
7011 } else if ((SplatBits & BitMask) != 0) {
7012 return SDValue();
7013 }
7014 BitMask <<= 8;
7015 ImmMask <<= 1;
7016 }
7017
7018 if (DAG.getDataLayout().isBigEndian()) {
7019 // Reverse the order of elements within the vector.
7020 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
7021 unsigned Mask = (1 << BytesPerElem) - 1;
7022 unsigned NumElems = 8 / BytesPerElem;
7023 unsigned NewImm = 0;
7024 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
7025 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
7026 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
7027 }
7028 Imm = NewImm;
7029 }
7030
7031 // Op=1, Cmode=1110.
7032 OpCmode = 0x1e;
7033 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
7034 break;
7035 }
7036
7037 default:
7038 llvm_unreachable("unexpected size for isVMOVModifiedImm")::llvm::llvm_unreachable_internal("unexpected size for isVMOVModifiedImm"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 7038)
;
7039 }
7040
7041 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
7042 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
7043}
7044
7045SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
7046 const ARMSubtarget *ST) const {
7047 EVT VT = Op.getValueType();
7048 bool IsDouble = (VT == MVT::f64);
7049 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
7050 const APFloat &FPVal = CFP->getValueAPF();
7051
7052 // Prevent floating-point constants from using literal loads
7053 // when execute-only is enabled.
7054 if (ST->genExecuteOnly()) {
7055 // If we can represent the constant as an immediate, don't lower it
7056 if (isFPImmLegal(FPVal, VT))
7057 return Op;
7058 // Otherwise, construct as integer, and move to float register
7059 APInt INTVal = FPVal.bitcastToAPInt();
7060 SDLoc DL(CFP);
7061 switch (VT.getSimpleVT().SimpleTy) {
7062 default:
7063 llvm_unreachable("Unknown floating point type!")::llvm::llvm_unreachable_internal("Unknown floating point type!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 7063)
;
7064 break;
7065 case MVT::f64: {
7066 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
7067 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
7068 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
7069 }
7070 case MVT::f32:
7071 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
7072 DAG.getConstant(INTVal, DL, MVT::i32));
7073 }
7074 }
7075
7076 if (!ST->hasVFP3Base())
7077 return SDValue();
7078
7079 // Use the default (constant pool) lowering for double constants when we have
7080 // an SP-only FPU
7081 if (IsDouble && !Subtarget->hasFP64())
7082 return SDValue();
7083
7084 // Try splatting with a VMOV.f32...
7085 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
7086
7087 if (ImmVal != -1) {
7088 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
7089 // We have code in place to select a valid ConstantFP already, no need to
7090 // do any mangling.
7091 return Op;
7092 }
7093
7094 // It's a float and we are trying to use NEON operations where
7095 // possible. Lower it to a splat followed by an extract.
7096 SDLoc DL(Op);
7097 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7098 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7099 NewVal);
7100 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7101 DAG.getConstant(0, DL, MVT::i32));
7102 }
7103
7104 // The rest of our options are NEON only, make sure that's allowed before
7105 // proceeding..
7106 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7107 return SDValue();
7108
7109 EVT VMovVT;
7110 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7111
7112 // It wouldn't really be worth bothering for doubles except for one very
7113 // important value, which does happen to match: 0.0. So make sure we don't do
7114 // anything stupid.
7115 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7116 return SDValue();
7117
7118 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7119 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7120 VMovVT, VT, VMOVModImm);
7121 if (NewVal != SDValue()) {
7122 SDLoc DL(Op);
7123 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7124 NewVal);
7125 if (IsDouble)
7126 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7127
7128 // It's a float: cast and extract a vector element.
7129 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7130 VecConstant);
7131 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7132 DAG.getConstant(0, DL, MVT::i32));
7133 }
7134
7135 // Finally, try a VMVN.i32
7136 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7137 VT, VMVNModImm);
7138 if (NewVal != SDValue()) {
7139 SDLoc DL(Op);
7140 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7141
7142 if (IsDouble)
7143 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7144
7145 // It's a float: cast and extract a vector element.
7146 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7147 VecConstant);
7148 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7149 DAG.getConstant(0, DL, MVT::i32));
7150 }
7151
7152 return SDValue();
7153}
7154
7155// check if an VEXT instruction can handle the shuffle mask when the
7156// vector sources of the shuffle are the same.
7157static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7158 unsigned NumElts = VT.getVectorNumElements();
7159
7160 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7161 if (M[0] < 0)
7162 return false;
7163
7164 Imm = M[0];
7165
7166 // If this is a VEXT shuffle, the immediate value is the index of the first
7167 // element. The other shuffle indices must be the successive elements after
7168 // the first one.
7169 unsigned ExpectedElt = Imm;
7170 for (unsigned i = 1; i < NumElts; ++i) {
7171 // Increment the expected index. If it wraps around, just follow it
7172 // back to index zero and keep going.
7173 ++ExpectedElt;
7174 if (ExpectedElt == NumElts)
7175 ExpectedElt = 0;
7176
7177 if (M[i] < 0) continue; // ignore UNDEF indices
7178 if (ExpectedElt != static_cast<unsigned>(M[i]))
7179 return false;
7180 }
7181
7182 return true;
7183}
7184
7185static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7186 bool &ReverseVEXT, unsigned &Imm) {
7187 unsigned NumElts = VT.getVectorNumElements();
7188 ReverseVEXT = false;
7189
7190 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7191 if (M[0] < 0)
7192 return false;
7193
7194 Imm = M[0];
7195
7196 // If this is a VEXT shuffle, the immediate value is the index of the first
7197 // element. The other shuffle indices must be the successive elements after
7198 // the first one.
7199 unsigned ExpectedElt = Imm;
7200 for (unsigned i = 1; i < NumElts; ++i) {
7201 // Increment the expected index. If it wraps around, it may still be
7202 // a VEXT but the source vectors must be swapped.
7203 ExpectedElt += 1;
7204 if (ExpectedElt == NumElts * 2) {
7205 ExpectedElt = 0;
7206 ReverseVEXT = true;
7207 }
7208
7209 if (M[i] < 0) continue; // ignore UNDEF indices
7210 if (ExpectedElt != static_cast<unsigned>(M[i]))
7211 return false;
7212 }
7213
7214 // Adjust the index value if the source operands will be swapped.
7215 if (ReverseVEXT)
7216 Imm -= NumElts;
7217
7218 return true;
7219}
7220
7221static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7222 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7223 // range, then 0 is placed into the resulting vector. So pretty much any mask
7224 // of 8 elements can work here.
7225 return VT == MVT::v8i8 && M.size() == 8;
7226}
7227
7228static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7229 unsigned Index) {
7230 if (Mask.size() == Elements * 2)
7231 return Index / Elements;
7232 return Mask[Index] == 0 ? 0 : 1;
7233}
7234
7235// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7236// checking that pairs of elements in the shuffle mask represent the same index
7237// in each vector, incrementing the expected index by 2 at each step.
7238// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7239// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7240// v2={e,f,g,h}
7241// WhichResult gives the offset for each element in the mask based on which
7242// of the two results it belongs to.
7243//
7244// The transpose can be represented either as:
7245// result1 = shufflevector v1, v2, result1_shuffle_mask
7246// result2 = shufflevector v1, v2, result2_shuffle_mask
7247// where v1/v2 and the shuffle masks have the same number of elements
7248// (here WhichResult (see below) indicates which result is being checked)
7249//
7250// or as:
7251// results = shufflevector v1, v2, shuffle_mask
7252// where both results are returned in one vector and the shuffle mask has twice
7253// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7254// want to check the low half and high half of the shuffle mask as if it were
7255// the other case
7256static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7257 unsigned EltSz = VT.getScalarSizeInBits();
7258 if (EltSz == 64)
7259 return false;
7260
7261 unsigned NumElts = VT.getVectorNumElements();
7262 if (M.size() != NumElts && M.size() != NumElts*2)
7263 return false;
7264
7265 // If the mask is twice as long as the input vector then we need to check the
7266 // upper and lower parts of the mask with a matching value for WhichResult
7267 // FIXME: A mask with only even values will be rejected in case the first
7268 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7269 // M[0] is used to determine WhichResult
7270 for (unsigned i = 0; i < M.size(); i += NumElts) {
7271 WhichResult = SelectPairHalf(NumElts, M, i);
7272 for (unsigned j = 0; j < NumElts; j += 2) {
7273 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7274 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7275 return false;
7276 }
7277 }
7278
7279 if (M.size() == NumElts*2)
7280 WhichResult = 0;
7281
7282 return true;
7283}
7284
7285/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7286/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7287/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7288static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7289 unsigned EltSz = VT.getScalarSizeInBits();
7290 if (EltSz == 64)
7291 return false;
7292
7293 unsigned NumElts = VT.getVectorNumElements();
7294 if (M.size() != NumElts && M.size() != NumElts*2)
7295 return false;
7296
7297 for (unsigned i = 0; i < M.size(); i += NumElts) {
7298 WhichResult = SelectPairHalf(NumElts, M, i);
7299 for (unsigned j = 0; j < NumElts; j += 2) {
7300 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7301 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7302 return false;
7303 }
7304 }
7305
7306 if (M.size() == NumElts*2)
7307 WhichResult = 0;
7308
7309 return true;
7310}
7311
7312// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7313// that the mask elements are either all even and in steps of size 2 or all odd
7314// and in steps of size 2.
7315// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7316// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7317// v2={e,f,g,h}
7318// Requires similar checks to that of isVTRNMask with
7319// respect the how results are returned.
7320static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7321 unsigned EltSz = VT.getScalarSizeInBits();
7322 if (EltSz == 64)
7323 return false;
7324
7325 unsigned NumElts = VT.getVectorNumElements();
7326 if (M.size() != NumElts && M.size() != NumElts*2)
7327 return false;
7328
7329 for (unsigned i = 0; i < M.size(); i += NumElts) {
7330 WhichResult = SelectPairHalf(NumElts, M, i);
7331 for (unsigned j = 0; j < NumElts; ++j) {
7332 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7333 return false;
7334 }
7335 }
7336
7337 if (M.size() == NumElts*2)
7338 WhichResult = 0;
7339
7340 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7341 if (VT.is64BitVector() && EltSz == 32)
7342 return false;
7343
7344 return true;
7345}
7346
7347/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7348/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7349/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7350static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7351 unsigned EltSz = VT.getScalarSizeInBits();
7352 if (EltSz == 64)
7353 return false;
7354
7355 unsigned NumElts = VT.getVectorNumElements();
7356 if (M.size() != NumElts && M.size() != NumElts*2)
7357 return false;
7358
7359 unsigned Half = NumElts / 2;
7360 for (unsigned i = 0; i < M.size(); i += NumElts) {
7361 WhichResult = SelectPairHalf(NumElts, M, i);
7362 for (unsigned j = 0; j < NumElts; j += Half) {
7363 unsigned Idx = WhichResult;
7364 for (unsigned k = 0; k < Half; ++k) {
7365 int MIdx = M[i + j + k];
7366 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7367 return false;
7368 Idx += 2;
7369 }
7370 }
7371 }
7372
7373 if (M.size() == NumElts*2)
7374 WhichResult = 0;
7375
7376 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7377 if (VT.is64BitVector() && EltSz == 32)
7378 return false;
7379
7380 return true;
7381}
7382
7383// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7384// that pairs of elements of the shufflemask represent the same index in each
7385// vector incrementing sequentially through the vectors.
7386// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7387// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7388// v2={e,f,g,h}
7389// Requires similar checks to that of isVTRNMask with respect the how results
7390// are returned.
7391static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7392 unsigned EltSz = VT.getScalarSizeInBits();
7393 if (EltSz == 64)
7394 return false;
7395
7396 unsigned NumElts = VT.getVectorNumElements();
7397 if (M.size() != NumElts && M.size() != NumElts*2)
7398 return false;
7399
7400 for (unsigned i = 0; i < M.size(); i += NumElts) {
7401 WhichResult = SelectPairHalf(NumElts, M, i);
7402 unsigned Idx = WhichResult * NumElts / 2;
7403 for (unsigned j = 0; j < NumElts; j += 2) {
7404 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7405 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7406 return false;
7407 Idx += 1;
7408 }
7409 }
7410
7411 if (M.size() == NumElts*2)
7412 WhichResult = 0;
7413
7414 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7415 if (VT.is64BitVector() && EltSz == 32)
7416 return false;
7417
7418 return true;
7419}
7420
7421/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7422/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7423/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7424static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7425 unsigned EltSz = VT.getScalarSizeInBits();
7426 if (EltSz == 64)
7427 return false;
7428
7429 unsigned NumElts = VT.getVectorNumElements();
7430 if (M.size() != NumElts && M.size() != NumElts*2)
7431 return false;
7432
7433 for (unsigned i = 0; i < M.size(); i += NumElts) {
7434 WhichResult = SelectPairHalf(NumElts, M, i);
7435 unsigned Idx = WhichResult * NumElts / 2;
7436 for (unsigned j = 0; j < NumElts; j += 2) {
7437 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7438 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7439 return false;
7440 Idx += 1;
7441 }
7442 }
7443
7444 if (M.size() == NumElts*2)
7445 WhichResult = 0;
7446
7447 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7448 if (VT.is64BitVector() && EltSz == 32)
7449 return false;
7450
7451 return true;
7452}
7453
7454/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7455/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7456static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7457 unsigned &WhichResult,
7458 bool &isV_UNDEF) {
7459 isV_UNDEF = false;
7460 if (isVTRNMask(ShuffleMask, VT, WhichResult))
7461 return ARMISD::VTRN;
7462 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7463 return ARMISD::VUZP;
7464 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7465 return ARMISD::VZIP;
7466
7467 isV_UNDEF = true;
7468 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7469 return ARMISD::VTRN;
7470 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7471 return ARMISD::VUZP;
7472 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7473 return ARMISD::VZIP;
7474
7475 return 0;
7476}
7477
7478/// \return true if this is a reverse operation on an vector.
7479static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7480 unsigned NumElts = VT.getVectorNumElements();
7481 // Make sure the mask has the right size.
7482 if (NumElts != M.size())
7483 return false;
7484
7485 // Look for <15, ..., 3, -1, 1, 0>.
7486 for (unsigned i = 0; i != NumElts; ++i)
7487 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7488 return false;
7489
7490 return true;
7491}
7492
7493static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7494 unsigned NumElts = VT.getVectorNumElements();
7495 // Make sure the mask has the right size.
7496 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7497 return false;
7498
7499 // If Top
7500 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7501 // This inserts Input2 into Input1
7502 // else if not Top
7503 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7504 // This inserts Input1 into Input2
7505 unsigned Offset = Top ? 0 : 1;
7506 unsigned N = SingleSource ? 0 : NumElts;
7507 for (unsigned i = 0; i < NumElts; i += 2) {
7508 if (M[i] >= 0 && M[i] != (int)i)
7509 return false;
7510 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7511 return false;
7512 }
7513
7514 return true;
7515}
7516
7517static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7518 unsigned NumElts = ToVT.getVectorNumElements();
7519 if (NumElts != M.size())
7520 return false;
7521
7522 // Test if the Trunc can be convertable to a VMOVN with this shuffle. We are
7523 // looking for patterns of:
7524 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7525 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7526
7527 unsigned Off0 = rev ? NumElts / 2 : 0;
7528 unsigned Off1 = rev ? 0 : NumElts / 2;
7529 for (unsigned i = 0; i < NumElts; i += 2) {
7530 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7531 return false;
7532 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7533 return false;
7534 }
7535
7536 return true;
7537}
7538
7539// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7540// from a pair of inputs. For example:
7541// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7542// FP_ROUND(EXTRACT_ELT(Y, 0),
7543// FP_ROUND(EXTRACT_ELT(X, 1),
7544// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7545static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7546 const ARMSubtarget *ST) {
7547 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!")(static_cast <bool> (BV.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!") ? void (0) : __assert_fail ("BV.getOpcode() == ISD::BUILD_VECTOR && \"Unknown opcode!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 7547, __extension__
__PRETTY_FUNCTION__))
;
7548 if (!ST->hasMVEFloatOps())
7549 return SDValue();
7550
7551 SDLoc dl(BV);
7552 EVT VT = BV.getValueType();
7553 if (VT != MVT::v8f16)
7554 return SDValue();
7555
7556 // We are looking for a buildvector of fptrunc elements, where all the
7557 // elements are interleavingly extracted from two sources. Check the first two
7558 // items are valid enough and extract some info from them (they are checked
7559 // properly in the loop below).
7560 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7561 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7562 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7563 return SDValue();
7564 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7565 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7566 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7567 return SDValue();
7568 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7569 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7570 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7571 return SDValue();
7572
7573 // Check all the values in the BuildVector line up with our expectations.
7574 for (unsigned i = 1; i < 4; i++) {
7575 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7576 return Trunc.getOpcode() == ISD::FP_ROUND &&
7577 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7578 Trunc.getOperand(0).getOperand(0) == Op &&
7579 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7580 };
7581 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7582 return SDValue();
7583 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7584 return SDValue();
7585 }
7586
7587 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7588 DAG.getConstant(0, dl, MVT::i32));
7589 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7590 DAG.getConstant(1, dl, MVT::i32));
7591}
7592
7593// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7594// from a single input on alternating lanes. For example:
7595// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7596// FP_ROUND(EXTRACT_ELT(X, 2),
7597// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7598static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7599 const ARMSubtarget *ST) {
7600 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!")(static_cast <bool> (BV.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!") ? void (0) : __assert_fail ("BV.getOpcode() == ISD::BUILD_VECTOR && \"Unknown opcode!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 7600, __extension__
__PRETTY_FUNCTION__))
;
7601 if (!ST->hasMVEFloatOps())
7602 return SDValue();
7603
7604 SDLoc dl(BV);
7605 EVT VT = BV.getValueType();
7606 if (VT != MVT::v4f32)
7607 return SDValue();
7608
7609 // We are looking for a buildvector of fptext elements, where all the
7610 // elements are alternating lanes from a single source. For example <0,2,4,6>
7611 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7612 // info from them (they are checked properly in the loop below).
7613 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7614 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7615 return SDValue();
7616 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7617 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7618 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7619 return SDValue();
7620
7621 // Check all the values in the BuildVector line up with our expectations.
7622 for (unsigned i = 1; i < 4; i++) {
7623 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7624 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7625 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7626 Trunc.getOperand(0).getOperand(0) == Op &&
7627 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7628 };
7629 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7630 return SDValue();
7631 }
7632
7633 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7634 DAG.getConstant(Offset, dl, MVT::i32));
7635}
7636
7637// If N is an integer constant that can be moved into a register in one
7638// instruction, return an SDValue of such a constant (will become a MOV
7639// instruction). Otherwise return null.
7640static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7641 const ARMSubtarget *ST, const SDLoc &dl) {
7642 uint64_t Val;
7643 if (!isa<ConstantSDNode>(N))
7644 return SDValue();
7645 Val = cast<ConstantSDNode>(N)->getZExtValue();
7646
7647 if (ST->isThumb1Only()) {
7648 if (Val <= 255 || ~Val <= 255)
7649 return DAG.getConstant(Val, dl, MVT::i32);
7650 } else {
7651 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7652 return DAG.getConstant(Val, dl, MVT::i32);
7653 }
7654 return SDValue();
7655}
7656
7657static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7658 const ARMSubtarget *ST) {
7659 SDLoc dl(Op);
7660 EVT VT = Op.getValueType();
7661
7662 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerBUILD_VECTOR_i1 called without MVE!") ? void (0) : __assert_fail
("ST->hasMVEIntegerOps() && \"LowerBUILD_VECTOR_i1 called without MVE!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 7662, __extension__
__PRETTY_FUNCTION__))
;
7663
7664 unsigned NumElts = VT.getVectorNumElements();
7665 unsigned BoolMask;
7666 unsigned BitsPerBool;
7667 if (NumElts == 2) {
7668 BitsPerBool = 8;
7669 BoolMask = 0xff;
7670 } else if (NumElts == 4) {
7671 BitsPerBool = 4;
7672 BoolMask = 0xf;
7673 } else if (NumElts == 8) {
7674 BitsPerBool = 2;
7675 BoolMask = 0x3;
7676 } else if (NumElts == 16) {
7677 BitsPerBool = 1;
7678 BoolMask = 0x1;
7679 } else
7680 return SDValue();
7681
7682 // If this is a single value copied into all lanes (a splat), we can just sign
7683 // extend that single value
7684 SDValue FirstOp = Op.getOperand(0);
7685 if (!isa<ConstantSDNode>(FirstOp) &&
7686 llvm::all_of(llvm::drop_begin(Op->ops()), [&FirstOp](const SDUse &U) {
7687 return U.get().isUndef() || U.get() == FirstOp;
7688 })) {
7689 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7690 DAG.getValueType(MVT::i1));
7691 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7692 }
7693
7694 // First create base with bits set where known
7695 unsigned Bits32 = 0;
7696 for (unsigned i = 0; i < NumElts; ++i) {
7697 SDValue V = Op.getOperand(i);
7698 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7699 continue;
7700 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7701 if (BitSet)
7702 Bits32 |= BoolMask << (i * BitsPerBool);
7703 }
7704
7705 // Add in unknown nodes
7706 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7707 DAG.getConstant(Bits32, dl, MVT::i32));
7708 for (unsigned i = 0; i < NumElts; ++i) {
7709 SDValue V = Op.getOperand(i);
7710 if (isa<ConstantSDNode>(V) || V.isUndef())
7711 continue;
7712 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7713 DAG.getConstant(i, dl, MVT::i32));
7714 }
7715
7716 return Base;
7717}
7718
7719static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG,
7720 const ARMSubtarget *ST) {
7721 if (!ST->hasMVEIntegerOps())
7722 return SDValue();
7723
7724 // We are looking for a buildvector where each element is Op[0] + i*N
7725 EVT VT = Op.getValueType();
7726 SDValue Op0 = Op.getOperand(0);
7727 unsigned NumElts = VT.getVectorNumElements();
7728
7729 // Get the increment value from operand 1
7730 SDValue Op1 = Op.getOperand(1);
7731 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7732 !isa<ConstantSDNode>(Op1.getOperand(1)))
7733 return SDValue();
7734 unsigned N = Op1.getConstantOperandVal(1);
7735 if (N != 1 && N != 2 && N != 4 && N != 8)
7736 return SDValue();
7737
7738 // Check that each other operand matches
7739 for (unsigned I = 2; I < NumElts; I++) {
7740 SDValue OpI = Op.getOperand(I);
7741 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7742 !isa<ConstantSDNode>(OpI.getOperand(1)) ||
7743 OpI.getConstantOperandVal(1) != I * N)
7744 return SDValue();
7745 }
7746
7747 SDLoc DL(Op);
7748 return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7749 DAG.getConstant(N, DL, MVT::i32));
7750}
7751
7752// Returns true if the operation N can be treated as qr instruction variant at
7753// operand Op.
7754static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7755 switch (N->getOpcode()) {
7756 case ISD::ADD:
7757 case ISD::MUL:
7758 case ISD::SADDSAT:
7759 case ISD::UADDSAT:
7760 return true;
7761 case ISD::SUB:
7762 case ISD::SSUBSAT:
7763 case ISD::USUBSAT:
7764 return N->getOperand(1).getNode() == Op;
7765 case ISD::INTRINSIC_WO_CHAIN:
7766 switch (N->getConstantOperandVal(0)) {
7767 case Intrinsic::arm_mve_add_predicated:
7768 case Intrinsic::arm_mve_mul_predicated:
7769 case Intrinsic::arm_mve_qadd_predicated:
7770 case Intrinsic::arm_mve_vhadd:
7771 case Intrinsic::arm_mve_hadd_predicated:
7772 case Intrinsic::arm_mve_vqdmulh:
7773 case Intrinsic::arm_mve_qdmulh_predicated:
7774 case Intrinsic::arm_mve_vqrdmulh:
7775 case Intrinsic::arm_mve_qrdmulh_predicated:
7776 case Intrinsic::arm_mve_vqdmull:
7777 case Intrinsic::arm_mve_vqdmull_predicated:
7778 return true;
7779 case Intrinsic::arm_mve_sub_predicated:
7780 case Intrinsic::arm_mve_qsub_predicated:
7781 case Intrinsic::arm_mve_vhsub:
7782 case Intrinsic::arm_mve_hsub_predicated:
7783 return N->getOperand(2).getNode() == Op;
7784 default:
7785 return false;
7786 }
7787 default:
7788 return false;
7789 }
7790}
7791
7792// If this is a case we can't handle, return null and let the default
7793// expansion code take care of it.
7794SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7795 const ARMSubtarget *ST) const {
7796 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7797 SDLoc dl(Op);
7798 EVT VT = Op.getValueType();
7799
7800 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7801 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7802
7803 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7804 return R;
7805
7806 APInt SplatBits, SplatUndef;
7807 unsigned SplatBitSize;
7808 bool HasAnyUndefs;
7809 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7810 if (SplatUndef.isAllOnes())
7811 return DAG.getUNDEF(VT);
7812
7813 // If all the users of this constant splat are qr instruction variants,
7814 // generate a vdup of the constant.
7815 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7816 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7817 all_of(BVN->uses(),
7818 [BVN](const SDNode *U) { return IsQRMVEInstruction(U, BVN); })) {
7819 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7820 : SplatBitSize == 16 ? MVT::v8i16
7821 : MVT::v16i8;
7822 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7823 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7824 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7825 }
7826
7827 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7828 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7829 // Check if an immediate VMOV works.
7830 EVT VmovVT;
7831 SDValue Val =
7832 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7833 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7834
7835 if (Val.getNode()) {
7836 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7837 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7838 }
7839
7840 // Try an immediate VMVN.
7841 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7842 Val = isVMOVModifiedImm(
7843 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7844 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7845 if (Val.getNode()) {
7846 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7847 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7848 }
7849
7850 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7851 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7852 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7853 if (ImmVal != -1) {
7854 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7855 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7856 }
7857 }
7858
7859 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7860 // type.
7861 if (ST->hasMVEIntegerOps() &&
7862 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7863 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7864 : SplatBitSize == 16 ? MVT::v8i16
7865 : MVT::v16i8;
7866 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7867 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7868 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7869 }
7870 }
7871 }
7872
7873 // Scan through the operands to see if only one value is used.
7874 //
7875 // As an optimisation, even if more than one value is used it may be more
7876 // profitable to splat with one value then change some lanes.
7877 //
7878 // Heuristically we decide to do this if the vector has a "dominant" value,
7879 // defined as splatted to more than half of the lanes.
7880 unsigned NumElts = VT.getVectorNumElements();
7881 bool isOnlyLowElement = true;
7882 bool usesOnlyOneValue = true;
7883 bool hasDominantValue = false;
7884 bool isConstant = true;
7885
7886 // Map of the number of times a particular SDValue appears in the
7887 // element list.
7888 DenseMap<SDValue, unsigned> ValueCounts;
7889 SDValue Value;
7890 for (unsigned i = 0; i < NumElts; ++i) {
7891 SDValue V = Op.getOperand(i);
7892 if (V.isUndef())
7893 continue;
7894 if (i > 0)
7895 isOnlyLowElement = false;
7896 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7897 isConstant = false;
7898
7899 ValueCounts.insert(std::make_pair(V, 0));
7900 unsigned &Count = ValueCounts[V];
7901
7902 // Is this value dominant? (takes up more than half of the lanes)
7903 if (++Count > (NumElts / 2)) {
7904 hasDominantValue = true;
7905 Value = V;
7906 }
7907 }
7908 if (ValueCounts.size() != 1)
7909 usesOnlyOneValue = false;
7910 if (!Value.getNode() && !ValueCounts.empty())
7911 Value = ValueCounts.begin()->first;
7912
7913 if (ValueCounts.empty())
7914 return DAG.getUNDEF(VT);
7915
7916 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7917 // Keep going if we are hitting this case.
7918 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7919 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7920
7921 unsigned EltSize = VT.getScalarSizeInBits();
7922
7923 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7924 // i32 and try again.
7925 if (hasDominantValue && EltSize <= 32) {
7926 if (!isConstant) {
7927 SDValue N;
7928
7929 // If we are VDUPing a value that comes directly from a vector, that will
7930 // cause an unnecessary move to and from a GPR, where instead we could
7931 // just use VDUPLANE. We can only do this if the lane being extracted
7932 // is at a constant index, as the VDUP from lane instructions only have
7933 // constant-index forms.
7934 ConstantSDNode *constIndex;
7935 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7936 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7937 // We need to create a new undef vector to use for the VDUPLANE if the
7938 // size of the vector from which we get the value is different than the
7939 // size of the vector that we need to create. We will insert the element
7940 // such that the register coalescer will remove unnecessary copies.
7941 if (VT != Value->getOperand(0).getValueType()) {
7942 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7943 VT.getVectorNumElements();
7944 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7945 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7946 Value, DAG.getConstant(index, dl, MVT::i32)),
7947 DAG.getConstant(index, dl, MVT::i32));
7948 } else
7949 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7950 Value->getOperand(0), Value->getOperand(1));
7951 } else
7952 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7953
7954 if (!usesOnlyOneValue) {
7955 // The dominant value was splatted as 'N', but we now have to insert
7956 // all differing elements.
7957 for (unsigned I = 0; I < NumElts; ++I) {
7958 if (Op.getOperand(I) == Value)
7959 continue;
7960 SmallVector<SDValue, 3> Ops;
7961 Ops.push_back(N);
7962 Ops.push_back(Op.getOperand(I));
7963 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7964 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7965 }
7966 }
7967 return N;
7968 }
7969 if (VT.getVectorElementType().isFloatingPoint()) {
7970 SmallVector<SDValue, 8> Ops;
7971 MVT FVT = VT.getVectorElementType().getSimpleVT();
7972 assert(FVT == MVT::f32 || FVT == MVT::f16)(static_cast <bool> (FVT == MVT::f32 || FVT == MVT::f16
) ? void (0) : __assert_fail ("FVT == MVT::f32 || FVT == MVT::f16"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 7972, __extension__
__PRETTY_FUNCTION__))
;
7973 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7974 for (unsigned i = 0; i < NumElts; ++i)
7975 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7976 Op.getOperand(i)));
7977 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7978 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7979 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7980 if (Val.getNode())
7981 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7982 }
7983 if (usesOnlyOneValue) {
7984 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7985 if (isConstant && Val.getNode())
7986 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7987 }
7988 }
7989
7990 // If all elements are constants and the case above didn't get hit, fall back
7991 // to the default expansion, which will generate a load from the constant
7992 // pool.
7993 if (isConstant)
7994 return SDValue();
7995
7996 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7997 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7998 // length <= 2.
7999 if (NumElts >= 4)
8000 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8001 return shuffle;
8002
8003 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
8004 // VCVT's
8005 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
8006 return VCVT;
8007 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
8008 return VCVT;
8009
8010 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
8011 // If we haven't found an efficient lowering, try splitting a 128-bit vector
8012 // into two 64-bit vectors; we might discover a better way to lower it.
8013 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
8014 EVT ExtVT = VT.getVectorElementType();
8015 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
8016 SDValue Lower =
8017 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
8018 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
8019 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
8020 SDValue Upper = DAG.getBuildVector(
8021 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
8022 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
8023 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
8024 if (Lower && Upper)
8025 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
8026 }
8027
8028 // Vectors with 32- or 64-bit elements can be built by directly assigning
8029 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
8030 // will be legalized.
8031 if (EltSize >= 32) {
8032 // Do the expansion with floating-point types, since that is what the VFP
8033 // registers are defined to use, and since i64 is not legal.
8034 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8035 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8036 SmallVector<SDValue, 8> Ops;
8037 for (unsigned i = 0; i < NumElts; ++i)
8038 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
8039 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8040 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8041 }
8042
8043 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8044 // know the default expansion would otherwise fall back on something even
8045 // worse. For a vector with one or two non-undef values, that's
8046 // scalar_to_vector for the elements followed by a shuffle (provided the
8047 // shuffle is valid for the target) and materialization element by element
8048 // on the stack followed by a load for everything else.
8049 if (!isConstant && !usesOnlyOneValue) {
8050 SDValue Vec = DAG.getUNDEF(VT);
8051 for (unsigned i = 0 ; i < NumElts; ++i) {
8052 SDValue V = Op.getOperand(i);
8053 if (V.isUndef())
8054 continue;
8055 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
8056 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8057 }
8058 return Vec;
8059 }
8060
8061 return SDValue();
8062}
8063
8064// Gather data to see if the operation can be modelled as a
8065// shuffle in combination with VEXTs.
8066SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
8067 SelectionDAG &DAG) const {
8068 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!")(static_cast <bool> (Op.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!") ? void (0) : __assert_fail ("Op.getOpcode() == ISD::BUILD_VECTOR && \"Unknown opcode!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8068, __extension__
__PRETTY_FUNCTION__))
;
8069 SDLoc dl(Op);
8070 EVT VT = Op.getValueType();
8071 unsigned NumElts = VT.getVectorNumElements();
8072
8073 struct ShuffleSourceInfo {
8074 SDValue Vec;
8075 unsigned MinElt = std::numeric_limits<unsigned>::max();
8076 unsigned MaxElt = 0;
8077
8078 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
8079 // be compatible with the shuffle we intend to construct. As a result
8080 // ShuffleVec will be some sliding window into the original Vec.
8081 SDValue ShuffleVec;
8082
8083 // Code should guarantee that element i in Vec starts at element "WindowBase
8084 // + i * WindowScale in ShuffleVec".
8085 int WindowBase = 0;
8086 int WindowScale = 1;
8087
8088 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
8089
8090 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
8091 };
8092
8093 // First gather all vectors used as an immediate source for this BUILD_VECTOR
8094 // node.
8095 SmallVector<ShuffleSourceInfo, 2> Sources;
8096 for (unsigned i = 0; i < NumElts; ++i) {
8097 SDValue V = Op.getOperand(i);
8098 if (V.isUndef())
8099 continue;
8100 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
8101 // A shuffle can only come from building a vector from various
8102 // elements of other vectors.
8103 return SDValue();
8104 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
8105 // Furthermore, shuffles require a constant mask, whereas extractelts
8106 // accept variable indices.
8107 return SDValue();
8108 }
8109
8110 // Add this element source to the list if it's not already there.
8111 SDValue SourceVec = V.getOperand(0);
8112 auto Source = llvm::find(Sources, SourceVec);
8113 if (Source == Sources.end())
8114 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
8115
8116 // Update the minimum and maximum lane number seen.
8117 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
8118 Source->MinElt = std::min(Source->MinElt, EltNo);
8119 Source->MaxElt = std::max(Source->MaxElt, EltNo);
8120 }
8121
8122 // Currently only do something sane when at most two source vectors
8123 // are involved.
8124 if (Sources.size() > 2)
8125 return SDValue();
8126
8127 // Find out the smallest element size among result and two sources, and use
8128 // it as element size to build the shuffle_vector.
8129 EVT SmallestEltTy = VT.getVectorElementType();
8130 for (auto &Source : Sources) {
8131 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
8132 if (SrcEltTy.bitsLT(SmallestEltTy))
8133 SmallestEltTy = SrcEltTy;
8134 }
8135 unsigned ResMultiplier =
8136 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
8137 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
8138 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
8139
8140 // If the source vector is too wide or too narrow, we may nevertheless be able
8141 // to construct a compatible shuffle either by concatenating it with UNDEF or
8142 // extracting a suitable range of elements.
8143 for (auto &Src : Sources) {
8144 EVT SrcVT = Src.ShuffleVec.getValueType();
8145
8146 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
8147 uint64_t VTSize = VT.getFixedSizeInBits();
8148 if (SrcVTSize == VTSize)
8149 continue;
8150
8151 // This stage of the search produces a source with the same element type as
8152 // the original, but with a total width matching the BUILD_VECTOR output.
8153 EVT EltVT = SrcVT.getVectorElementType();
8154 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8155 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8156
8157 if (SrcVTSize < VTSize) {
8158 if (2 * SrcVTSize != VTSize)
8159 return SDValue();
8160 // We can pad out the smaller vector for free, so if it's part of a
8161 // shuffle...
8162 Src.ShuffleVec =
8163 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8164 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8165 continue;
8166 }
8167
8168 if (SrcVTSize != 2 * VTSize)
8169 return SDValue();
8170
8171 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8172 // Span too large for a VEXT to cope
8173 return SDValue();
8174 }
8175
8176 if (Src.MinElt >= NumSrcElts) {
8177 // The extraction can just take the second half
8178 Src.ShuffleVec =
8179 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8180 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8181 Src.WindowBase = -NumSrcElts;
8182 } else if (Src.MaxElt < NumSrcElts) {
8183 // The extraction can just take the first half
8184 Src.ShuffleVec =
8185 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8186 DAG.getConstant(0, dl, MVT::i32));
8187 } else {
8188 // An actual VEXT is needed
8189 SDValue VEXTSrc1 =
8190 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8191 DAG.getConstant(0, dl, MVT::i32));
8192 SDValue VEXTSrc2 =
8193 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8194 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8195
8196 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
8197 VEXTSrc2,
8198 DAG.getConstant(Src.MinElt, dl, MVT::i32));
8199 Src.WindowBase = -Src.MinElt;
8200 }
8201 }
8202
8203 // Another possible incompatibility occurs from the vector element types. We
8204 // can fix this by bitcasting the source vectors to the same type we intend
8205 // for the shuffle.
8206 for (auto &Src : Sources) {
8207 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8208 if (SrcEltTy == SmallestEltTy)
8209 continue;
8210 assert(ShuffleVT.getVectorElementType() == SmallestEltTy)(static_cast <bool> (ShuffleVT.getVectorElementType() ==
SmallestEltTy) ? void (0) : __assert_fail ("ShuffleVT.getVectorElementType() == SmallestEltTy"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8210, __extension__
__PRETTY_FUNCTION__))
;
8211 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8212 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8213 Src.WindowBase *= Src.WindowScale;
8214 }
8215
8216 // Final check before we try to actually produce a shuffle.
8217 LLVM_DEBUG(for (auto Srcdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { for (auto Src : Sources) (static_cast <bool
> (Src.ShuffleVec.getValueType() == ShuffleVT) ? void (0) :
__assert_fail ("Src.ShuffleVec.getValueType() == ShuffleVT",
"llvm/lib/Target/ARM/ARMISelLowering.cpp", 8219, __extension__
__PRETTY_FUNCTION__));; } } while (false)
8218 : Sources)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { for (auto Src : Sources) (static_cast <bool
> (Src.ShuffleVec.getValueType() == ShuffleVT) ? void (0) :
__assert_fail ("Src.ShuffleVec.getValueType() == ShuffleVT",
"llvm/lib/Target/ARM/ARMISelLowering.cpp", 8219, __extension__
__PRETTY_FUNCTION__));; } } while (false)
8219 assert(Src.ShuffleVec.getValueType() == ShuffleVT);)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { for (auto Src : Sources) (static_cast <bool
> (Src.ShuffleVec.getValueType() == ShuffleVT) ? void (0) :
__assert_fail ("Src.ShuffleVec.getValueType() == ShuffleVT",
"llvm/lib/Target/ARM/ARMISelLowering.cpp", 8219, __extension__
__PRETTY_FUNCTION__));; } } while (false)
;
8220
8221 // The stars all align, our next step is to produce the mask for the shuffle.
8222 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8223 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8224 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8225 SDValue Entry = Op.getOperand(i);
8226 if (Entry.isUndef())
8227 continue;
8228
8229 auto Src = llvm::find(Sources, Entry.getOperand(0));
8230 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8231
8232 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8233 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8234 // segment.
8235 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8236 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8237 VT.getScalarSizeInBits());
8238 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8239
8240 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8241 // starting at the appropriate offset.
8242 int *LaneMask = &Mask[i * ResMultiplier];
8243
8244 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8245 ExtractBase += NumElts * (Src - Sources.begin());
8246 for (int j = 0; j < LanesDefined; ++j)
8247 LaneMask[j] = ExtractBase + j;
8248 }
8249
8250
8251 // We can't handle more than two sources. This should have already
8252 // been checked before this point.
8253 assert(Sources.size() <= 2 && "Too many sources!")(static_cast <bool> (Sources.size() <= 2 && "Too many sources!"
) ? void (0) : __assert_fail ("Sources.size() <= 2 && \"Too many sources!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8253, __extension__
__PRETTY_FUNCTION__))
;
8254
8255 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8256 for (unsigned i = 0; i < Sources.size(); ++i)
8257 ShuffleOps[i] = Sources[i].ShuffleVec;
8258
8259 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8260 ShuffleOps[1], Mask, DAG);
8261 if (!Shuffle)
8262 return SDValue();
8263 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8264}
8265
8266enum ShuffleOpCodes {
8267 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8268 OP_VREV,
8269 OP_VDUP0,
8270 OP_VDUP1,
8271 OP_VDUP2,
8272 OP_VDUP3,
8273 OP_VEXT1,
8274 OP_VEXT2,
8275 OP_VEXT3,
8276 OP_VUZPL, // VUZP, left result
8277 OP_VUZPR, // VUZP, right result
8278 OP_VZIPL, // VZIP, left result
8279 OP_VZIPR, // VZIP, right result
8280 OP_VTRNL, // VTRN, left result
8281 OP_VTRNR // VTRN, right result
8282};
8283
8284static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8285 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8286 switch (OpNum) {
8287 case OP_COPY:
8288 case OP_VREV:
8289 case OP_VDUP0:
8290 case OP_VDUP1:
8291 case OP_VDUP2:
8292 case OP_VDUP3:
8293 return true;
8294 }
8295 return false;
8296}
8297
8298/// isShuffleMaskLegal - Targets can use this to indicate that they only
8299/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8300/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8301/// are assumed to be legal.
8302bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8303 if (VT.getVectorNumElements() == 4 &&
8304 (VT.is128BitVector() || VT.is64BitVector())) {
8305 unsigned PFIndexes[4];
8306 for (unsigned i = 0; i != 4; ++i) {
8307 if (M[i] < 0)
8308 PFIndexes[i] = 8;
8309 else
8310 PFIndexes[i] = M[i];
8311 }
8312
8313 // Compute the index in the perfect shuffle table.
8314 unsigned PFTableIndex =
8315 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8316 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8317 unsigned Cost = (PFEntry >> 30);
8318
8319 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8320 return true;
8321 }
8322
8323 bool ReverseVEXT, isV_UNDEF;
8324 unsigned Imm, WhichResult;
8325
8326 unsigned EltSize = VT.getScalarSizeInBits();
8327 if (EltSize >= 32 ||
8328 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8329 ShuffleVectorInst::isIdentityMask(M) ||
8330 isVREVMask(M, VT, 64) ||
8331 isVREVMask(M, VT, 32) ||
8332 isVREVMask(M, VT, 16))
8333 return true;
8334 else if (Subtarget->hasNEON() &&
8335 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8336 isVTBLMask(M, VT) ||
8337 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
8338 return true;
8339 else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8340 isReverseMask(M, VT))
8341 return true;
8342 else if (Subtarget->hasMVEIntegerOps() &&
8343 (isVMOVNMask(M, VT, true, false) ||
8344 isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8345 return true;
8346 else
8347 return false;
8348}
8349
8350/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8351/// the specified operations to build the shuffle.
8352static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8353 SDValue RHS, SelectionDAG &DAG,
8354 const SDLoc &dl) {
8355 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8356 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8357 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8358
8359 if (OpNum == OP_COPY) {
8360 if (LHSID == (1*9+2)*9+3) return LHS;
8361 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!")(static_cast <bool> (LHSID == ((4*9+5)*9+6)*9+7 &&
"Illegal OP_COPY!") ? void (0) : __assert_fail ("LHSID == ((4*9+5)*9+6)*9+7 && \"Illegal OP_COPY!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8361, __extension__
__PRETTY_FUNCTION__))
;
8362 return RHS;
8363 }
8364
8365 SDValue OpLHS, OpRHS;
8366 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8367 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8368 EVT VT = OpLHS.getValueType();
8369
8370 switch (OpNum) {
8371 default: llvm_unreachable("Unknown shuffle opcode!")::llvm::llvm_unreachable_internal("Unknown shuffle opcode!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8371)
;
8372 case OP_VREV:
8373 // VREV divides the vector in half and swaps within the half.
8374 if (VT.getScalarSizeInBits() == 32)
8375 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8376 // vrev <4 x i16> -> VREV32
8377 if (VT.getScalarSizeInBits() == 16)
8378 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8379 // vrev <4 x i8> -> VREV16
8380 assert(VT.getScalarSizeInBits() == 8)(static_cast <bool> (VT.getScalarSizeInBits() == 8) ? void
(0) : __assert_fail ("VT.getScalarSizeInBits() == 8", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8380, __extension__ __PRETTY_FUNCTION__))
;
8381 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8382 case OP_VDUP0:
8383 case OP_VDUP1:
8384 case OP_VDUP2:
8385 case OP_VDUP3:
8386 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8387 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8388 case OP_VEXT1:
8389 case OP_VEXT2:
8390 case OP_VEXT3:
8391 return DAG.getNode(ARMISD::VEXT, dl, VT,
8392 OpLHS, OpRHS,
8393 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8394 case OP_VUZPL:
8395 case OP_VUZPR:
8396 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8397 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8398 case OP_VZIPL:
8399 case OP_VZIPR:
8400 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8401 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8402 case OP_VTRNL:
8403 case OP_VTRNR:
8404 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8405 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8406 }
8407}
8408
8409static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8410 ArrayRef<int> ShuffleMask,
8411 SelectionDAG &DAG) {
8412 // Check to see if we can use the VTBL instruction.
8413 SDValue V1 = Op.getOperand(0);
8414 SDValue V2 = Op.getOperand(1);
8415 SDLoc DL(Op);
8416
8417 SmallVector<SDValue, 8> VTBLMask;
8418 for (int I : ShuffleMask)
8419 VTBLMask.push_back(DAG.getConstant(I, DL, MVT::i32));
8420
8421 if (V2.getNode()->isUndef())
8422 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8423 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8424
8425 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8426 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8427}
8428
8429static SDValue LowerReverse_VECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
8430 SDLoc DL(Op);
8431 EVT VT = Op.getValueType();
8432
8433 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v8f16
|| VT == MVT::v16i8) && "Expect an v8i16/v16i8 type"
) ? void (0) : __assert_fail ("(VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && \"Expect an v8i16/v16i8 type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8434, __extension__
__PRETTY_FUNCTION__))
8434 "Expect an v8i16/v16i8 type")(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v8f16
|| VT == MVT::v16i8) && "Expect an v8i16/v16i8 type"
) ? void (0) : __assert_fail ("(VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && \"Expect an v8i16/v16i8 type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8434, __extension__
__PRETTY_FUNCTION__))
;
8435 SDValue OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, Op.getOperand(0));
8436 // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8437 // extract the first 8 bytes into the top double word and the last 8 bytes
8438 // into the bottom double word, through a new vector shuffle that will be
8439 // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8440 std::vector<int> NewMask;
8441 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8442 NewMask.push_back(VT.getVectorNumElements() / 2 + i);
8443 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8444 NewMask.push_back(i);
8445 return DAG.getVectorShuffle(VT, DL, OpLHS, OpLHS, NewMask);
8446}
8447
8448static EVT getVectorTyFromPredicateVector(EVT VT) {
8449 switch (VT.getSimpleVT().SimpleTy) {
8450 case MVT::v2i1:
8451 return MVT::v2f64;
8452 case MVT::v4i1:
8453 return MVT::v4i32;
8454 case MVT::v8i1:
8455 return MVT::v8i16;
8456 case MVT::v16i1:
8457 return MVT::v16i8;
8458 default:
8459 llvm_unreachable("Unexpected vector predicate type")::llvm::llvm_unreachable_internal("Unexpected vector predicate type"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8459)
;
8460 }
8461}
8462
8463static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8464 SelectionDAG &DAG) {
8465 // Converting from boolean predicates to integers involves creating a vector
8466 // of all ones or all zeroes and selecting the lanes based upon the real
8467 // predicate.
8468 SDValue AllOnes =
8469 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8470 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8471
8472 SDValue AllZeroes =
8473 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8474 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8475
8476 // Get full vector type from predicate type
8477 EVT NewVT = getVectorTyFromPredicateVector(VT);
8478
8479 SDValue RecastV1;
8480 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8481 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8482 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8483 // since we know in hardware the sizes are really the same.
8484 if (VT != MVT::v16i1)
8485 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8486 else
8487 RecastV1 = Pred;
8488
8489 // Select either all ones or zeroes depending upon the real predicate bits.
8490 SDValue PredAsVector =
8491 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8492
8493 // Recast our new predicate-as-integer v16i8 vector into something
8494 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8495 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8496}
8497
8498static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8499 const ARMSubtarget *ST) {
8500 EVT VT = Op.getValueType();
8501 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8502 ArrayRef<int> ShuffleMask = SVN->getMask();
8503
8504 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No support for vector shuffle of boolean predicates") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No support for vector shuffle of boolean predicates\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8505, __extension__
__PRETTY_FUNCTION__))
8505 "No support for vector shuffle of boolean predicates")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No support for vector shuffle of boolean predicates") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No support for vector shuffle of boolean predicates\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8505, __extension__
__PRETTY_FUNCTION__))
;
8506
8507 SDValue V1 = Op.getOperand(0);
8508 SDLoc dl(Op);
8509 if (isReverseMask(ShuffleMask, VT)) {
8510 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8511 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8512 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8513 DAG.getConstant(16, dl, MVT::i32));
8514 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8515 }
8516
8517 // Until we can come up with optimised cases for every single vector
8518 // shuffle in existence we have chosen the least painful strategy. This is
8519 // to essentially promote the boolean predicate to a 8-bit integer, where
8520 // each predicate represents a byte. Then we fall back on a normal integer
8521 // vector shuffle and convert the result back into a predicate vector. In
8522 // many cases the generated code might be even better than scalar code
8523 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8524 // fields in a register into 8 other arbitrary 2-bit fields!
8525 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
8526 EVT NewVT = PredAsVector.getValueType();
8527
8528 // Do the shuffle!
8529 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
8530 DAG.getUNDEF(NewVT), ShuffleMask);
8531
8532 // Now return the result of comparing the shuffled vector with zero,
8533 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8534 // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8535 if (VT == MVT::v2i1) {
8536 SDValue BC = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Shuffled);
8537 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, BC,
8538 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8539 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
8540 }
8541 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8542 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8543}
8544
8545static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8546 ArrayRef<int> ShuffleMask,
8547 SelectionDAG &DAG) {
8548 // Attempt to lower the vector shuffle using as many whole register movs as
8549 // possible. This is useful for types smaller than 32bits, which would
8550 // often otherwise become a series for grp movs.
8551 SDLoc dl(Op);
8552 EVT VT = Op.getValueType();
8553 if (VT.getScalarSizeInBits() >= 32)
8554 return SDValue();
8555
8556 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v8f16
|| VT == MVT::v16i8) && "Unexpected vector type") ? void
(0) : __assert_fail ("(VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8557, __extension__
__PRETTY_FUNCTION__))
8557 "Unexpected vector type")(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v8f16
|| VT == MVT::v16i8) && "Unexpected vector type") ? void
(0) : __assert_fail ("(VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8557, __extension__
__PRETTY_FUNCTION__))
;
8558 int NumElts = VT.getVectorNumElements();
8559 int QuarterSize = NumElts / 4;
8560 // The four final parts of the vector, as i32's
8561 SDValue Parts[4];
8562
8563 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8564 // <u,u,u,u>), returning the vmov lane index
8565 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8566 // Detect which mov lane this would be from the first non-undef element.
8567 int MovIdx = -1;
8568 for (int i = 0; i < Length; i++) {
8569 if (ShuffleMask[Start + i] >= 0) {
8570 if (ShuffleMask[Start + i] % Length != i)
8571 return -1;
8572 MovIdx = ShuffleMask[Start + i] / Length;
8573 break;
8574 }
8575 }
8576 // If all items are undef, leave this for other combines
8577 if (MovIdx == -1)
8578 return -1;
8579 // Check the remaining values are the correct part of the same mov
8580 for (int i = 1; i < Length; i++) {
8581 if (ShuffleMask[Start + i] >= 0 &&
8582 (ShuffleMask[Start + i] / Length != MovIdx ||
8583 ShuffleMask[Start + i] % Length != i))
8584 return -1;
8585 }
8586 return MovIdx;
8587 };
8588
8589 for (int Part = 0; Part < 4; ++Part) {
8590 // Does this part look like a mov
8591 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8592 if (Elt != -1) {
8593 SDValue Input = Op->getOperand(0);
8594 if (Elt >= 4) {
8595 Input = Op->getOperand(1);
8596 Elt -= 4;
8597 }
8598 SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8599 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8600 DAG.getConstant(Elt, dl, MVT::i32));
8601 }
8602 }
8603
8604 // Nothing interesting found, just return
8605 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8606 return SDValue();
8607
8608 // The other parts need to be built with the old shuffle vector, cast to a
8609 // v4i32 and extract_vector_elts
8610 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8611 SmallVector<int, 16> NewShuffleMask;
8612 for (int Part = 0; Part < 4; ++Part)
8613 for (int i = 0; i < QuarterSize; i++)
8614 NewShuffleMask.push_back(
8615 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8616 SDValue NewShuffle = DAG.getVectorShuffle(
8617 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8618 SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8619
8620 for (int Part = 0; Part < 4; ++Part)
8621 if (!Parts[Part])
8622 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8623 BitCast, DAG.getConstant(Part, dl, MVT::i32));
8624 }
8625 // Build a vector out of the various parts and bitcast it back to the original
8626 // type.
8627 SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8628 return DAG.getBitcast(VT, NewVec);
8629}
8630
8631static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,
8632 ArrayRef<int> ShuffleMask,
8633 SelectionDAG &DAG) {
8634 SDValue V1 = Op.getOperand(0);
8635 SDValue V2 = Op.getOperand(1);
8636 EVT VT = Op.getValueType();
8637 unsigned NumElts = VT.getVectorNumElements();
8638
8639 // An One-Off Identity mask is one that is mostly an identity mask from as
8640 // single source but contains a single element out-of-place, either from a
8641 // different vector or from another position in the same vector. As opposed to
8642 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8643 // pair directly.
8644 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8645 int &OffElement) {
8646 OffElement = -1;
8647 int NonUndef = 0;
8648 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8649 if (Mask[i] == -1)
8650 continue;
8651 NonUndef++;
8652 if (Mask[i] != i + BaseOffset) {
8653 if (OffElement == -1)
8654 OffElement = i;
8655 else
8656 return false;
8657 }
8658 }
8659 return NonUndef > 2 && OffElement != -1;
8660 };
8661 int OffElement;
8662 SDValue VInput;
8663 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8664 VInput = V1;
8665 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8666 VInput = V2;
8667 else
8668 return SDValue();
8669
8670 SDLoc dl(Op);
8671 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8672 ? MVT::i32
8673 : VT.getScalarType();
8674 SDValue Elt = DAG.getNode(
8675 ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8676 ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8677 DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8678 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8679 DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8680}
8681
8682static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8683 const ARMSubtarget *ST) {
8684 SDValue V1 = Op.getOperand(0);
8685 SDValue V2 = Op.getOperand(1);
8686 SDLoc dl(Op);
8687 EVT VT = Op.getValueType();
8688 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8689 unsigned EltSize = VT.getScalarSizeInBits();
8690
8691 if (ST->hasMVEIntegerOps() && EltSize == 1)
8692 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8693
8694 // Convert shuffles that are directly supported on NEON to target-specific
8695 // DAG nodes, instead of keeping them as shuffles and matching them again
8696 // during code selection. This is more efficient and avoids the possibility
8697 // of inconsistencies between legalization and selection.
8698 // FIXME: floating-point vectors should be canonicalized to integer vectors
8699 // of the same time so that they get CSEd properly.
8700 ArrayRef<int> ShuffleMask = SVN->getMask();
8701
8702 if (EltSize <= 32) {
8703 if (SVN->isSplat()) {
8704 int Lane = SVN->getSplatIndex();
8705 // If this is undef splat, generate it via "just" vdup, if possible.
8706 if (Lane == -1) Lane = 0;
8707
8708 // Test if V1 is a SCALAR_TO_VECTOR.
8709 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8710 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8711 }
8712 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8713 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8714 // reaches it).
8715 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8716 !isa<ConstantSDNode>(V1.getOperand(0))) {
8717 bool IsScalarToVector = true;
8718 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8719 if (!V1.getOperand(i).isUndef()) {
8720 IsScalarToVector = false;
8721 break;
8722 }
8723 if (IsScalarToVector)
8724 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8725 }
8726 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8727 DAG.getConstant(Lane, dl, MVT::i32));
8728 }
8729
8730 bool ReverseVEXT = false;
8731 unsigned Imm = 0;
8732 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8733 if (ReverseVEXT)
8734 std::swap(V1, V2);
8735 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8736 DAG.getConstant(Imm, dl, MVT::i32));
8737 }
8738
8739 if (isVREVMask(ShuffleMask, VT, 64))
8740 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8741 if (isVREVMask(ShuffleMask, VT, 32))
8742 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8743 if (isVREVMask(ShuffleMask, VT, 16))
8744 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8745
8746 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8747 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8748 DAG.getConstant(Imm, dl, MVT::i32));
8749 }
8750
8751 // Check for Neon shuffles that modify both input vectors in place.
8752 // If both results are used, i.e., if there are two shuffles with the same
8753 // source operands and with masks corresponding to both results of one of
8754 // these operations, DAG memoization will ensure that a single node is
8755 // used for both shuffles.
8756 unsigned WhichResult = 0;
8757 bool isV_UNDEF = false;
8758 if (ST->hasNEON()) {
8759 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8760 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8761 if (isV_UNDEF)
8762 V2 = V1;
8763 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8764 .getValue(WhichResult);
8765 }
8766 }
8767 if (ST->hasMVEIntegerOps()) {
8768 if (isVMOVNMask(ShuffleMask, VT, false, false))
8769 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8770 DAG.getConstant(0, dl, MVT::i32));
8771 if (isVMOVNMask(ShuffleMask, VT, true, false))
8772 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8773 DAG.getConstant(1, dl, MVT::i32));
8774 if (isVMOVNMask(ShuffleMask, VT, true, true))
8775 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8776 DAG.getConstant(1, dl, MVT::i32));
8777 }
8778
8779 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8780 // shuffles that produce a result larger than their operands with:
8781 // shuffle(concat(v1, undef), concat(v2, undef))
8782 // ->
8783 // shuffle(concat(v1, v2), undef)
8784 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8785 //
8786 // This is useful in the general case, but there are special cases where
8787 // native shuffles produce larger results: the two-result ops.
8788 //
8789 // Look through the concat when lowering them:
8790 // shuffle(concat(v1, v2), undef)
8791 // ->
8792 // concat(VZIP(v1, v2):0, :1)
8793 //
8794 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8795 SDValue SubV1 = V1->getOperand(0);
8796 SDValue SubV2 = V1->getOperand(1);
8797 EVT SubVT = SubV1.getValueType();
8798
8799 // We expect these to have been canonicalized to -1.
8800 assert(llvm::all_of(ShuffleMask, [&](int i) {(static_cast <bool> (llvm::all_of(ShuffleMask, [&](
int i) { return i < (int)VT.getVectorNumElements(); }) &&
"Unexpected shuffle index into UNDEF operand!") ? void (0) :
__assert_fail ("llvm::all_of(ShuffleMask, [&](int i) { return i < (int)VT.getVectorNumElements(); }) && \"Unexpected shuffle index into UNDEF operand!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8802, __extension__
__PRETTY_FUNCTION__))
8801 return i < (int)VT.getVectorNumElements();(static_cast <bool> (llvm::all_of(ShuffleMask, [&](
int i) { return i < (int)VT.getVectorNumElements(); }) &&
"Unexpected shuffle index into UNDEF operand!") ? void (0) :
__assert_fail ("llvm::all_of(ShuffleMask, [&](int i) { return i < (int)VT.getVectorNumElements(); }) && \"Unexpected shuffle index into UNDEF operand!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8802, __extension__
__PRETTY_FUNCTION__))
8802 }) && "Unexpected shuffle index into UNDEF operand!")(static_cast <bool> (llvm::all_of(ShuffleMask, [&](
int i) { return i < (int)VT.getVectorNumElements(); }) &&
"Unexpected shuffle index into UNDEF operand!") ? void (0) :
__assert_fail ("llvm::all_of(ShuffleMask, [&](int i) { return i < (int)VT.getVectorNumElements(); }) && \"Unexpected shuffle index into UNDEF operand!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8802, __extension__
__PRETTY_FUNCTION__))
;
8803
8804 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8805 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8806 if (isV_UNDEF)
8807 SubV2 = SubV1;
8808 assert((WhichResult == 0) &&(static_cast <bool> ((WhichResult == 0) && "In-place shuffle of concat can only have one result!"
) ? void (0) : __assert_fail ("(WhichResult == 0) && \"In-place shuffle of concat can only have one result!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8809, __extension__
__PRETTY_FUNCTION__))
8809 "In-place shuffle of concat can only have one result!")(static_cast <bool> ((WhichResult == 0) && "In-place shuffle of concat can only have one result!"
) ? void (0) : __assert_fail ("(WhichResult == 0) && \"In-place shuffle of concat can only have one result!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8809, __extension__
__PRETTY_FUNCTION__))
;
8810 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8811 SubV1, SubV2);
8812 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8813 Res.getValue(1));
8814 }
8815 }
8816 }
8817
8818 if (ST->hasMVEIntegerOps() && EltSize <= 32)
8819 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8820 return V;
8821
8822 // If the shuffle is not directly supported and it has 4 elements, use
8823 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8824 unsigned NumElts = VT.getVectorNumElements();
8825 if (NumElts == 4) {
8826 unsigned PFIndexes[4];
8827 for (unsigned i = 0; i != 4; ++i) {
8828 if (ShuffleMask[i] < 0)
8829 PFIndexes[i] = 8;
8830 else
8831 PFIndexes[i] = ShuffleMask[i];
8832 }
8833
8834 // Compute the index in the perfect shuffle table.
8835 unsigned PFTableIndex =
8836 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8837 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8838 unsigned Cost = (PFEntry >> 30);
8839
8840 if (Cost <= 4) {
8841 if (ST->hasNEON())
8842 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8843 else if (isLegalMVEShuffleOp(PFEntry)) {
8844 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8845 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8846 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8847 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8848 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8849 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8850 }
8851 }
8852 }
8853
8854 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8855 if (EltSize >= 32) {
8856 // Do the expansion with floating-point types, since that is what the VFP
8857 // registers are defined to use, and since i64 is not legal.
8858 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8859 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8860 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8861 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8862 SmallVector<SDValue, 8> Ops;
8863 for (unsigned i = 0; i < NumElts; ++i) {
8864 if (ShuffleMask[i] < 0)
8865 Ops.push_back(DAG.getUNDEF(EltVT));
8866 else
8867 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8868 ShuffleMask[i] < (int)NumElts ? V1 : V2,
8869 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8870 dl, MVT::i32)));
8871 }
8872 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8873 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8874 }
8875
8876 if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8877 isReverseMask(ShuffleMask, VT))
8878 return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
8879
8880 if (ST->hasNEON() && VT == MVT::v8i8)
8881 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8882 return NewOp;
8883
8884 if (ST->hasMVEIntegerOps())
8885 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8886 return NewOp;
8887
8888 return SDValue();
8889}
8890
8891static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8892 const ARMSubtarget *ST) {
8893 EVT VecVT = Op.getOperand(0).getValueType();
8894 SDLoc dl(Op);
8895
8896 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8897, __extension__
__PRETTY_FUNCTION__))
8897 "LowerINSERT_VECTOR_ELT_i1 called without MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8897, __extension__
__PRETTY_FUNCTION__))
;
8898
8899 SDValue Conv =
8900 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8901 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8902 unsigned LaneWidth =
8903 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8904 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8905 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8906 Op.getOperand(1), DAG.getValueType(MVT::i1));
8907 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8908 DAG.getConstant(~Mask, dl, MVT::i32));
8909 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8910}
8911
8912SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8913 SelectionDAG &DAG) const {
8914 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8915 SDValue Lane = Op.getOperand(2);
8916 if (!isa<ConstantSDNode>(Lane))
8917 return SDValue();
8918
8919 SDValue Elt = Op.getOperand(1);
8920 EVT EltVT = Elt.getValueType();
8921
8922 if (Subtarget->hasMVEIntegerOps() &&
8923 Op.getValueType().getScalarSizeInBits() == 1)
8924 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8925
8926 if (getTypeAction(*DAG.getContext(), EltVT) ==
8927 TargetLowering::TypePromoteFloat) {
8928 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8929 // but the type system will try to do that if we don't intervene.
8930 // Reinterpret any such vector-element insertion as one with the
8931 // corresponding integer types.
8932
8933 SDLoc dl(Op);
8934
8935 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8936 assert(getTypeAction(*DAG.getContext(), IEltVT) !=(static_cast <bool> (getTypeAction(*DAG.getContext(), IEltVT
) != TargetLowering::TypePromoteFloat) ? void (0) : __assert_fail
("getTypeAction(*DAG.getContext(), IEltVT) != TargetLowering::TypePromoteFloat"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8937, __extension__
__PRETTY_FUNCTION__))
8937 TargetLowering::TypePromoteFloat)(static_cast <bool> (getTypeAction(*DAG.getContext(), IEltVT
) != TargetLowering::TypePromoteFloat) ? void (0) : __assert_fail
("getTypeAction(*DAG.getContext(), IEltVT) != TargetLowering::TypePromoteFloat"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8937, __extension__
__PRETTY_FUNCTION__))
;
8938
8939 SDValue VecIn = Op.getOperand(0);
8940 EVT VecVT = VecIn.getValueType();
8941 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8942 VecVT.getVectorNumElements());
8943
8944 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8945 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8946 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8947 IVecIn, IElt, Lane);
8948 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8949 }
8950
8951 return Op;
8952}
8953
8954static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8955 const ARMSubtarget *ST) {
8956 EVT VecVT = Op.getOperand(0).getValueType();
8957 SDLoc dl(Op);
8958
8959 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8960, __extension__
__PRETTY_FUNCTION__))
8960 "LowerINSERT_VECTOR_ELT_i1 called without MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8960, __extension__
__PRETTY_FUNCTION__))
;
8961
8962 SDValue Conv =
8963 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8964 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8965 unsigned LaneWidth =
8966 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8967 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8968 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8969 return Shift;
8970}
8971
8972static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8973 const ARMSubtarget *ST) {
8974 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8975 SDValue Lane = Op.getOperand(1);
8976 if (!isa<ConstantSDNode>(Lane))
8977 return SDValue();
8978
8979 SDValue Vec = Op.getOperand(0);
8980 EVT VT = Vec.getValueType();
8981
8982 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8983 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8984
8985 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8986 SDLoc dl(Op);
8987 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8988 }
8989
8990 return Op;
8991}
8992
8993static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8994 const ARMSubtarget *ST) {
8995 SDLoc dl(Op);
8996 assert(Op.getValueType().getScalarSizeInBits() == 1 &&(static_cast <bool> (Op.getValueType().getScalarSizeInBits
() == 1 && "Unexpected custom CONCAT_VECTORS lowering"
) ? void (0) : __assert_fail ("Op.getValueType().getScalarSizeInBits() == 1 && \"Unexpected custom CONCAT_VECTORS lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8997, __extension__
__PRETTY_FUNCTION__))
8997 "Unexpected custom CONCAT_VECTORS lowering")(static_cast <bool> (Op.getValueType().getScalarSizeInBits
() == 1 && "Unexpected custom CONCAT_VECTORS lowering"
) ? void (0) : __assert_fail ("Op.getValueType().getScalarSizeInBits() == 1 && \"Unexpected custom CONCAT_VECTORS lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8997, __extension__
__PRETTY_FUNCTION__))
;
8998 assert(isPowerOf2_32(Op.getNumOperands()) &&(static_cast <bool> (isPowerOf2_32(Op.getNumOperands())
&& "Unexpected custom CONCAT_VECTORS lowering") ? void
(0) : __assert_fail ("isPowerOf2_32(Op.getNumOperands()) && \"Unexpected custom CONCAT_VECTORS lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8999, __extension__
__PRETTY_FUNCTION__))
8999 "Unexpected custom CONCAT_VECTORS lowering")(static_cast <bool> (isPowerOf2_32(Op.getNumOperands())
&& "Unexpected custom CONCAT_VECTORS lowering") ? void
(0) : __assert_fail ("isPowerOf2_32(Op.getNumOperands()) && \"Unexpected custom CONCAT_VECTORS lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 8999, __extension__
__PRETTY_FUNCTION__))
;
9000 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"CONCAT_VECTORS lowering only supported for MVE") ? void (0)
: __assert_fail ("ST->hasMVEIntegerOps() && \"CONCAT_VECTORS lowering only supported for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9001, __extension__
__PRETTY_FUNCTION__))
9001 "CONCAT_VECTORS lowering only supported for MVE")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"CONCAT_VECTORS lowering only supported for MVE") ? void (0)
: __assert_fail ("ST->hasMVEIntegerOps() && \"CONCAT_VECTORS lowering only supported for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9001, __extension__
__PRETTY_FUNCTION__))
;
9002
9003 auto ConcatPair = [&](SDValue V1, SDValue V2) {
9004 EVT Op1VT = V1.getValueType();
9005 EVT Op2VT = V2.getValueType();
9006 assert(Op1VT == Op2VT && "Operand types don't match!")(static_cast <bool> (Op1VT == Op2VT && "Operand types don't match!"
) ? void (0) : __assert_fail ("Op1VT == Op2VT && \"Operand types don't match!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9006, __extension__
__PRETTY_FUNCTION__))
;
9007 EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
9008
9009 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
9010 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
9011
9012 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
9013 // promoted to v8i16, etc.
9014 MVT ElType =
9015 getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
9016 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
9017
9018 // Extract the vector elements from Op1 and Op2 one by one and truncate them
9019 // to be the right size for the destination. For example, if Op1 is v4i1
9020 // then the promoted vector is v4i32. The result of concatenation gives a
9021 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
9022 // needs truncating to i16 and inserting in the result.
9023 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
9024 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
9025 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
9026 EVT NewVT = NewV.getValueType();
9027 EVT ConcatVT = ConVec.getValueType();
9028 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
9029 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
9030 DAG.getIntPtrConstant(i, dl));
9031 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
9032 DAG.getConstant(j, dl, MVT::i32));
9033 }
9034 return ConVec;
9035 };
9036 unsigned j = 0;
9037 ConVec = ExtractInto(NewV1, ConVec, j);
9038 ConVec = ExtractInto(NewV2, ConVec, j);
9039
9040 // Now return the result of comparing the subvector with zero, which will
9041 // generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1 we
9042 // convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
9043 if (VT == MVT::v2i1) {
9044 SDValue BC = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, ConVec);
9045 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, BC,
9046 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9047 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
9048 }
9049 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
9050 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9051 };
9052
9053 // Concat each pair of subvectors and pack into the lower half of the array.
9054 SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
9055 while (ConcatOps.size() > 1) {
9056 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
9057 SDValue V1 = ConcatOps[I];
9058 SDValue V2 = ConcatOps[I + 1];
9059 ConcatOps[I / 2] = ConcatPair(V1, V2);
9060 }
9061 ConcatOps.resize(ConcatOps.size() / 2);
9062 }
9063 return ConcatOps[0];
9064}
9065
9066static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
9067 const ARMSubtarget *ST) {
9068 EVT VT = Op->getValueType(0);
9069 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
9070 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
9071
9072 // The only time a CONCAT_VECTORS operation can have legal types is when
9073 // two 64-bit vectors are concatenated to a 128-bit vector.
9074 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&(static_cast <bool> (Op.getValueType().is128BitVector()
&& Op.getNumOperands() == 2 && "unexpected CONCAT_VECTORS"
) ? void (0) : __assert_fail ("Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && \"unexpected CONCAT_VECTORS\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9075, __extension__
__PRETTY_FUNCTION__))
9075 "unexpected CONCAT_VECTORS")(static_cast <bool> (Op.getValueType().is128BitVector()
&& Op.getNumOperands() == 2 && "unexpected CONCAT_VECTORS"
) ? void (0) : __assert_fail ("Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && \"unexpected CONCAT_VECTORS\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9075, __extension__
__PRETTY_FUNCTION__))
;
9076 SDLoc dl(Op);
9077 SDValue Val = DAG.getUNDEF(MVT::v2f64);
9078 SDValue Op0 = Op.getOperand(0);
9079 SDValue Op1 = Op.getOperand(1);
9080 if (!Op0.isUndef())
9081 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
9082 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
9083 DAG.getIntPtrConstant(0, dl));
9084 if (!Op1.isUndef())
9085 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
9086 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
9087 DAG.getIntPtrConstant(1, dl));
9088 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
9089}
9090
9091static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
9092 const ARMSubtarget *ST) {
9093 SDValue V1 = Op.getOperand(0);
9094 SDValue V2 = Op.getOperand(1);
9095 SDLoc dl(Op);
9096 EVT VT = Op.getValueType();
9097 EVT Op1VT = V1.getValueType();
9098 unsigned NumElts = VT.getVectorNumElements();
9099 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
9100
9101 assert(VT.getScalarSizeInBits() == 1 &&(static_cast <bool> (VT.getScalarSizeInBits() == 1 &&
"Unexpected custom EXTRACT_SUBVECTOR lowering") ? void (0) :
__assert_fail ("VT.getScalarSizeInBits() == 1 && \"Unexpected custom EXTRACT_SUBVECTOR lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9102, __extension__
__PRETTY_FUNCTION__))
9102 "Unexpected custom EXTRACT_SUBVECTOR lowering")(static_cast <bool> (VT.getScalarSizeInBits() == 1 &&
"Unexpected custom EXTRACT_SUBVECTOR lowering") ? void (0) :
__assert_fail ("VT.getScalarSizeInBits() == 1 && \"Unexpected custom EXTRACT_SUBVECTOR lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9102, __extension__
__PRETTY_FUNCTION__))
;
9103 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"EXTRACT_SUBVECTOR lowering only supported for MVE") ? void (
0) : __assert_fail ("ST->hasMVEIntegerOps() && \"EXTRACT_SUBVECTOR lowering only supported for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9104, __extension__
__PRETTY_FUNCTION__))
9104 "EXTRACT_SUBVECTOR lowering only supported for MVE")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"EXTRACT_SUBVECTOR lowering only supported for MVE") ? void (
0) : __assert_fail ("ST->hasMVEIntegerOps() && \"EXTRACT_SUBVECTOR lowering only supported for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9104, __extension__
__PRETTY_FUNCTION__))
;
9105
9106 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
9107
9108 // We now have Op1 promoted to a vector of integers, where v8i1 gets
9109 // promoted to v8i16, etc.
9110
9111 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
9112
9113 if (NumElts == 2) {
9114 EVT SubVT = MVT::v4i32;
9115 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9116 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
9117 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9118 DAG.getIntPtrConstant(i, dl));
9119 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9120 DAG.getConstant(j, dl, MVT::i32));
9121 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9122 DAG.getConstant(j + 1, dl, MVT::i32));
9123 }
9124 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, SubVec,
9125 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9126 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
9127 }
9128
9129 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
9130 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9131 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
9132 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9133 DAG.getIntPtrConstant(i, dl));
9134 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9135 DAG.getConstant(j, dl, MVT::i32));
9136 }
9137
9138 // Now return the result of comparing the subvector with zero,
9139 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9140 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
9141 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9142}
9143
9144// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
9145static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG,
9146 const ARMSubtarget *ST) {
9147 assert(ST->hasMVEIntegerOps() && "Expected MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"Expected MVE!") ? void (0) : __assert_fail ("ST->hasMVEIntegerOps() && \"Expected MVE!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9147, __extension__
__PRETTY_FUNCTION__))
;
9148 EVT VT = N->getValueType(0);
9149 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&(static_cast <bool> ((VT == MVT::v16i1 || VT == MVT::v8i1
|| VT == MVT::v4i1) && "Expected a vector i1 type!")
? void (0) : __assert_fail ("(VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) && \"Expected a vector i1 type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9150, __extension__
__PRETTY_FUNCTION__))
9150 "Expected a vector i1 type!")(static_cast <bool> ((VT == MVT::v16i1 || VT == MVT::v8i1
|| VT == MVT::v4i1) && "Expected a vector i1 type!")
? void (0) : __assert_fail ("(VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) && \"Expected a vector i1 type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9150, __extension__
__PRETTY_FUNCTION__))
;
9151 SDValue Op = N->getOperand(0);
9152 EVT FromVT = Op.getValueType();
9153 SDLoc DL(N);
9154
9155 SDValue And =
9156 DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
9157 return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
9158 DAG.getCondCode(ISD::SETNE));
9159}
9160
9161static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG,
9162 const ARMSubtarget *Subtarget) {
9163 if (!Subtarget->hasMVEIntegerOps())
9164 return SDValue();
9165
9166 EVT ToVT = N->getValueType(0);
9167 if (ToVT.getScalarType() == MVT::i1)
9168 return LowerTruncatei1(N, DAG, Subtarget);
9169
9170 // MVE does not have a single instruction to perform the truncation of a v4i32
9171 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9172 // Most of the instructions in MVE follow the 'Beats' system, where moving
9173 // values from different lanes is usually something that the instructions
9174 // avoid.
9175 //
9176 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9177 // which take a the top/bottom half of a larger lane and extend it (or do the
9178 // opposite, truncating into the top/bottom lane from a larger lane). Note
9179 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9180 // bottom 16bits from each vector lane. This works really well with T/B
9181 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9182 // to move order.
9183 //
9184 // But truncates and sext/zext are always going to be fairly common from llvm.
9185 // We have several options for how to deal with them:
9186 // - Wherever possible combine them into an instruction that makes them
9187 // "free". This includes loads/stores, which can perform the trunc as part
9188 // of the memory operation. Or certain shuffles that can be turned into
9189 // VMOVN/VMOVL.
9190 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9191 // trunc(mul(sext(a), sext(b))) may become
9192 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9193 // this case can use VMULL). This is performed in the
9194 // MVELaneInterleavingPass.
9195 // - Otherwise we have an option. By default we would expand the
9196 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9197 // registers. One for each vector lane in the vector. This can obviously be
9198 // very expensive.
9199 // - The other option is to use the fact that loads/store can extend/truncate
9200 // to turn a trunc into two truncating stack stores and a stack reload. This
9201 // becomes 3 back-to-back memory operations, but at least that is less than
9202 // all the insert/extracts.
9203 //
9204 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9205 // are either optimized where they can be, or eventually lowered into stack
9206 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9207 // two early, where other instructions would be better, and stops us from
9208 // having to reconstruct multiple buildvector shuffles into loads/stores.
9209 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9210 return SDValue();
9211 EVT FromVT = N->getOperand(0).getValueType();
9212 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9213 return SDValue();
9214
9215 SDValue Lo, Hi;
9216 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9217 SDLoc DL(N);
9218 return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9219}
9220
9221static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG,
9222 const ARMSubtarget *Subtarget) {
9223 if (!Subtarget->hasMVEIntegerOps())
9224 return SDValue();
9225
9226 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9227
9228 EVT ToVT = N->getValueType(0);
9229 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9230 return SDValue();
9231 SDValue Op = N->getOperand(0);
9232 EVT FromVT = Op.getValueType();
9233 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9234 return SDValue();
9235
9236 SDLoc DL(N);
9237 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9238 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9239 ExtVT = MVT::v8i16;
9240
9241 unsigned Opcode =
9242 N->getOpcode() == ISD::SIGN_EXTEND ? ARMISD::MVESEXT : ARMISD::MVEZEXT;
9243 SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9244 SDValue Ext1 = Ext.getValue(1);
9245
9246 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9247 Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9248 Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9249 }
9250
9251 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9252}
9253
9254/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9255/// element has been zero/sign-extended, depending on the isSigned parameter,
9256/// from an integer type half its size.
9257static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
9258 bool isSigned) {
9259 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9260 EVT VT = N->getValueType(0);
9261 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9262 SDNode *BVN = N->getOperand(0).getNode();
9263 if (BVN->getValueType(0) != MVT::v4i32 ||
9264 BVN->getOpcode() != ISD::BUILD_VECTOR)
9265 return false;
9266 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9267 unsigned HiElt = 1 - LoElt;
9268 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
9269 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
9270 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
9271 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
9272 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9273 return false;
9274 if (isSigned) {
9275 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9276 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9277 return true;
9278 } else {
9279 if (Hi0->isZero() && Hi1->isZero())
9280 return true;
9281 }
9282 return false;
9283 }
9284
9285 if (N->getOpcode() != ISD::BUILD_VECTOR)
9286 return false;
9287
9288 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9289 SDNode *Elt = N->getOperand(i).getNode();
9290 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
9291 unsigned EltSize = VT.getScalarSizeInBits();
9292 unsigned HalfSize = EltSize / 2;
9293 if (isSigned) {
9294 if (!isIntN(HalfSize, C->getSExtValue()))
9295 return false;
9296 } else {
9297 if (!isUIntN(HalfSize, C->getZExtValue()))
9298 return false;
9299 }
9300 continue;
9301 }
9302 return false;
9303 }
9304
9305 return true;
9306}
9307
9308/// isSignExtended - Check if a node is a vector value that is sign-extended
9309/// or a constant BUILD_VECTOR with sign-extended elements.
9310static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
9311 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9312 return true;
9313 if (isExtendedBUILD_VECTOR(N, DAG, true))
9314 return true;
9315 return false;
9316}
9317
9318/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9319/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9320static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
9321 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9322 ISD::isZEXTLoad(N))
9323 return true;
9324 if (isExtendedBUILD_VECTOR(N, DAG, false))
9325 return true;
9326 return false;
9327}
9328
9329static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9330 if (OrigVT.getSizeInBits() >= 64)
9331 return OrigVT;
9332
9333 assert(OrigVT.isSimple() && "Expecting a simple value type")(static_cast <bool> (OrigVT.isSimple() && "Expecting a simple value type"
) ? void (0) : __assert_fail ("OrigVT.isSimple() && \"Expecting a simple value type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9333, __extension__
__PRETTY_FUNCTION__))
;
9334
9335 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9336 switch (OrigSimpleTy) {
9337 default: llvm_unreachable("Unexpected Vector Type")::llvm::llvm_unreachable_internal("Unexpected Vector Type", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9337)
;
9338 case MVT::v2i8:
9339 case MVT::v2i16:
9340 return MVT::v2i32;
9341 case MVT::v4i8:
9342 return MVT::v4i16;
9343 }
9344}
9345
9346/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9347/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9348/// We insert the required extension here to get the vector to fill a D register.
9349static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
9350 const EVT &OrigTy,
9351 const EVT &ExtTy,
9352 unsigned ExtOpcode) {
9353 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9354 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9355 // 64-bits we need to insert a new extension so that it will be 64-bits.
9356 assert(ExtTy.is128BitVector() && "Unexpected extension size")(static_cast <bool> (ExtTy.is128BitVector() && "Unexpected extension size"
) ? void (0) : __assert_fail ("ExtTy.is128BitVector() && \"Unexpected extension size\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9356, __extension__
__PRETTY_FUNCTION__))
;
9357 if (OrigTy.getSizeInBits() >= 64)
9358 return N;
9359
9360 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9361 EVT NewVT = getExtensionTo64Bits(OrigTy);
9362
9363 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9364}
9365
9366/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9367/// does not do any sign/zero extension. If the original vector is less
9368/// than 64 bits, an appropriate extension will be added after the load to
9369/// reach a total size of 64 bits. We have to add the extension separately
9370/// because ARM does not have a sign/zero extending load for vectors.
9371static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
9372 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9373
9374 // The load already has the right type.
9375 if (ExtendedTy == LD->getMemoryVT())
9376 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9377 LD->getBasePtr(), LD->getPointerInfo(), LD->getAlign(),
9378 LD->getMemOperand()->getFlags());
9379
9380 // We need to create a zextload/sextload. We cannot just create a load
9381 // followed by a zext/zext node because LowerMUL is also run during normal
9382 // operation legalization where we can't create illegal types.
9383 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9384 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9385 LD->getMemoryVT(), LD->getAlign(),
9386 LD->getMemOperand()->getFlags());
9387}
9388
9389/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9390/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9391/// the unextended value. The unextended vector should be 64 bits so that it can
9392/// be used as an operand to a VMULL instruction. If the original vector size
9393/// before extension is less than 64 bits we add a an extension to resize
9394/// the vector to 64 bits.
9395static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
9396 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9397 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9398 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9399 N->getOperand(0)->getValueType(0),
9400 N->getValueType(0),
9401 N->getOpcode());
9402
9403 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9404 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&(static_cast <bool> ((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad
(LD)) && "Expected extending load") ? void (0) : __assert_fail
("(ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && \"Expected extending load\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9405, __extension__
__PRETTY_FUNCTION__))
9405 "Expected extending load")(static_cast <bool> ((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad
(LD)) && "Expected extending load") ? void (0) : __assert_fail
("(ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && \"Expected extending load\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9405, __extension__
__PRETTY_FUNCTION__))
;
9406
9407 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9408 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9409 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9410 SDValue extLoad =
9411 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9412 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9413
9414 return newLoad;
9415 }
9416
9417 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9418 // have been legalized as a BITCAST from v4i32.
9419 if (N->getOpcode() == ISD::BITCAST) {
9420 SDNode *BVN = N->getOperand(0).getNode();
9421 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&(static_cast <bool> (BVN->getOpcode() == ISD::BUILD_VECTOR
&& BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"
) ? void (0) : __assert_fail ("BVN->getOpcode() == ISD::BUILD_VECTOR && BVN->getValueType(0) == MVT::v4i32 && \"expected v4i32 BUILD_VECTOR\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9422, __extension__
__PRETTY_FUNCTION__))
9422 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR")(static_cast <bool> (BVN->getOpcode() == ISD::BUILD_VECTOR
&& BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"
) ? void (0) : __assert_fail ("BVN->getOpcode() == ISD::BUILD_VECTOR && BVN->getValueType(0) == MVT::v4i32 && \"expected v4i32 BUILD_VECTOR\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9422, __extension__
__PRETTY_FUNCTION__))
;
9423 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9424 return DAG.getBuildVector(
9425 MVT::v2i32, SDLoc(N),
9426 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9427 }
9428 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9429 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR")(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "expected BUILD_VECTOR") ? void (0) : __assert_fail
("N->getOpcode() == ISD::BUILD_VECTOR && \"expected BUILD_VECTOR\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9429, __extension__
__PRETTY_FUNCTION__))
;
9430 EVT VT = N->getValueType(0);
9431 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9432 unsigned NumElts = VT.getVectorNumElements();
9433 MVT TruncVT = MVT::getIntegerVT(EltSize);
9434 SmallVector<SDValue, 8> Ops;
9435 SDLoc dl(N);
9436 for (unsigned i = 0; i != NumElts; ++i) {
9437 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
9438 const APInt &CInt = C->getAPIntValue();
9439 // Element types smaller than 32 bits are not legal, so use i32 elements.
9440 // The values are implicitly truncated so sext vs. zext doesn't matter.
9441 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9442 }
9443 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9444}
9445
9446static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9447 unsigned Opcode = N->getOpcode();
9448 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9449 SDNode *N0 = N->getOperand(0).getNode();
9450 SDNode *N1 = N->getOperand(1).getNode();
9451 return N0->hasOneUse() && N1->hasOneUse() &&
9452 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9453 }
9454 return false;
9455}
9456
9457static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9458 unsigned Opcode = N->getOpcode();
9459 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9460 SDNode *N0 = N->getOperand(0).getNode();
9461 SDNode *N1 = N->getOperand(1).getNode();
9462 return N0->hasOneUse() && N1->hasOneUse() &&
9463 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9464 }
9465 return false;
9466}
9467
9468static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
9469 // Multiplications are only custom-lowered for 128-bit vectors so that
9470 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9471 EVT VT = Op.getValueType();
9472 assert(VT.is128BitVector() && VT.isInteger() &&(static_cast <bool> (VT.is128BitVector() && VT.
isInteger() && "unexpected type for custom-lowering ISD::MUL"
) ? void (0) : __assert_fail ("VT.is128BitVector() && VT.isInteger() && \"unexpected type for custom-lowering ISD::MUL\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9473, __extension__
__PRETTY_FUNCTION__))
9473 "unexpected type for custom-lowering ISD::MUL")(static_cast <bool> (VT.is128BitVector() && VT.
isInteger() && "unexpected type for custom-lowering ISD::MUL"
) ? void (0) : __assert_fail ("VT.is128BitVector() && VT.isInteger() && \"unexpected type for custom-lowering ISD::MUL\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9473, __extension__
__PRETTY_FUNCTION__))
;
9474 SDNode *N0 = Op.getOperand(0).getNode();
9475 SDNode *N1 = Op.getOperand(1).getNode();
9476 unsigned NewOpc = 0;
9477 bool isMLA = false;
9478 bool isN0SExt = isSignExtended(N0, DAG);
9479 bool isN1SExt = isSignExtended(N1, DAG);
9480 if (isN0SExt && isN1SExt)
9481 NewOpc = ARMISD::VMULLs;
9482 else {
9483 bool isN0ZExt = isZeroExtended(N0, DAG);
9484 bool isN1ZExt = isZeroExtended(N1, DAG);
9485 if (isN0ZExt && isN1ZExt)
9486 NewOpc = ARMISD::VMULLu;
9487 else if (isN1SExt || isN1ZExt) {
9488 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9489 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9490 if (isN1SExt && isAddSubSExt(N0, DAG)) {
9491 NewOpc = ARMISD::VMULLs;
9492 isMLA = true;
9493 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9494 NewOpc = ARMISD::VMULLu;
9495 isMLA = true;
9496 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9497 std::swap(N0, N1);
9498 NewOpc = ARMISD::VMULLu;
9499 isMLA = true;
9500 }
9501 }
9502
9503 if (!NewOpc) {
9504 if (VT == MVT::v2i64)
9505 // Fall through to expand this. It is not legal.
9506 return SDValue();
9507 else
9508 // Other vector multiplications are legal.
9509 return Op;
9510 }
9511 }
9512
9513 // Legalize to a VMULL instruction.
9514 SDLoc DL(Op);
9515 SDValue Op0;
9516 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9517 if (!isMLA) {
9518 Op0 = SkipExtensionForVMULL(N0, DAG);
9519 assert(Op0.getValueType().is64BitVector() &&(static_cast <bool> (Op0.getValueType().is64BitVector()
&& Op1.getValueType().is64BitVector() && "unexpected types for extended operands to VMULL"
) ? void (0) : __assert_fail ("Op0.getValueType().is64BitVector() && Op1.getValueType().is64BitVector() && \"unexpected types for extended operands to VMULL\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9521, __extension__
__PRETTY_FUNCTION__))
9520 Op1.getValueType().is64BitVector() &&(static_cast <bool> (Op0.getValueType().is64BitVector()
&& Op1.getValueType().is64BitVector() && "unexpected types for extended operands to VMULL"
) ? void (0) : __assert_fail ("Op0.getValueType().is64BitVector() && Op1.getValueType().is64BitVector() && \"unexpected types for extended operands to VMULL\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9521, __extension__
__PRETTY_FUNCTION__))
9521 "unexpected types for extended operands to VMULL")(static_cast <bool> (Op0.getValueType().is64BitVector()
&& Op1.getValueType().is64BitVector() && "unexpected types for extended operands to VMULL"
) ? void (0) : __assert_fail ("Op0.getValueType().is64BitVector() && Op1.getValueType().is64BitVector() && \"unexpected types for extended operands to VMULL\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9521, __extension__
__PRETTY_FUNCTION__))
;
9522 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9523 }
9524
9525 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9526 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9527 // vmull q0, d4, d6
9528 // vmlal q0, d5, d6
9529 // is faster than
9530 // vaddl q0, d4, d5
9531 // vmovl q1, d6
9532 // vmul q0, q0, q1
9533 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9534 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9535 EVT Op1VT = Op1.getValueType();
9536 return DAG.getNode(N0->getOpcode(), DL, VT,
9537 DAG.getNode(NewOpc, DL, VT,
9538 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9539 DAG.getNode(NewOpc, DL, VT,
9540 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9541}
9542
9543static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
9544 SelectionDAG &DAG) {
9545 // TODO: Should this propagate fast-math-flags?
9546
9547 // Convert to float
9548 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9549 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9550 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9551 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9552 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9553 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9554 // Get reciprocal estimate.
9555 // float4 recip = vrecpeq_f32(yf);
9556 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9557 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9558 Y);
9559 // Because char has a smaller range than uchar, we can actually get away
9560 // without any newton steps. This requires that we use a weird bias
9561 // of 0xb000, however (again, this has been exhaustively tested).
9562 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9563 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9564 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9565 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9566 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9567 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9568 // Convert back to short.
9569 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9570 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9571 return X;
9572}
9573
9574static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9575 SelectionDAG &DAG) {
9576 // TODO: Should this propagate fast-math-flags?
9577
9578 SDValue N2;
9579 // Convert to float.
9580 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9581 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9582 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9583 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9584 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9585 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9586
9587 // Use reciprocal estimate and one refinement step.
9588 // float4 recip = vrecpeq_f32(yf);
9589 // recip *= vrecpsq_f32(yf, recip);
9590 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9591 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9592 N1);
9593 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9594 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9595 N1, N2);
9596 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9597 // Because short has a smaller range than ushort, we can actually get away
9598 // with only a single newton step. This requires that we use a weird bias
9599 // of 89, however (again, this has been exhaustively tested).
9600 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9601 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9602 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9603 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9604 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9605 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9606 // Convert back to integer and return.
9607 // return vmovn_s32(vcvt_s32_f32(result));
9608 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9609 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9610 return N0;
9611}
9612
9613static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9614 const ARMSubtarget *ST) {
9615 EVT VT = Op.getValueType();
9616 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::SDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::SDIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9617, __extension__
__PRETTY_FUNCTION__))
9617 "unexpected type for custom-lowering ISD::SDIV")(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::SDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::SDIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9617, __extension__
__PRETTY_FUNCTION__))
;
9618
9619 SDLoc dl(Op);
9620 SDValue N0 = Op.getOperand(0);
9621 SDValue N1 = Op.getOperand(1);
9622 SDValue N2, N3;
9623
9624 if (VT == MVT::v8i8) {
9625 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9626 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9627
9628 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9629 DAG.getIntPtrConstant(4, dl));
9630 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9631 DAG.getIntPtrConstant(4, dl));
9632 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9633 DAG.getIntPtrConstant(0, dl));
9634 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9635 DAG.getIntPtrConstant(0, dl));
9636
9637 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9638 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9639
9640 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9641 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9642
9643 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9644 return N0;
9645 }
9646 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9647}
9648
9649static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9650 const ARMSubtarget *ST) {
9651 // TODO: Should this propagate fast-math-flags?
9652 EVT VT = Op.getValueType();
9653 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::UDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::UDIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9654, __extension__
__PRETTY_FUNCTION__))
9654 "unexpected type for custom-lowering ISD::UDIV")(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::UDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::UDIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9654, __extension__
__PRETTY_FUNCTION__))
;
9655
9656 SDLoc dl(Op);
9657 SDValue N0 = Op.getOperand(0);
9658 SDValue N1 = Op.getOperand(1);
9659 SDValue N2, N3;
9660
9661 if (VT == MVT::v8i8) {
9662 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9663 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9664
9665 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9666 DAG.getIntPtrConstant(4, dl));
9667 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9668 DAG.getIntPtrConstant(4, dl));
9669 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9670 DAG.getIntPtrConstant(0, dl));
9671 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9672 DAG.getIntPtrConstant(0, dl));
9673
9674 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9675 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9676
9677 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9678 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9679
9680 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9681 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9682 MVT::i32),
9683 N0);
9684 return N0;
9685 }
9686
9687 // v4i16 sdiv ... Convert to float.
9688 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9689 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9690 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9691 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9692 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9693 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9694
9695 // Use reciprocal estimate and two refinement steps.
9696 // float4 recip = vrecpeq_f32(yf);
9697 // recip *= vrecpsq_f32(yf, recip);
9698 // recip *= vrecpsq_f32(yf, recip);
9699 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9700 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9701 BN1);
9702 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9703 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9704 BN1, N2);
9705 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9706 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9707 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9708 BN1, N2);
9709 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9710 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9711 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9712 // and that it will never cause us to return an answer too large).
9713 // float4 result = as_float4(as_int4(xf*recip) + 2);
9714 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9715 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9716 N1 = DAG.getConstant(2, dl, MVT::v4i32);
9717 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9718 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9719 // Convert back to integer and return.
9720 // return vmovn_u32(vcvt_s32_f32(result));
9721 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9722 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9723 return N0;
9724}
9725
9726static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
9727 SDNode *N = Op.getNode();
9728 EVT VT = N->getValueType(0);
9729 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9730
9731 SDValue Carry = Op.getOperand(2);
9732
9733 SDLoc DL(Op);
9734
9735 SDValue Result;
9736 if (Op.getOpcode() == ISD::ADDCARRY) {
9737 // This converts the boolean value carry into the carry flag.
9738 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9739
9740 // Do the addition proper using the carry flag we wanted.
9741 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9742 Op.getOperand(1), Carry);
9743
9744 // Now convert the carry flag into a boolean value.
9745 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9746 } else {
9747 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
9748 // have to invert the carry first.
9749 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9750 DAG.getConstant(1, DL, MVT::i32), Carry);
9751 // This converts the boolean value carry into the carry flag.
9752 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9753
9754 // Do the subtraction proper using the carry flag we wanted.
9755 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9756 Op.getOperand(1), Carry);
9757
9758 // Now convert the carry flag into a boolean value.
9759 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9760 // But the carry returned by ARMISD::SUBE is not a borrow as expected
9761 // by ISD::SUBCARRY, so compute 1 - C.
9762 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9763 DAG.getConstant(1, DL, MVT::i32), Carry);
9764 }
9765
9766 // Return both values.
9767 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9768}
9769
9770SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9771 assert(Subtarget->isTargetDarwin())(static_cast <bool> (Subtarget->isTargetDarwin()) ? void
(0) : __assert_fail ("Subtarget->isTargetDarwin()", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9771, __extension__ __PRETTY_FUNCTION__))
;
9772
9773 // For iOS, we want to call an alternative entry point: __sincos_stret,
9774 // return values are passed via sret.
9775 SDLoc dl(Op);
9776 SDValue Arg = Op.getOperand(0);
9777 EVT ArgVT = Arg.getValueType();
9778 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9779 auto PtrVT = getPointerTy(DAG.getDataLayout());
9780
9781 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9782 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9783
9784 // Pair of floats / doubles used to pass the result.
9785 Type *RetTy = StructType::get(ArgTy, ArgTy);
9786 auto &DL = DAG.getDataLayout();
9787
9788 ArgListTy Args;
9789 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9790 SDValue SRet;
9791 if (ShouldUseSRet) {
9792 // Create stack object for sret.
9793 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9794 const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9795 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9796 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9797
9798 ArgListEntry Entry;
9799 Entry.Node = SRet;
9800 Entry.Ty = RetTy->getPointerTo();
9801 Entry.IsSExt = false;
9802 Entry.IsZExt = false;
9803 Entry.IsSRet = true;
9804 Args.push_back(Entry);
9805 RetTy = Type::getVoidTy(*DAG.getContext());
9806 }
9807
9808 ArgListEntry Entry;
9809 Entry.Node = Arg;
9810 Entry.Ty = ArgTy;
9811 Entry.IsSExt = false;
9812 Entry.IsZExt = false;
9813 Args.push_back(Entry);
9814
9815 RTLIB::Libcall LC =
9816 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9817 const char *LibcallName = getLibcallName(LC);
9818 CallingConv::ID CC = getLibcallCallingConv(LC);
9819 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9820
9821 TargetLowering::CallLoweringInfo CLI(DAG);
9822 CLI.setDebugLoc(dl)
9823 .setChain(DAG.getEntryNode())
9824 .setCallee(CC, RetTy, Callee, std::move(Args))
9825 .setDiscardResult(ShouldUseSRet);
9826 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9827
9828 if (!ShouldUseSRet)
9829 return CallResult.first;
9830
9831 SDValue LoadSin =
9832 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9833
9834 // Address of cos field.
9835 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9836 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9837 SDValue LoadCos =
9838 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9839
9840 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9841 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9842 LoadSin.getValue(0), LoadCos.getValue(0));
9843}
9844
9845SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9846 bool Signed,
9847 SDValue &Chain) const {
9848 EVT VT = Op.getValueType();
9849 assert((VT == MVT::i32 || VT == MVT::i64) &&(static_cast <bool> ((VT == MVT::i32 || VT == MVT::i64)
&& "unexpected type for custom lowering DIV") ? void
(0) : __assert_fail ("(VT == MVT::i32 || VT == MVT::i64) && \"unexpected type for custom lowering DIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9850, __extension__
__PRETTY_FUNCTION__))
9850 "unexpected type for custom lowering DIV")(static_cast <bool> ((VT == MVT::i32 || VT == MVT::i64)
&& "unexpected type for custom lowering DIV") ? void
(0) : __assert_fail ("(VT == MVT::i32 || VT == MVT::i64) && \"unexpected type for custom lowering DIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9850, __extension__
__PRETTY_FUNCTION__))
;
9851 SDLoc dl(Op);
9852
9853 const auto &DL = DAG.getDataLayout();
9854 const auto &TLI = DAG.getTargetLoweringInfo();
9855
9856 const char *Name = nullptr;
9857 if (Signed)
9858 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9859 else
9860 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9861
9862 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9863
9864 ARMTargetLowering::ArgListTy Args;
9865
9866 for (auto AI : {1, 0}) {
9867 ArgListEntry Arg;
9868 Arg.Node = Op.getOperand(AI);
9869 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9870 Args.push_back(Arg);
9871 }
9872
9873 CallLoweringInfo CLI(DAG);
9874 CLI.setDebugLoc(dl)
9875 .setChain(Chain)
9876 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9877 ES, std::move(Args));
9878
9879 return LowerCallTo(CLI).first;
9880}
9881
9882// This is a code size optimisation: return the original SDIV node to
9883// DAGCombiner when we don't want to expand SDIV into a sequence of
9884// instructions, and an empty node otherwise which will cause the
9885// SDIV to be expanded in DAGCombine.
9886SDValue
9887ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9888 SelectionDAG &DAG,
9889 SmallVectorImpl<SDNode *> &Created) const {
9890 // TODO: Support SREM
9891 if (N->getOpcode() != ISD::SDIV)
9892 return SDValue();
9893
9894 const auto &ST = DAG.getSubtarget<ARMSubtarget>();
9895 const bool MinSize = ST.hasMinSize();
9896 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9897 : ST.hasDivideInARMMode();
9898
9899 // Don't touch vector types; rewriting this may lead to scalarizing
9900 // the int divs.
9901 if (N->getOperand(0).getValueType().isVector())
9902 return SDValue();
9903
9904 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9905 // hwdiv support for this to be really profitable.
9906 if (!(MinSize && HasDivide))
9907 return SDValue();
9908
9909 // ARM mode is a bit simpler than Thumb: we can handle large power
9910 // of 2 immediates with 1 mov instruction; no further checks required,
9911 // just return the sdiv node.
9912 if (!ST.isThumb())
9913 return SDValue(N, 0);
9914
9915 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9916 // and thus lose the code size benefits of a MOVS that requires only 2.
9917 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9918 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9919 if (Divisor.sgt(128))
9920 return SDValue();
9921
9922 return SDValue(N, 0);
9923}
9924
9925SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9926 bool Signed) const {
9927 assert(Op.getValueType() == MVT::i32 &&(static_cast <bool> (Op.getValueType() == MVT::i32 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i32 && \"unexpected type for custom lowering DIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9928, __extension__
__PRETTY_FUNCTION__))
9928 "unexpected type for custom lowering DIV")(static_cast <bool> (Op.getValueType() == MVT::i32 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i32 && \"unexpected type for custom lowering DIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9928, __extension__
__PRETTY_FUNCTION__))
;
9929 SDLoc dl(Op);
9930
9931 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9932 DAG.getEntryNode(), Op.getOperand(1));
9933
9934 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9935}
9936
9937static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9938 SDLoc DL(N);
9939 SDValue Op = N->getOperand(1);
9940 if (N->getValueType(0) == MVT::i32)
9941 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9942 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9943 DAG.getConstant(0, DL, MVT::i32));
9944 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9945 DAG.getConstant(1, DL, MVT::i32));
9946 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9947 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9948}
9949
9950void ARMTargetLowering::ExpandDIV_Windows(
9951 SDValue Op, SelectionDAG &DAG, bool Signed,
9952 SmallVectorImpl<SDValue> &Results) const {
9953 const auto &DL = DAG.getDataLayout();
9954 const auto &TLI = DAG.getTargetLoweringInfo();
9955
9956 assert(Op.getValueType() == MVT::i64 &&(static_cast <bool> (Op.getValueType() == MVT::i64 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i64 && \"unexpected type for custom lowering DIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9957, __extension__
__PRETTY_FUNCTION__))
9957 "unexpected type for custom lowering DIV")(static_cast <bool> (Op.getValueType() == MVT::i64 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i64 && \"unexpected type for custom lowering DIV\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9957, __extension__
__PRETTY_FUNCTION__))
;
9958 SDLoc dl(Op);
9959
9960 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9961
9962 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9963
9964 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9965 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9966 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9967 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9968
9969 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9970}
9971
9972static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9973 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9974 EVT MemVT = LD->getMemoryVT();
9975 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||(static_cast <bool> ((MemVT == MVT::v2i1 || MemVT == MVT
::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
"Expected a predicate type!") ? void (0) : __assert_fail ("(MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9977, __extension__
__PRETTY_FUNCTION__))
9976 MemVT == MVT::v16i1) &&(static_cast <bool> ((MemVT == MVT::v2i1 || MemVT == MVT
::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
"Expected a predicate type!") ? void (0) : __assert_fail ("(MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9977, __extension__
__PRETTY_FUNCTION__))
9977 "Expected a predicate type!")(static_cast <bool> ((MemVT == MVT::v2i1 || MemVT == MVT
::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
"Expected a predicate type!") ? void (0) : __assert_fail ("(MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9977, __extension__
__PRETTY_FUNCTION__))
;
9978 assert(MemVT == Op.getValueType())(static_cast <bool> (MemVT == Op.getValueType()) ? void
(0) : __assert_fail ("MemVT == Op.getValueType()", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9978, __extension__ __PRETTY_FUNCTION__))
;
9979 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&(static_cast <bool> (LD->getExtensionType() == ISD::
NON_EXTLOAD && "Expected a non-extending load") ? void
(0) : __assert_fail ("LD->getExtensionType() == ISD::NON_EXTLOAD && \"Expected a non-extending load\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9980, __extension__
__PRETTY_FUNCTION__))
9980 "Expected a non-extending load")(static_cast <bool> (LD->getExtensionType() == ISD::
NON_EXTLOAD && "Expected a non-extending load") ? void
(0) : __assert_fail ("LD->getExtensionType() == ISD::NON_EXTLOAD && \"Expected a non-extending load\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9980, __extension__
__PRETTY_FUNCTION__))
;
9981 assert(LD->isUnindexed() && "Expected a unindexed load")(static_cast <bool> (LD->isUnindexed() && "Expected a unindexed load"
) ? void (0) : __assert_fail ("LD->isUnindexed() && \"Expected a unindexed load\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 9981, __extension__
__PRETTY_FUNCTION__))
;
9982
9983 // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
9984 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9985 // need to make sure that 8/4/2 bits are actually loaded into the correct
9986 // place, which means loading the value and then shuffling the values into
9987 // the bottom bits of the predicate.
9988 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9989 // for BE).
9990 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9991 // a natural VMSR(load), so needs to be reversed.
9992
9993 SDLoc dl(Op);
9994 SDValue Load = DAG.getExtLoad(
9995 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9996 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9997 LD->getMemOperand());
9998 SDValue Val = Load;
9999 if (DAG.getDataLayout().isBigEndian())
10000 Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
10001 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
10002 DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
10003 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
10004 if (MemVT != MVT::v16i1)
10005 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
10006 DAG.getConstant(0, dl, MVT::i32));
10007 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
10008}
10009
10010void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
10011 SelectionDAG &DAG) const {
10012 LoadSDNode *LD = cast<LoadSDNode>(N);
10013 EVT MemVT = LD->getMemoryVT();
10014 assert(LD->isUnindexed() && "Loads should be unindexed at this point.")(static_cast <bool> (LD->isUnindexed() && "Loads should be unindexed at this point."
) ? void (0) : __assert_fail ("LD->isUnindexed() && \"Loads should be unindexed at this point.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10014, __extension__
__PRETTY_FUNCTION__))
;
10015
10016 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
10017 !Subtarget->isThumb1Only() && LD->isVolatile()) {
10018 SDLoc dl(N);
10019 SDValue Result = DAG.getMemIntrinsicNode(
10020 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
10021 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
10022 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
10023 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
10024 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
10025 Results.append({Pair, Result.getValue(2)});
10026 }
10027}
10028
10029static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
10030 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
10031 EVT MemVT = ST->getMemoryVT();
10032 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||(static_cast <bool> ((MemVT == MVT::v2i1 || MemVT == MVT
::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
"Expected a predicate type!") ? void (0) : __assert_fail ("(MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10034, __extension__
__PRETTY_FUNCTION__))
10033 MemVT == MVT::v16i1) &&(static_cast <bool> ((MemVT == MVT::v2i1 || MemVT == MVT
::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
"Expected a predicate type!") ? void (0) : __assert_fail ("(MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10034, __extension__
__PRETTY_FUNCTION__))
10034 "Expected a predicate type!")(static_cast <bool> ((MemVT == MVT::v2i1 || MemVT == MVT
::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
"Expected a predicate type!") ? void (0) : __assert_fail ("(MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10034, __extension__
__PRETTY_FUNCTION__))
;
10035 assert(MemVT == ST->getValue().getValueType())(static_cast <bool> (MemVT == ST->getValue().getValueType
()) ? void (0) : __assert_fail ("MemVT == ST->getValue().getValueType()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10035, __extension__
__PRETTY_FUNCTION__))
;
10036 assert(!ST->isTruncatingStore() && "Expected a non-extending store")(static_cast <bool> (!ST->isTruncatingStore() &&
"Expected a non-extending store") ? void (0) : __assert_fail
("!ST->isTruncatingStore() && \"Expected a non-extending store\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10036, __extension__
__PRETTY_FUNCTION__))
;
10037 assert(ST->isUnindexed() && "Expected a unindexed store")(static_cast <bool> (ST->isUnindexed() && "Expected a unindexed store"
) ? void (0) : __assert_fail ("ST->isUnindexed() && \"Expected a unindexed store\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10037, __extension__
__PRETTY_FUNCTION__))
;
10038
10039 // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
10040 // top bits unset and a scalar store.
10041 SDLoc dl(Op);
10042 SDValue Build = ST->getValue();
10043 if (MemVT != MVT::v16i1) {
10044 SmallVector<SDValue, 16> Ops;
10045 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
10046 unsigned Elt = DAG.getDataLayout().isBigEndian()
10047 ? MemVT.getVectorNumElements() - I - 1
10048 : I;
10049 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
10050 DAG.getConstant(Elt, dl, MVT::i32)));
10051 }
10052 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
10053 Ops.push_back(DAG.getUNDEF(MVT::i32));
10054 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
10055 }
10056 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
10057 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
10058 GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
10059 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
10060 DAG.getConstant(16, dl, MVT::i32));
10061 return DAG.getTruncStore(
10062 ST->getChain(), dl, GRP, ST->getBasePtr(),
10063 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
10064 ST->getMemOperand());
10065}
10066
10067static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
10068 const ARMSubtarget *Subtarget) {
10069 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
10070 EVT MemVT = ST->getMemoryVT();
10071 assert(ST->isUnindexed() && "Stores should be unindexed at this point.")(static_cast <bool> (ST->isUnindexed() && "Stores should be unindexed at this point."
) ? void (0) : __assert_fail ("ST->isUnindexed() && \"Stores should be unindexed at this point.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10071, __extension__
__PRETTY_FUNCTION__))
;
10072
10073 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
10074 !Subtarget->isThumb1Only() && ST->isVolatile()) {
10075 SDNode *N = Op.getNode();
10076 SDLoc dl(N);
10077
10078 SDValue Lo = DAG.getNode(
10079 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
10080 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
10081 MVT::i32));
10082 SDValue Hi = DAG.getNode(
10083 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
10084 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
10085 MVT::i32));
10086
10087 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
10088 {ST->getChain(), Lo, Hi, ST->getBasePtr()},
10089 MemVT, ST->getMemOperand());
10090 } else if (Subtarget->hasMVEIntegerOps() &&
10091 ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10092 MemVT == MVT::v16i1))) {
10093 return LowerPredicateStore(Op, DAG);
10094 }
10095
10096 return SDValue();
10097}
10098
10099static bool isZeroVector(SDValue N) {
10100 return (ISD::isBuildVectorAllZeros(N.getNode()) ||
10101 (N->getOpcode() == ARMISD::VMOVIMM &&
10102 isNullConstant(N->getOperand(0))));
10103}
10104
10105static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
10106 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
10107 MVT VT = Op.getSimpleValueType();
10108 SDValue Mask = N->getMask();
10109 SDValue PassThru = N->getPassThru();
10110 SDLoc dl(Op);
10111
10112 if (isZeroVector(PassThru))
10113 return Op;
10114
10115 // MVE Masked loads use zero as the passthru value. Here we convert undef to
10116 // zero too, and other values are lowered to a select.
10117 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
10118 DAG.getTargetConstant(0, dl, MVT::i32));
10119 SDValue NewLoad = DAG.getMaskedLoad(
10120 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
10121 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
10122 N->getExtensionType(), N->isExpandingLoad());
10123 SDValue Combo = NewLoad;
10124 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
10125 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
10126 isZeroVector(PassThru->getOperand(0));
10127 if (!PassThru.isUndef() && !PassThruIsCastZero)
10128 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
10129 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
10130}
10131
10132static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
10133 const ARMSubtarget *ST) {
10134 if (!ST->hasMVEIntegerOps())
10135 return SDValue();
10136
10137 SDLoc dl(Op);
10138 unsigned BaseOpcode = 0;
10139 switch (Op->getOpcode()) {
10140 default: llvm_unreachable("Expected VECREDUCE opcode")::llvm::llvm_unreachable_internal("Expected VECREDUCE opcode"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10140)
;
10141 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10142 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10143 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
10144 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
10145 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
10146 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
10147 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10148 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10149 }
10150
10151 SDValue Op0 = Op->getOperand(0);
10152 EVT VT = Op0.getValueType();
10153 EVT EltVT = VT.getVectorElementType();
10154 unsigned NumElts = VT.getVectorNumElements();
10155 unsigned NumActiveLanes = NumElts;
10156
10157 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||(static_cast <bool> ((NumActiveLanes == 16 || NumActiveLanes
== 8 || NumActiveLanes == 4 || NumActiveLanes == 2) &&
"Only expected a power 2 vector size") ? void (0) : __assert_fail
("(NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || NumActiveLanes == 2) && \"Only expected a power 2 vector size\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10159, __extension__
__PRETTY_FUNCTION__))
10158 NumActiveLanes == 2) &&(static_cast <bool> ((NumActiveLanes == 16 || NumActiveLanes
== 8 || NumActiveLanes == 4 || NumActiveLanes == 2) &&
"Only expected a power 2 vector size") ? void (0) : __assert_fail
("(NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || NumActiveLanes == 2) && \"Only expected a power 2 vector size\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10159, __extension__
__PRETTY_FUNCTION__))
10159 "Only expected a power 2 vector size")(static_cast <bool> ((NumActiveLanes == 16 || NumActiveLanes
== 8 || NumActiveLanes == 4 || NumActiveLanes == 2) &&
"Only expected a power 2 vector size") ? void (0) : __assert_fail
("(NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || NumActiveLanes == 2) && \"Only expected a power 2 vector size\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10159, __extension__
__PRETTY_FUNCTION__))
;
10160
10161 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10162 // allows us to easily extract vector elements from the lanes.
10163 while (NumActiveLanes > 4) {
10164 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10165 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
10166 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
10167 NumActiveLanes /= 2;
10168 }
10169
10170 SDValue Res;
10171 if (NumActiveLanes == 4) {
10172 // The remaining 4 elements are summed sequentially
10173 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10174 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
10175 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10176 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
10177 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10178 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
10179 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10180 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
10181 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10182 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
10183 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
10184 } else {
10185 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10186 DAG.getConstant(0, dl, MVT::i32));
10187 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10188 DAG.getConstant(1, dl, MVT::i32));
10189 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10190 }
10191
10192 // Result type may be wider than element type.
10193 if (EltVT != Op->getValueType(0))
10194 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10195 return Res;
10196}
10197
10198static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
10199 const ARMSubtarget *ST) {
10200 if (!ST->hasMVEFloatOps())
10201 return SDValue();
10202 return LowerVecReduce(Op, DAG, ST);
10203}
10204
10205static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
10206 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getSuccessOrdering()))
10207 // Acquire/Release load/store is not legal for targets without a dmb or
10208 // equivalent available.
10209 return SDValue();
10210
10211 // Monotonic load/store is legal for all targets.
10212 return Op;
10213}
10214
10215static void ReplaceREADCYCLECOUNTER(SDNode *N,
10216 SmallVectorImpl<SDValue> &Results,
10217 SelectionDAG &DAG,
10218 const ARMSubtarget *Subtarget) {
10219 SDLoc DL(N);
10220 // Under Power Management extensions, the cycle-count is:
10221 // mrc p15, #0, <Rt>, c9, c13, #0
10222 SDValue Ops[] = { N->getOperand(0), // Chain
10223 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10224 DAG.getTargetConstant(15, DL, MVT::i32),
10225 DAG.getTargetConstant(0, DL, MVT::i32),
10226 DAG.getTargetConstant(9, DL, MVT::i32),
10227 DAG.getTargetConstant(13, DL, MVT::i32),
10228 DAG.getTargetConstant(0, DL, MVT::i32)
10229 };
10230
10231 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10232 DAG.getVTList(MVT::i32, MVT::Other), Ops);
10233 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10234 DAG.getConstant(0, DL, MVT::i32)));
10235 Results.push_back(Cycles32.getValue(1));
10236}
10237
10238static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
10239 SDLoc dl(V.getNode());
10240 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
10241 SDValue VHi = DAG.getAnyExtOrTrunc(
10242 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
10243 dl, MVT::i32);
10244 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10245 if (isBigEndian)
10246 std::swap (VLo, VHi);
10247 SDValue RegClass =
10248 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10249 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10250 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10251 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
10252 return SDValue(
10253 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10254}
10255
10256static void ReplaceCMP_SWAP_64Results(SDNode *N,
10257 SmallVectorImpl<SDValue> & Results,
10258 SelectionDAG &DAG) {
10259 assert(N->getValueType(0) == MVT::i64 &&(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"AtomicCmpSwap on types less than 64 should be legal") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"AtomicCmpSwap on types less than 64 should be legal\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10260, __extension__
__PRETTY_FUNCTION__))
10260 "AtomicCmpSwap on types less than 64 should be legal")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"AtomicCmpSwap on types less than 64 should be legal") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"AtomicCmpSwap on types less than 64 should be legal\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10260, __extension__
__PRETTY_FUNCTION__))
;
10261 SDValue Ops[] = {N->getOperand(1),
10262 createGPRPairNode(DAG, N->getOperand(2)),
10263 createGPRPairNode(DAG, N->getOperand(3)),
10264 N->getOperand(0)};
10265 SDNode *CmpSwap = DAG.getMachineNode(
10266 ARM::CMP_SWAP_64, SDLoc(N),
10267 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
10268
10269 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10270 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10271
10272 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10273
10274 SDValue Lo =
10275 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10276 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10277 SDValue Hi =
10278 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10279 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10280 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10281 Results.push_back(SDValue(CmpSwap, 2));
10282}
10283
10284SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10285 SDLoc dl(Op);
10286 EVT VT = Op.getValueType();
10287 SDValue Chain = Op.getOperand(0);
10288 SDValue LHS = Op.getOperand(1);
10289 SDValue RHS = Op.getOperand(2);
10290 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
10291 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10292
10293 // If we don't have instructions of this float type then soften to a libcall
10294 // and use SETCC instead.
10295 if (isUnsupportedFloatingType(LHS.getValueType())) {
10296 DAG.getTargetLoweringInfo().softenSetCCOperands(
10297 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
10298 if (!RHS.getNode()) {
10299 RHS = DAG.getConstant(0, dl, LHS.getValueType());
10300 CC = ISD::SETNE;
10301 }
10302 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10303 DAG.getCondCode(CC));
10304 return DAG.getMergeValues({Result, Chain}, dl);
10305 }
10306
10307 ARMCC::CondCodes CondCode, CondCode2;
10308 FPCCToARMCC(CC, CondCode, CondCode2);
10309
10310 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
10311 // in CMPFP and CMPFPE, but instead it should be made explicit by these
10312 // instructions using a chain instead of glue. This would also fix the problem
10313 // here (and also in LowerSELECT_CC) where we generate two comparisons when
10314 // CondCode2 != AL.
10315 SDValue True = DAG.getConstant(1, dl, VT);
10316 SDValue False = DAG.getConstant(0, dl, VT);
10317 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10318 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
10319 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10320 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
10321 if (CondCode2 != ARMCC::AL) {
10322 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10323 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10324 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
10325 }
10326 return DAG.getMergeValues({Result, Chain}, dl);
10327}
10328
10329SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10330 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10331
10332 EVT VT = getPointerTy(DAG.getDataLayout());
10333 SDLoc DL(Op);
10334 int FI = MFI.CreateFixedObject(4, 0, false);
10335 return DAG.getFrameIndex(FI, VT);
10336}
10337
10338SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10339 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Lowering node: "; Op.dump();
} } while (false)
;
10340 switch (Op.getOpcode()) {
10341 default: llvm_unreachable("Don't know how to custom lower this!")::llvm::llvm_unreachable_internal("Don't know how to custom lower this!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10341)
;
10342 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10343 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10344 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10345 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10346 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10347 case ISD::SELECT: return LowerSELECT(Op, DAG);
10348 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10349 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10350 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10351 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10352 case ISD::VASTART: return LowerVASTART(Op, DAG);
10353 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10354 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10355 case ISD::SINT_TO_FP:
10356 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10357 case ISD::STRICT_FP_TO_SINT:
10358 case ISD::STRICT_FP_TO_UINT:
10359 case ISD::FP_TO_SINT:
10360 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10361 case ISD::FP_TO_SINT_SAT:
10362 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10363 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10364 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10365 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10366 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10367 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10368 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10369 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10370 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10371 Subtarget);
10372 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10373 case ISD::SHL:
10374 case ISD::SRL:
10375 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
10376 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
10377 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
10378 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10379 case ISD::SRL_PARTS:
10380 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10381 case ISD::CTTZ:
10382 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10383 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10384 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
10385 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10386 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
10387 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10388 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10389 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10390 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10391 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10392 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10393 case ISD::TRUNCATE: return LowerTruncate(Op.getNode(), DAG, Subtarget);
10394 case ISD::SIGN_EXTEND:
10395 case ISD::ZERO_EXTEND: return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10396 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10397 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10398 case ISD::MUL: return LowerMUL(Op, DAG);
10399 case ISD::SDIV:
10400 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10401 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10402 return LowerSDIV(Op, DAG, Subtarget);
10403 case ISD::UDIV:
10404 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10405 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10406 return LowerUDIV(Op, DAG, Subtarget);
10407 case ISD::ADDCARRY:
10408 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
10409 case ISD::SADDO:
10410 case ISD::SSUBO:
10411 return LowerSignedALUO(Op, DAG);
10412 case ISD::UADDO:
10413 case ISD::USUBO:
10414 return LowerUnsignedALUO(Op, DAG);
10415 case ISD::SADDSAT:
10416 case ISD::SSUBSAT:
10417 case ISD::UADDSAT:
10418 case ISD::USUBSAT:
10419 return LowerADDSUBSAT(Op, DAG, Subtarget);
10420 case ISD::LOAD:
10421 return LowerPredicateLoad(Op, DAG);
10422 case ISD::STORE:
10423 return LowerSTORE(Op, DAG, Subtarget);
10424 case ISD::MLOAD:
10425 return LowerMLOAD(Op, DAG);
10426 case ISD::VECREDUCE_MUL:
10427 case ISD::VECREDUCE_AND:
10428 case ISD::VECREDUCE_OR:
10429 case ISD::VECREDUCE_XOR:
10430 return LowerVecReduce(Op, DAG, Subtarget);
10431 case ISD::VECREDUCE_FADD:
10432 case ISD::VECREDUCE_FMUL:
10433 case ISD::VECREDUCE_FMIN:
10434 case ISD::VECREDUCE_FMAX:
10435 return LowerVecReduceF(Op, DAG, Subtarget);
10436 case ISD::ATOMIC_LOAD:
10437 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
10438 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
10439 case ISD::SDIVREM:
10440 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10441 case ISD::DYNAMIC_STACKALLOC:
10442 if (Subtarget->isTargetWindows())
10443 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10444 llvm_unreachable("Don't know how to custom lower this!")::llvm::llvm_unreachable_internal("Don't know how to custom lower this!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10444)
;
10445 case ISD::STRICT_FP_ROUND:
10446 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10447 case ISD::STRICT_FP_EXTEND:
10448 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10449 case ISD::STRICT_FSETCC:
10450 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10451 case ISD::SPONENTRY:
10452 return LowerSPONENTRY(Op, DAG);
10453 case ARMISD::WIN__DBZCHK: return SDValue();
10454 }
10455}
10456
10457static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
10458 SelectionDAG &DAG) {
10459 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10460 unsigned Opc = 0;
10461 if (IntNo == Intrinsic::arm_smlald)
10462 Opc = ARMISD::SMLALD;
10463 else if (IntNo == Intrinsic::arm_smlaldx)
10464 Opc = ARMISD::SMLALDX;
10465 else if (IntNo == Intrinsic::arm_smlsld)
10466 Opc = ARMISD::SMLSLD;
10467 else if (IntNo == Intrinsic::arm_smlsldx)
10468 Opc = ARMISD::SMLSLDX;
10469 else
10470 return;
10471
10472 SDLoc dl(N);
10473 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10474 N->getOperand(3),
10475 DAG.getConstant(0, dl, MVT::i32));
10476 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10477 N->getOperand(3),
10478 DAG.getConstant(1, dl, MVT::i32));
10479
10480 SDValue LongMul = DAG.getNode(Opc, dl,
10481 DAG.getVTList(MVT::i32, MVT::i32),
10482 N->getOperand(1), N->getOperand(2),
10483 Lo, Hi);
10484 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10485 LongMul.getValue(0), LongMul.getValue(1)));
10486}
10487
10488/// ReplaceNodeResults - Replace the results of node with an illegal result
10489/// type with new values built out of custom code.
10490void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
10491 SmallVectorImpl<SDValue> &Results,
10492 SelectionDAG &DAG) const {
10493 SDValue Res;
10494 switch (N->getOpcode()) {
10495 default:
10496 llvm_unreachable("Don't know how to custom expand this!")::llvm::llvm_unreachable_internal("Don't know how to custom expand this!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10496)
;
10497 case ISD::READ_REGISTER:
10498 ExpandREAD_REGISTER(N, Results, DAG);
10499 break;
10500 case ISD::BITCAST:
10501 Res = ExpandBITCAST(N, DAG, Subtarget);
10502 break;
10503 case ISD::SRL:
10504 case ISD::SRA:
10505 case ISD::SHL:
10506 Res = Expand64BitShift(N, DAG, Subtarget);
10507 break;
10508 case ISD::SREM:
10509 case ISD::UREM:
10510 Res = LowerREM(N, DAG);
10511 break;
10512 case ISD::SDIVREM:
10513 case ISD::UDIVREM:
10514 Res = LowerDivRem(SDValue(N, 0), DAG);
10515 assert(Res.getNumOperands() == 2 && "DivRem needs two values")(static_cast <bool> (Res.getNumOperands() == 2 &&
"DivRem needs two values") ? void (0) : __assert_fail ("Res.getNumOperands() == 2 && \"DivRem needs two values\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10515, __extension__
__PRETTY_FUNCTION__))
;
10516 Results.push_back(Res.getValue(0));
10517 Results.push_back(Res.getValue(1));
10518 return;
10519 case ISD::SADDSAT:
10520 case ISD::SSUBSAT:
10521 case ISD::UADDSAT:
10522 case ISD::USUBSAT:
10523 Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10524 break;
10525 case ISD::READCYCLECOUNTER:
10526 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10527 return;
10528 case ISD::UDIV:
10529 case ISD::SDIV:
10530 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows")(static_cast <bool> (Subtarget->isTargetWindows() &&
"can only expand DIV on Windows") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"can only expand DIV on Windows\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10530, __extension__
__PRETTY_FUNCTION__))
;
10531 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10532 Results);
10533 case ISD::ATOMIC_CMP_SWAP:
10534 ReplaceCMP_SWAP_64Results(N, Results, DAG);
10535 return;
10536 case ISD::INTRINSIC_WO_CHAIN:
10537 return ReplaceLongIntrinsic(N, Results, DAG);
10538 case ISD::LOAD:
10539 LowerLOAD(N, Results, DAG);
10540 break;
10541 case ISD::TRUNCATE:
10542 Res = LowerTruncate(N, DAG, Subtarget);
10543 break;
10544 case ISD::SIGN_EXTEND:
10545 case ISD::ZERO_EXTEND:
10546 Res = LowerVectorExtend(N, DAG, Subtarget);
10547 break;
10548 case ISD::FP_TO_SINT_SAT:
10549 case ISD::FP_TO_UINT_SAT:
10550 Res = LowerFP_TO_INT_SAT(SDValue(N, 0), DAG, Subtarget);
10551 break;
10552 }
10553 if (Res.getNode())
10554 Results.push_back(Res);
10555}
10556
10557//===----------------------------------------------------------------------===//
10558// ARM Scheduler Hooks
10559//===----------------------------------------------------------------------===//
10560
10561/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10562/// registers the function context.
10563void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10564 MachineBasicBlock *MBB,
10565 MachineBasicBlock *DispatchBB,
10566 int FI) const {
10567 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported with SjLj"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported with SjLj\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10568, __extension__
__PRETTY_FUNCTION__))
10568 "ROPI/RWPI not currently supported with SjLj")(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported with SjLj"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported with SjLj\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10568, __extension__
__PRETTY_FUNCTION__))
;
10569 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10570 DebugLoc dl = MI.getDebugLoc();
10571 MachineFunction *MF = MBB->getParent();
10572 MachineRegisterInfo *MRI = &MF->getRegInfo();
10573 MachineConstantPool *MCP = MF->getConstantPool();
10574 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
10575 const Function &F = MF->getFunction();
10576
10577 bool isThumb = Subtarget->isThumb();
10578 bool isThumb2 = Subtarget->isThumb2();
10579
10580 unsigned PCLabelId = AFI->createPICLabelUId();
10581 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10582 ARMConstantPoolValue *CPV =
10583 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10584 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10585
10586 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10587 : &ARM::GPRRegClass;
10588
10589 // Grab constant pool and fixed stack memory operands.
10590 MachineMemOperand *CPMMO =
10591 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10592 MachineMemOperand::MOLoad, 4, Align(4));
10593
10594 MachineMemOperand *FIMMOSt =
10595 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
10596 MachineMemOperand::MOStore, 4, Align(4));
10597
10598 // Load the address of the dispatch MBB into the jump buffer.
10599 if (isThumb2) {
10600 // Incoming value: jbuf
10601 // ldr.n r5, LCPI1_1
10602 // orr r5, r5, #1
10603 // add r5, pc
10604 // str r5, [$jbuf, #+4] ; &jbuf[1]
10605 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10606 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10607 .addConstantPoolIndex(CPI)
10608 .addMemOperand(CPMMO)
10609 .add(predOps(ARMCC::AL));
10610 // Set the low bit because of thumb mode.
10611 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10612 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10613 .addReg(NewVReg1, RegState::Kill)
10614 .addImm(0x01)
10615 .add(predOps(ARMCC::AL))
10616 .add(condCodeOp());
10617 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10618 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10619 .addReg(NewVReg2, RegState::Kill)
10620 .addImm(PCLabelId);
10621 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10622 .addReg(NewVReg3, RegState::Kill)
10623 .addFrameIndex(FI)
10624 .addImm(36) // &jbuf[1] :: pc
10625 .addMemOperand(FIMMOSt)
10626 .add(predOps(ARMCC::AL));
10627 } else if (isThumb) {
10628 // Incoming value: jbuf
10629 // ldr.n r1, LCPI1_4
10630 // add r1, pc
10631 // mov r2, #1
10632 // orrs r1, r2
10633 // add r2, $jbuf, #+4 ; &jbuf[1]
10634 // str r1, [r2]
10635 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10636 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10637 .addConstantPoolIndex(CPI)
10638 .addMemOperand(CPMMO)
10639 .add(predOps(ARMCC::AL));
10640 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10641 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10642 .addReg(NewVReg1, RegState::Kill)
10643 .addImm(PCLabelId);
10644 // Set the low bit because of thumb mode.
10645 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10646 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10647 .addReg(ARM::CPSR, RegState::Define)
10648 .addImm(1)
10649 .add(predOps(ARMCC::AL));
10650 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10651 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10652 .addReg(ARM::CPSR, RegState::Define)
10653 .addReg(NewVReg2, RegState::Kill)
10654 .addReg(NewVReg3, RegState::Kill)
10655 .add(predOps(ARMCC::AL));
10656 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10657 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10658 .addFrameIndex(FI)
10659 .addImm(36); // &jbuf[1] :: pc
10660 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10661 .addReg(NewVReg4, RegState::Kill)
10662 .addReg(NewVReg5, RegState::Kill)
10663 .addImm(0)
10664 .addMemOperand(FIMMOSt)
10665 .add(predOps(ARMCC::AL));
10666 } else {
10667 // Incoming value: jbuf
10668 // ldr r1, LCPI1_1
10669 // add r1, pc, r1
10670 // str r1, [$jbuf, #+4] ; &jbuf[1]
10671 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10672 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10673 .addConstantPoolIndex(CPI)
10674 .addImm(0)
10675 .addMemOperand(CPMMO)
10676 .add(predOps(ARMCC::AL));
10677 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10678 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10679 .addReg(NewVReg1, RegState::Kill)
10680 .addImm(PCLabelId)
10681 .add(predOps(ARMCC::AL));
10682 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10683 .addReg(NewVReg2, RegState::Kill)
10684 .addFrameIndex(FI)
10685 .addImm(36) // &jbuf[1] :: pc
10686 .addMemOperand(FIMMOSt)
10687 .add(predOps(ARMCC::AL));
10688 }
10689}
10690
10691void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10692 MachineBasicBlock *MBB) const {
10693 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10694 DebugLoc dl = MI.getDebugLoc();
10695 MachineFunction *MF = MBB->getParent();
10696 MachineRegisterInfo *MRI = &MF->getRegInfo();
10697 MachineFrameInfo &MFI = MF->getFrameInfo();
10698 int FI = MFI.getFunctionContextIndex();
10699
10700 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10701 : &ARM::GPRnopcRegClass;
10702
10703 // Get a mapping of the call site numbers to all of the landing pads they're
10704 // associated with.
10705 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10706 unsigned MaxCSNum = 0;
10707 for (MachineBasicBlock &BB : *MF) {
10708 if (!BB.isEHPad())
10709 continue;
10710
10711 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10712 // pad.
10713 for (MachineInstr &II : BB) {
10714 if (!II.isEHLabel())
10715 continue;
10716
10717 MCSymbol *Sym = II.getOperand(0).getMCSymbol();
10718 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10719
10720 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10721 for (unsigned Idx : CallSiteIdxs) {
10722 CallSiteNumToLPad[Idx].push_back(&BB);
10723 MaxCSNum = std::max(MaxCSNum, Idx);
10724 }
10725 break;
10726 }
10727 }
10728
10729 // Get an ordered list of the machine basic blocks for the jump table.
10730 std::vector<MachineBasicBlock*> LPadList;
10731 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10732 LPadList.reserve(CallSiteNumToLPad.size());
10733 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10734 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10735 for (MachineBasicBlock *MBB : MBBList) {
10736 LPadList.push_back(MBB);
10737 InvokeBBs.insert(MBB->pred_begin(), MBB->pred_end());
10738 }
10739 }
10740
10741 assert(!LPadList.empty() &&(static_cast <bool> (!LPadList.empty() && "No landing pad destinations for the dispatch jump table!"
) ? void (0) : __assert_fail ("!LPadList.empty() && \"No landing pad destinations for the dispatch jump table!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10742, __extension__
__PRETTY_FUNCTION__))
10742 "No landing pad destinations for the dispatch jump table!")(static_cast <bool> (!LPadList.empty() && "No landing pad destinations for the dispatch jump table!"
) ? void (0) : __assert_fail ("!LPadList.empty() && \"No landing pad destinations for the dispatch jump table!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 10742, __extension__
__PRETTY_FUNCTION__))
;
10743
10744 // Create the jump table and associated information.
10745 MachineJumpTableInfo *JTI =
10746 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10747 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10748
10749 // Create the MBBs for the dispatch code.
10750
10751 // Shove the dispatch's address into the return slot in the function context.
10752 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10753 DispatchBB->setIsEHPad();
10754
10755 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10756 unsigned trap_opcode;
10757 if (Subtarget->isThumb())
10758 trap_opcode = ARM::tTRAP;
10759 else
10760 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10761
10762 BuildMI(TrapBB, dl, TII->get(trap_opcode));
10763 DispatchBB->addSuccessor(TrapBB);
10764
10765 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10766 DispatchBB->addSuccessor(DispContBB);
10767
10768 // Insert and MBBs.
10769 MF->insert(MF->end(), DispatchBB);
10770 MF->insert(MF->end(), DispContBB);
10771 MF->insert(MF->end(), TrapBB);
10772
10773 // Insert code into the entry block that creates and registers the function
10774 // context.
10775 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10776
10777 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10778 MachinePointerInfo::getFixedStack(*MF, FI),
10779 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10780
10781 MachineInstrBuilder MIB;
10782 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10783
10784 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10785 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10786
10787 // Add a register mask with no preserved registers. This results in all
10788 // registers being marked as clobbered. This can't work if the dispatch block
10789 // is in a Thumb1 function and is linked with ARM code which uses the FP
10790 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10791 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
10792
10793 bool IsPositionIndependent = isPositionIndependent();
10794 unsigned NumLPads = LPadList.size();
10795 if (Subtarget->isThumb2()) {
10796 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10797 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10798 .addFrameIndex(FI)
10799 .addImm(4)
10800 .addMemOperand(FIMMOLd)
10801 .add(predOps(ARMCC::AL));
10802
10803 if (NumLPads < 256) {
10804 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10805 .addReg(NewVReg1)
10806 .addImm(LPadList.size())
10807 .add(predOps(ARMCC::AL));
10808 } else {
10809 Register VReg1 = MRI->createVirtualRegister(TRC);
10810 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10811 .addImm(NumLPads & 0xFFFF)
10812 .add(predOps(ARMCC::AL));
10813
10814 unsigned VReg2 = VReg1;
10815 if ((NumLPads & 0xFFFF0000) != 0) {
10816 VReg2 = MRI->createVirtualRegister(TRC);
10817 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10818 .addReg(VReg1)
10819 .addImm(NumLPads >> 16)
10820 .add(predOps(ARMCC::AL));
10821 }
10822
10823 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10824 .addReg(NewVReg1)
10825 .addReg(VReg2)
10826 .add(predOps(ARMCC::AL));
10827 }
10828
10829 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10830 .addMBB(TrapBB)
10831 .addImm(ARMCC::HI)
10832 .addReg(ARM::CPSR);
10833
10834 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10835 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10836 .addJumpTableIndex(MJTI)
10837 .add(predOps(ARMCC::AL));
10838
10839 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10840 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10841 .addReg(NewVReg3, RegState::Kill)
10842 .addReg(NewVReg1)
10843 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10844 .add(predOps(ARMCC::AL))
10845 .add(condCodeOp());
10846
10847 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10848 .addReg(NewVReg4, RegState::Kill)
10849 .addReg(NewVReg1)
10850 .addJumpTableIndex(MJTI);
10851 } else if (Subtarget->isThumb()) {
10852 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10853 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10854 .addFrameIndex(FI)
10855 .addImm(1)
10856 .addMemOperand(FIMMOLd)
10857 .add(predOps(ARMCC::AL));
10858
10859 if (NumLPads < 256) {
10860 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10861 .addReg(NewVReg1)
10862 .addImm(NumLPads)
10863 .add(predOps(ARMCC::AL));
10864 } else {
10865 MachineConstantPool *ConstantPool = MF->getConstantPool();
10866 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10867 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10868
10869 // MachineConstantPool wants an explicit alignment.
10870 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10871 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10872
10873 Register VReg1 = MRI->createVirtualRegister(TRC);
10874 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10875 .addReg(VReg1, RegState::Define)
10876 .addConstantPoolIndex(Idx)
10877 .add(predOps(ARMCC::AL));
10878 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10879 .addReg(NewVReg1)
10880 .addReg(VReg1)
10881 .add(predOps(ARMCC::AL));
10882 }
10883
10884 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10885 .addMBB(TrapBB)
10886 .addImm(ARMCC::HI)
10887 .addReg(ARM::CPSR);
10888
10889 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10890 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10891 .addReg(ARM::CPSR, RegState::Define)
10892 .addReg(NewVReg1)
10893 .addImm(2)
10894 .add(predOps(ARMCC::AL));
10895
10896 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10897 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10898 .addJumpTableIndex(MJTI)
10899 .add(predOps(ARMCC::AL));
10900
10901 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10902 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10903 .addReg(ARM::CPSR, RegState::Define)
10904 .addReg(NewVReg2, RegState::Kill)
10905 .addReg(NewVReg3)
10906 .add(predOps(ARMCC::AL));
10907
10908 MachineMemOperand *JTMMOLd =
10909 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10910 MachineMemOperand::MOLoad, 4, Align(4));
10911
10912 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10913 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10914 .addReg(NewVReg4, RegState::Kill)
10915 .addImm(0)
10916 .addMemOperand(JTMMOLd)
10917 .add(predOps(ARMCC::AL));
10918
10919 unsigned NewVReg6 = NewVReg5;
10920 if (IsPositionIndependent) {
10921 NewVReg6 = MRI->createVirtualRegister(TRC);
10922 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
10923 .addReg(ARM::CPSR, RegState::Define)
10924 .addReg(NewVReg5, RegState::Kill)
10925 .addReg(NewVReg3)
10926 .add(predOps(ARMCC::AL));
10927 }
10928
10929 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
10930 .addReg(NewVReg6, RegState::Kill)
10931 .addJumpTableIndex(MJTI);
10932 } else {
10933 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10934 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
10935 .addFrameIndex(FI)
10936 .addImm(4)
10937 .addMemOperand(FIMMOLd)
10938 .add(predOps(ARMCC::AL));
10939
10940 if (NumLPads < 256) {
10941 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
10942 .addReg(NewVReg1)
10943 .addImm(NumLPads)
10944 .add(predOps(ARMCC::AL));
10945 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
10946 Register VReg1 = MRI->createVirtualRegister(TRC);
10947 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
10948 .addImm(NumLPads & 0xFFFF)
10949 .add(predOps(ARMCC::AL));
10950
10951 unsigned VReg2 = VReg1;
10952 if ((NumLPads & 0xFFFF0000) != 0) {
10953 VReg2 = MRI->createVirtualRegister(TRC);
10954 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
10955 .addReg(VReg1)
10956 .addImm(NumLPads >> 16)
10957 .add(predOps(ARMCC::AL));
10958 }
10959
10960 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10961 .addReg(NewVReg1)
10962 .addReg(VReg2)
10963 .add(predOps(ARMCC::AL));
10964 } else {
10965 MachineConstantPool *ConstantPool = MF->getConstantPool();
10966 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10967 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10968
10969 // MachineConstantPool wants an explicit alignment.
10970 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10971 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10972
10973 Register VReg1 = MRI->createVirtualRegister(TRC);
10974 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10975 .addReg(VReg1, RegState::Define)
10976 .addConstantPoolIndex(Idx)
10977 .addImm(0)
10978 .add(predOps(ARMCC::AL));
10979 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10980 .addReg(NewVReg1)
10981 .addReg(VReg1, RegState::Kill)
10982 .add(predOps(ARMCC::AL));
10983 }
10984
10985 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10986 .addMBB(TrapBB)
10987 .addImm(ARMCC::HI)
10988 .addReg(ARM::CPSR);
10989
10990 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10991 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10992 .addReg(NewVReg1)
10993 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10994 .add(predOps(ARMCC::AL))
10995 .add(condCodeOp());
10996 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10997 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10998 .addJumpTableIndex(MJTI)
10999 .add(predOps(ARMCC::AL));
11000
11001 MachineMemOperand *JTMMOLd =
11002 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11003 MachineMemOperand::MOLoad, 4, Align(4));
11004 Register NewVReg5 = MRI->createVirtualRegister(TRC);
11005 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
11006 .addReg(NewVReg3, RegState::Kill)
11007 .addReg(NewVReg4)
11008 .addImm(0)
11009 .addMemOperand(JTMMOLd)
11010 .add(predOps(ARMCC::AL));
11011
11012 if (IsPositionIndependent) {
11013 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
11014 .addReg(NewVReg5, RegState::Kill)
11015 .addReg(NewVReg4)
11016 .addJumpTableIndex(MJTI);
11017 } else {
11018 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
11019 .addReg(NewVReg5, RegState::Kill)
11020 .addJumpTableIndex(MJTI);
11021 }
11022 }
11023
11024 // Add the jump table entries as successors to the MBB.
11025 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11026 for (MachineBasicBlock *CurMBB : LPadList) {
11027 if (SeenMBBs.insert(CurMBB).second)
11028 DispContBB->addSuccessor(CurMBB);
11029 }
11030
11031 // N.B. the order the invoke BBs are processed in doesn't matter here.
11032 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11033 SmallVector<MachineBasicBlock*, 64> MBBLPads;
11034 for (MachineBasicBlock *BB : InvokeBBs) {
11035
11036 // Remove the landing pad successor from the invoke block and replace it
11037 // with the new dispatch block.
11038 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11039 while (!Successors.empty()) {
11040 MachineBasicBlock *SMBB = Successors.pop_back_val();
11041 if (SMBB->isEHPad()) {
11042 BB->removeSuccessor(SMBB);
11043 MBBLPads.push_back(SMBB);
11044 }
11045 }
11046
11047 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
11048 BB->normalizeSuccProbs();
11049
11050 // Find the invoke call and mark all of the callee-saved registers as
11051 // 'implicit defined' so that they're spilled. This prevents code from
11052 // moving instructions to before the EH block, where they will never be
11053 // executed.
11054 for (MachineBasicBlock::reverse_iterator
11055 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11056 if (!II->isCall()) continue;
11057
11058 DenseMap<unsigned, bool> DefRegs;
11059 for (MachineInstr::mop_iterator
11060 OI = II->operands_begin(), OE = II->operands_end();
11061 OI != OE; ++OI) {
11062 if (!OI->isReg()) continue;
11063 DefRegs[OI->getReg()] = true;
11064 }
11065
11066 MachineInstrBuilder MIB(*MF, &*II);
11067
11068 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11069 unsigned Reg = SavedRegs[i];
11070 if (Subtarget->isThumb2() &&
11071 !ARM::tGPRRegClass.contains(Reg) &&
11072 !ARM::hGPRRegClass.contains(Reg))
11073 continue;
11074 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11075 continue;
11076 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11077 continue;
11078 if (!DefRegs[Reg])
11079 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
11080 }
11081
11082 break;
11083 }
11084 }
11085
11086 // Mark all former landing pads as non-landing pads. The dispatch is the only
11087 // landing pad now.
11088 for (MachineBasicBlock *MBBLPad : MBBLPads)
11089 MBBLPad->setIsEHPad(false);
11090
11091 // The instruction is gone now.
11092 MI.eraseFromParent();
11093}
11094
11095static
11096MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
11097 for (MachineBasicBlock *S : MBB->successors())
11098 if (S != Succ)
11099 return S;
11100 llvm_unreachable("Expecting a BB with two successors!")::llvm::llvm_unreachable_internal("Expecting a BB with two successors!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11100)
;
11101}
11102
11103/// Return the load opcode for a given load size. If load size >= 8,
11104/// neon opcode will be returned.
11105static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11106 if (LdSize >= 8)
11107 return LdSize == 16 ? ARM::VLD1q32wb_fixed
11108 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11109 if (IsThumb1)
11110 return LdSize == 4 ? ARM::tLDRi
11111 : LdSize == 2 ? ARM::tLDRHi
11112 : LdSize == 1 ? ARM::tLDRBi : 0;
11113 if (IsThumb2)
11114 return LdSize == 4 ? ARM::t2LDR_POST
11115 : LdSize == 2 ? ARM::t2LDRH_POST
11116 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11117 return LdSize == 4 ? ARM::LDR_POST_IMM
11118 : LdSize == 2 ? ARM::LDRH_POST
11119 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11120}
11121
11122/// Return the store opcode for a given store size. If store size >= 8,
11123/// neon opcode will be returned.
11124static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11125 if (StSize >= 8)
11126 return StSize == 16 ? ARM::VST1q32wb_fixed
11127 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11128 if (IsThumb1)
11129 return StSize == 4 ? ARM::tSTRi
11130 : StSize == 2 ? ARM::tSTRHi
11131 : StSize == 1 ? ARM::tSTRBi : 0;
11132 if (IsThumb2)
11133 return StSize == 4 ? ARM::t2STR_POST
11134 : StSize == 2 ? ARM::t2STRH_POST
11135 : StSize == 1 ? ARM::t2STRB_POST : 0;
11136 return StSize == 4 ? ARM::STR_POST_IMM
11137 : StSize == 2 ? ARM::STRH_POST
11138 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11139}
11140
11141/// Emit a post-increment load operation with given size. The instructions
11142/// will be added to BB at Pos.
11143static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11144 const TargetInstrInfo *TII, const DebugLoc &dl,
11145 unsigned LdSize, unsigned Data, unsigned AddrIn,
11146 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11147 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11148 assert(LdOpc != 0 && "Should have a load opcode")(static_cast <bool> (LdOpc != 0 && "Should have a load opcode"
) ? void (0) : __assert_fail ("LdOpc != 0 && \"Should have a load opcode\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11148, __extension__
__PRETTY_FUNCTION__))
;
11149 if (LdSize >= 8) {
11150 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11151 .addReg(AddrOut, RegState::Define)
11152 .addReg(AddrIn)
11153 .addImm(0)
11154 .add(predOps(ARMCC::AL));
11155 } else if (IsThumb1) {
11156 // load + update AddrIn
11157 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11158 .addReg(AddrIn)
11159 .addImm(0)
11160 .add(predOps(ARMCC::AL));
11161 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11162 .add(t1CondCodeOp())
11163 .addReg(AddrIn)
11164 .addImm(LdSize)
11165 .add(predOps(ARMCC::AL));
11166 } else if (IsThumb2) {
11167 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11168 .addReg(AddrOut, RegState::Define)
11169 .addReg(AddrIn)
11170 .addImm(LdSize)
11171 .add(predOps(ARMCC::AL));
11172 } else { // arm
11173 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11174 .addReg(AddrOut, RegState::Define)
11175 .addReg(AddrIn)
11176 .addReg(0)
11177 .addImm(LdSize)
11178 .add(predOps(ARMCC::AL));
11179 }
11180}
11181
11182/// Emit a post-increment store operation with given size. The instructions
11183/// will be added to BB at Pos.
11184static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11185 const TargetInstrInfo *TII, const DebugLoc &dl,
11186 unsigned StSize, unsigned Data, unsigned AddrIn,
11187 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11188 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11189 assert(StOpc != 0 && "Should have a store opcode")(static_cast <bool> (StOpc != 0 && "Should have a store opcode"
) ? void (0) : __assert_fail ("StOpc != 0 && \"Should have a store opcode\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11189, __extension__
__PRETTY_FUNCTION__))
;
11190 if (StSize >= 8) {
11191 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11192 .addReg(AddrIn)
11193 .addImm(0)
11194 .addReg(Data)
11195 .add(predOps(ARMCC::AL));
11196 } else if (IsThumb1) {
11197 // store + update AddrIn
11198 BuildMI(*BB, Pos, dl, TII->get(StOpc))
11199 .addReg(Data)
11200 .addReg(AddrIn)
11201 .addImm(0)
11202 .add(predOps(ARMCC::AL));
11203 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11204 .add(t1CondCodeOp())
11205 .addReg(AddrIn)
11206 .addImm(StSize)
11207 .add(predOps(ARMCC::AL));
11208 } else if (IsThumb2) {
11209 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11210 .addReg(Data)
11211 .addReg(AddrIn)
11212 .addImm(StSize)
11213 .add(predOps(ARMCC::AL));
11214 } else { // arm
11215 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11216 .addReg(Data)
11217 .addReg(AddrIn)
11218 .addReg(0)
11219 .addImm(StSize)
11220 .add(predOps(ARMCC::AL));
11221 }
11222}
11223
11224MachineBasicBlock *
11225ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11226 MachineBasicBlock *BB) const {
11227 // This pseudo instruction has 3 operands: dst, src, size
11228 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11229 // Otherwise, we will generate unrolled scalar copies.
11230 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11231 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11232 MachineFunction::iterator It = ++BB->getIterator();
11233
11234 Register dest = MI.getOperand(0).getReg();
11235 Register src = MI.getOperand(1).getReg();
11236 unsigned SizeVal = MI.getOperand(2).getImm();
11237 unsigned Alignment = MI.getOperand(3).getImm();
11238 DebugLoc dl = MI.getDebugLoc();
11239
11240 MachineFunction *MF = BB->getParent();
11241 MachineRegisterInfo &MRI = MF->getRegInfo();
11242 unsigned UnitSize = 0;
11243 const TargetRegisterClass *TRC = nullptr;
11244 const TargetRegisterClass *VecTRC = nullptr;
11245
11246 bool IsThumb1 = Subtarget->isThumb1Only();
11247 bool IsThumb2 = Subtarget->isThumb2();
11248 bool IsThumb = Subtarget->isThumb();
11249
11250 if (Alignment & 1) {
11251 UnitSize = 1;
11252 } else if (Alignment & 2) {
11253 UnitSize = 2;
11254 } else {
11255 // Check whether we can use NEON instructions.
11256 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11257 Subtarget->hasNEON()) {
11258 if ((Alignment % 16 == 0) && SizeVal >= 16)
11259 UnitSize = 16;
11260 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11261 UnitSize = 8;
11262 }
11263 // Can't use NEON instructions.
11264 if (UnitSize == 0)
11265 UnitSize = 4;
11266 }
11267
11268 // Select the correct opcode and register class for unit size load/store
11269 bool IsNeon = UnitSize >= 8;
11270 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11271 if (IsNeon)
11272 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11273 : UnitSize == 8 ? &ARM::DPRRegClass
11274 : nullptr;
11275
11276 unsigned BytesLeft = SizeVal % UnitSize;
11277 unsigned LoopSize = SizeVal - BytesLeft;
11278
11279 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11280 // Use LDR and STR to copy.
11281 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11282 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11283 unsigned srcIn = src;
11284 unsigned destIn = dest;
11285 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11286 Register srcOut = MRI.createVirtualRegister(TRC);
11287 Register destOut = MRI.createVirtualRegister(TRC);
11288 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11289 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11290 IsThumb1, IsThumb2);
11291 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11292 IsThumb1, IsThumb2);
11293 srcIn = srcOut;
11294 destIn = destOut;
11295 }
11296
11297 // Handle the leftover bytes with LDRB and STRB.
11298 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11299 // [destOut] = STRB_POST(scratch, destIn, 1)
11300 for (unsigned i = 0; i < BytesLeft; i++) {
11301 Register srcOut = MRI.createVirtualRegister(TRC);
11302 Register destOut = MRI.createVirtualRegister(TRC);
11303 Register scratch = MRI.createVirtualRegister(TRC);
11304 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11305 IsThumb1, IsThumb2);
11306 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11307 IsThumb1, IsThumb2);
11308 srcIn = srcOut;
11309 destIn = destOut;
11310 }
11311 MI.eraseFromParent(); // The instruction is gone now.
11312 return BB;
11313 }
11314
11315 // Expand the pseudo op to a loop.
11316 // thisMBB:
11317 // ...
11318 // movw varEnd, # --> with thumb2
11319 // movt varEnd, #
11320 // ldrcp varEnd, idx --> without thumb2
11321 // fallthrough --> loopMBB
11322 // loopMBB:
11323 // PHI varPhi, varEnd, varLoop
11324 // PHI srcPhi, src, srcLoop
11325 // PHI destPhi, dst, destLoop
11326 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11327 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11328 // subs varLoop, varPhi, #UnitSize
11329 // bne loopMBB
11330 // fallthrough --> exitMBB
11331 // exitMBB:
11332 // epilogue to handle left-over bytes
11333 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11334 // [destOut] = STRB_POST(scratch, destLoop, 1)
11335 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11336 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11337 MF->insert(It, loopMBB);
11338 MF->insert(It, exitMBB);
11339
11340 // Transfer the remainder of BB and its successor edges to exitMBB.
11341 exitMBB->splice(exitMBB->begin(), BB,
11342 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11343 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11344
11345 // Load an immediate to varEnd.
11346 Register varEnd = MRI.createVirtualRegister(TRC);
11347 if (Subtarget->useMovt()) {
11348 unsigned Vtmp = varEnd;
11349 if ((LoopSize & 0xFFFF0000) != 0)
11350 Vtmp = MRI.createVirtualRegister(TRC);
11351 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
11352 .addImm(LoopSize & 0xFFFF)
11353 .add(predOps(ARMCC::AL));
11354
11355 if ((LoopSize & 0xFFFF0000) != 0)
11356 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
11357 .addReg(Vtmp)
11358 .addImm(LoopSize >> 16)
11359 .add(predOps(ARMCC::AL));
11360 } else {
11361 MachineConstantPool *ConstantPool = MF->getConstantPool();
11362 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11363 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11364
11365 // MachineConstantPool wants an explicit alignment.
11366 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11367 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11368 MachineMemOperand *CPMMO =
11369 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
11370 MachineMemOperand::MOLoad, 4, Align(4));
11371
11372 if (IsThumb)
11373 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11374 .addReg(varEnd, RegState::Define)
11375 .addConstantPoolIndex(Idx)
11376 .add(predOps(ARMCC::AL))
11377 .addMemOperand(CPMMO);
11378 else
11379 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11380 .addReg(varEnd, RegState::Define)
11381 .addConstantPoolIndex(Idx)
11382 .addImm(0)
11383 .add(predOps(ARMCC::AL))
11384 .addMemOperand(CPMMO);
11385 }
11386 BB->addSuccessor(loopMBB);
11387
11388 // Generate the loop body:
11389 // varPhi = PHI(varLoop, varEnd)
11390 // srcPhi = PHI(srcLoop, src)
11391 // destPhi = PHI(destLoop, dst)
11392 MachineBasicBlock *entryBB = BB;
11393 BB = loopMBB;
11394 Register varLoop = MRI.createVirtualRegister(TRC);
11395 Register varPhi = MRI.createVirtualRegister(TRC);
11396 Register srcLoop = MRI.createVirtualRegister(TRC);
11397 Register srcPhi = MRI.createVirtualRegister(TRC);
11398 Register destLoop = MRI.createVirtualRegister(TRC);
11399 Register destPhi = MRI.createVirtualRegister(TRC);
11400
11401 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11402 .addReg(varLoop).addMBB(loopMBB)
11403 .addReg(varEnd).addMBB(entryBB);
11404 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11405 .addReg(srcLoop).addMBB(loopMBB)
11406 .addReg(src).addMBB(entryBB);
11407 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11408 .addReg(destLoop).addMBB(loopMBB)
11409 .addReg(dest).addMBB(entryBB);
11410
11411 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11412 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11413 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11414 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11415 IsThumb1, IsThumb2);
11416 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11417 IsThumb1, IsThumb2);
11418
11419 // Decrement loop variable by UnitSize.
11420 if (IsThumb1) {
11421 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11422 .add(t1CondCodeOp())
11423 .addReg(varPhi)
11424 .addImm(UnitSize)
11425 .add(predOps(ARMCC::AL));
11426 } else {
11427 MachineInstrBuilder MIB =
11428 BuildMI(*BB, BB->end(), dl,
11429 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11430 MIB.addReg(varPhi)
11431 .addImm(UnitSize)
11432 .add(predOps(ARMCC::AL))
11433 .add(condCodeOp());
11434 MIB->getOperand(5).setReg(ARM::CPSR);
11435 MIB->getOperand(5).setIsDef(true);
11436 }
11437 BuildMI(*BB, BB->end(), dl,
11438 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11439 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11440
11441 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11442 BB->addSuccessor(loopMBB);
11443 BB->addSuccessor(exitMBB);
11444
11445 // Add epilogue to handle BytesLeft.
11446 BB = exitMBB;
11447 auto StartOfExit = exitMBB->begin();
11448
11449 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11450 // [destOut] = STRB_POST(scratch, destLoop, 1)
11451 unsigned srcIn = srcLoop;
11452 unsigned destIn = destLoop;
11453 for (unsigned i = 0; i < BytesLeft; i++) {
11454 Register srcOut = MRI.createVirtualRegister(TRC);
11455 Register destOut = MRI.createVirtualRegister(TRC);
11456 Register scratch = MRI.createVirtualRegister(TRC);
11457 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11458 IsThumb1, IsThumb2);
11459 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11460 IsThumb1, IsThumb2);
11461 srcIn = srcOut;
11462 destIn = destOut;
11463 }
11464
11465 MI.eraseFromParent(); // The instruction is gone now.
11466 return BB;
11467}
11468
11469MachineBasicBlock *
11470ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11471 MachineBasicBlock *MBB) const {
11472 const TargetMachine &TM = getTargetMachine();
11473 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11474 DebugLoc DL = MI.getDebugLoc();
11475
11476 assert(Subtarget->isTargetWindows() &&(static_cast <bool> (Subtarget->isTargetWindows() &&
"__chkstk is only supported on Windows") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"__chkstk is only supported on Windows\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11477, __extension__
__PRETTY_FUNCTION__))
11477 "__chkstk is only supported on Windows")(static_cast <bool> (Subtarget->isTargetWindows() &&
"__chkstk is only supported on Windows") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"__chkstk is only supported on Windows\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11477, __extension__
__PRETTY_FUNCTION__))
;
11478 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode")(static_cast <bool> (Subtarget->isThumb2() &&
"Windows on ARM requires Thumb-2 mode") ? void (0) : __assert_fail
("Subtarget->isThumb2() && \"Windows on ARM requires Thumb-2 mode\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11478, __extension__
__PRETTY_FUNCTION__))
;
11479
11480 // __chkstk takes the number of words to allocate on the stack in R4, and
11481 // returns the stack adjustment in number of bytes in R4. This will not
11482 // clober any other registers (other than the obvious lr).
11483 //
11484 // Although, technically, IP should be considered a register which may be
11485 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11486 // thumb-2 environment, so there is no interworking required. As a result, we
11487 // do not expect a veneer to be emitted by the linker, clobbering IP.
11488 //
11489 // Each module receives its own copy of __chkstk, so no import thunk is
11490 // required, again, ensuring that IP is not clobbered.
11491 //
11492 // Finally, although some linkers may theoretically provide a trampoline for
11493 // out of range calls (which is quite common due to a 32M range limitation of
11494 // branches for Thumb), we can generate the long-call version via
11495 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11496 // IP.
11497
11498 switch (TM.getCodeModel()) {
11499 case CodeModel::Tiny:
11500 llvm_unreachable("Tiny code model not available on ARM.")::llvm::llvm_unreachable_internal("Tiny code model not available on ARM."
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11500)
;
11501 case CodeModel::Small:
11502 case CodeModel::Medium:
11503 case CodeModel::Kernel:
11504 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11505 .add(predOps(ARMCC::AL))
11506 .addExternalSymbol("__chkstk")
11507 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11508 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11509 .addReg(ARM::R12,
11510 RegState::Implicit | RegState::Define | RegState::Dead)
11511 .addReg(ARM::CPSR,
11512 RegState::Implicit | RegState::Define | RegState::Dead);
11513 break;
11514 case CodeModel::Large: {
11515 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11516 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11517
11518 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11519 .addExternalSymbol("__chkstk");
11520 BuildMI(*MBB, MI, DL, TII.get(gettBLXrOpcode(*MBB->getParent())))
11521 .add(predOps(ARMCC::AL))
11522 .addReg(Reg, RegState::Kill)
11523 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11524 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11525 .addReg(ARM::R12,
11526 RegState::Implicit | RegState::Define | RegState::Dead)
11527 .addReg(ARM::CPSR,
11528 RegState::Implicit | RegState::Define | RegState::Dead);
11529 break;
11530 }
11531 }
11532
11533 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11534 .addReg(ARM::SP, RegState::Kill)
11535 .addReg(ARM::R4, RegState::Kill)
11536 .setMIFlags(MachineInstr::FrameSetup)
11537 .add(predOps(ARMCC::AL))
11538 .add(condCodeOp());
11539
11540 MI.eraseFromParent();
11541 return MBB;
11542}
11543
11544MachineBasicBlock *
11545ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11546 MachineBasicBlock *MBB) const {
11547 DebugLoc DL = MI.getDebugLoc();
11548 MachineFunction *MF = MBB->getParent();
11549 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11550
11551 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11552 MF->insert(++MBB->getIterator(), ContBB);
11553 ContBB->splice(ContBB->begin(), MBB,
11554 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11555 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
11556 MBB->addSuccessor(ContBB);
11557
11558 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11559 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11560 MF->push_back(TrapBB);
11561 MBB->addSuccessor(TrapBB);
11562
11563 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11564 .addReg(MI.getOperand(0).getReg())
11565 .addImm(0)
11566 .add(predOps(ARMCC::AL));
11567 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11568 .addMBB(TrapBB)
11569 .addImm(ARMCC::EQ)
11570 .addReg(ARM::CPSR);
11571
11572 MI.eraseFromParent();
11573 return ContBB;
11574}
11575
11576// The CPSR operand of SelectItr might be missing a kill marker
11577// because there were multiple uses of CPSR, and ISel didn't know
11578// which to mark. Figure out whether SelectItr should have had a
11579// kill marker, and set it if it should. Returns the correct kill
11580// marker value.
11581static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
11582 MachineBasicBlock* BB,
11583 const TargetRegisterInfo* TRI) {
11584 // Scan forward through BB for a use/def of CPSR.
11585 MachineBasicBlock::iterator miI(std::next(SelectItr));
11586 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11587 const MachineInstr& mi = *miI;
11588 if (mi.readsRegister(ARM::CPSR))
11589 return false;
11590 if (mi.definesRegister(ARM::CPSR))
11591 break; // Should have kill-flag - update below.
11592 }
11593
11594 // If we hit the end of the block, check whether CPSR is live into a
11595 // successor.
11596 if (miI == BB->end()) {
11597 for (MachineBasicBlock *Succ : BB->successors())
11598 if (Succ->isLiveIn(ARM::CPSR))
11599 return false;
11600 }
11601
11602 // We found a def, or hit the end of the basic block and CPSR wasn't live
11603 // out. SelectMI should have a kill flag on CPSR.
11604 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11605 return true;
11606}
11607
11608/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11609/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11610static Register genTPEntry(MachineBasicBlock *TpEntry,
11611 MachineBasicBlock *TpLoopBody,
11612 MachineBasicBlock *TpExit, Register OpSizeReg,
11613 const TargetInstrInfo *TII, DebugLoc Dl,
11614 MachineRegisterInfo &MRI) {
11615 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11616 Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11617 BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11618 .addUse(OpSizeReg)
11619 .addImm(15)
11620 .add(predOps(ARMCC::AL))
11621 .addReg(0);
11622
11623 Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11624 BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11625 .addUse(AddDestReg, RegState::Kill)
11626 .addImm(4)
11627 .add(predOps(ARMCC::AL))
11628 .addReg(0);
11629
11630 Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11631 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11632 .addUse(LsrDestReg, RegState::Kill);
11633
11634 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11635 .addUse(TotalIterationsReg)
11636 .addMBB(TpExit);
11637
11638 BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11639 .addMBB(TpLoopBody)
11640 .add(predOps(ARMCC::AL));
11641
11642 return TotalIterationsReg;
11643}
11644
11645/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11646/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11647/// loops.
11648static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11649 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11650 const TargetInstrInfo *TII, DebugLoc Dl,
11651 MachineRegisterInfo &MRI, Register OpSrcReg,
11652 Register OpDestReg, Register ElementCountReg,
11653 Register TotalIterationsReg, bool IsMemcpy) {
11654 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11655 // array, loop iteration counter, predication counter.
11656
11657 Register SrcPhiReg, CurrSrcReg;
11658 if (IsMemcpy) {
11659 // Current position in the src array
11660 SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11661 CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11662 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11663 .addUse(OpSrcReg)
11664 .addMBB(TpEntry)
11665 .addUse(CurrSrcReg)
11666 .addMBB(TpLoopBody);
11667 }
11668
11669 // Current position in the dest array
11670 Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11671 Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11672 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11673 .addUse(OpDestReg)
11674 .addMBB(TpEntry)
11675 .addUse(CurrDestReg)
11676 .addMBB(TpLoopBody);
11677
11678 // Current loop counter
11679 Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11680 Register RemainingLoopIterationsReg =
11681 MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11682 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11683 .addUse(TotalIterationsReg)
11684 .addMBB(TpEntry)
11685 .addUse(RemainingLoopIterationsReg)
11686 .addMBB(TpLoopBody);
11687
11688 // Predication counter
11689 Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11690 Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11691 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11692 .addUse(ElementCountReg)
11693 .addMBB(TpEntry)
11694 .addUse(RemainingElementsReg)
11695 .addMBB(TpLoopBody);
11696
11697 // Pass predication counter to VCTP
11698 Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11699 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11700 .addUse(PredCounterPhiReg)
11701 .addImm(ARMVCC::None)
11702 .addReg(0)
11703 .addReg(0);
11704
11705 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
11706 .addUse(PredCounterPhiReg)
11707 .addImm(16)
11708 .add(predOps(ARMCC::AL))
11709 .addReg(0);
11710
11711 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11712 Register SrcValueReg;
11713 if (IsMemcpy) {
11714 SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
11715 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
11716 .addDef(CurrSrcReg)
11717 .addDef(SrcValueReg)
11718 .addReg(SrcPhiReg)
11719 .addImm(16)
11720 .addImm(ARMVCC::Then)
11721 .addUse(VccrReg)
11722 .addReg(0);
11723 } else
11724 SrcValueReg = OpSrcReg;
11725
11726 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
11727 .addDef(CurrDestReg)
11728 .addUse(SrcValueReg)
11729 .addReg(DestPhiReg)
11730 .addImm(16)
11731 .addImm(ARMVCC::Then)
11732 .addUse(VccrReg)
11733 .addReg(0);
11734
11735 // Add the pseudoInstrs for decrementing the loop counter and marking the
11736 // end:t2DoLoopDec and t2DoLoopEnd
11737 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
11738 .addUse(LoopCounterPhiReg)
11739 .addImm(1);
11740
11741 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
11742 .addUse(RemainingLoopIterationsReg)
11743 .addMBB(TpLoopBody);
11744
11745 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
11746 .addMBB(TpExit)
11747 .add(predOps(ARMCC::AL));
11748}
11749
11750MachineBasicBlock *
11751ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11752 MachineBasicBlock *BB) const {
11753 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11754 DebugLoc dl = MI.getDebugLoc();
11755 bool isThumb2 = Subtarget->isThumb2();
11756 switch (MI.getOpcode()) {
11757 default: {
11758 MI.print(errs());
11759 llvm_unreachable("Unexpected instr type to insert")::llvm::llvm_unreachable_internal("Unexpected instr type to insert"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11759)
;
11760 }
11761
11762 // Thumb1 post-indexed loads are really just single-register LDMs.
11763 case ARM::tLDR_postidx: {
11764 MachineOperand Def(MI.getOperand(1));
11765 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11766 .add(Def) // Rn_wb
11767 .add(MI.getOperand(2)) // Rn
11768 .add(MI.getOperand(3)) // PredImm
11769 .add(MI.getOperand(4)) // PredReg
11770 .add(MI.getOperand(0)) // Rt
11771 .cloneMemRefs(MI);
11772 MI.eraseFromParent();
11773 return BB;
11774 }
11775
11776 case ARM::MVE_MEMCPYLOOPINST:
11777 case ARM::MVE_MEMSETLOOPINST: {
11778
11779 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11780 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11781 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11782 // adds the relevant instructions in the TP loop Body for generation of a
11783 // WLSTP loop.
11784
11785 // Below is relevant portion of the CFG after the transformation.
11786 // The Machine Basic Blocks are shown along with branch conditions (in
11787 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11788 // portion of the CFG and may not necessarily be the entry/exit of the
11789 // function.
11790
11791 // (Relevant) CFG after transformation:
11792 // TP entry MBB
11793 // |
11794 // |-----------------|
11795 // (n <= 0) (n > 0)
11796 // | |
11797 // | TP loop Body MBB<--|
11798 // | | |
11799 // \ |___________|
11800 // \ /
11801 // TP exit MBB
11802
11803 MachineFunction *MF = BB->getParent();
11804 MachineFunctionProperties &Properties = MF->getProperties();
11805 MachineRegisterInfo &MRI = MF->getRegInfo();
11806
11807 Register OpDestReg = MI.getOperand(0).getReg();
11808 Register OpSrcReg = MI.getOperand(1).getReg();
11809 Register OpSizeReg = MI.getOperand(2).getReg();
11810
11811 // Allocate the required MBBs and add to parent function.
11812 MachineBasicBlock *TpEntry = BB;
11813 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
11814 MachineBasicBlock *TpExit;
11815
11816 MF->push_back(TpLoopBody);
11817
11818 // If any instructions are present in the current block after
11819 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
11820 // move the instructions into the newly created exit block. If there are no
11821 // instructions add an explicit branch to the FallThrough block and then
11822 // split.
11823 //
11824 // The split is required for two reasons:
11825 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
11826 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
11827 // need to be updated. splitAt() already handles this.
11828 TpExit = BB->splitAt(MI, false);
11829 if (TpExit == BB) {
11830 assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "(static_cast <bool> (BB->canFallThrough() &&
"Exit Block must be Fallthrough of the " "block containing memcpy/memset Pseudo"
) ? void (0) : __assert_fail ("BB->canFallThrough() && \"Exit Block must be Fallthrough of the \" \"block containing memcpy/memset Pseudo\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11831, __extension__
__PRETTY_FUNCTION__))
11831 "block containing memcpy/memset Pseudo")(static_cast <bool> (BB->canFallThrough() &&
"Exit Block must be Fallthrough of the " "block containing memcpy/memset Pseudo"
) ? void (0) : __assert_fail ("BB->canFallThrough() && \"Exit Block must be Fallthrough of the \" \"block containing memcpy/memset Pseudo\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 11831, __extension__
__PRETTY_FUNCTION__))
;
11832 TpExit = BB->getFallThrough();
11833 BuildMI(BB, dl, TII->get(ARM::t2B))
11834 .addMBB(TpExit)
11835 .add(predOps(ARMCC::AL));
11836 TpExit = BB->splitAt(MI, false);
11837 }
11838
11839 // Add logic for iteration count
11840 Register TotalIterationsReg =
11841 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
11842
11843 // Add the vectorized (and predicated) loads/store instructions
11844 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
11845 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
11846 OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
11847
11848 // Required to avoid conflict with the MachineVerifier during testing.
11849 Properties.reset(MachineFunctionProperties::Property::NoPHIs);
11850
11851 // Connect the blocks
11852 TpEntry->addSuccessor(TpLoopBody);
11853 TpLoopBody->addSuccessor(TpLoopBody);
11854 TpLoopBody->addSuccessor(TpExit);
11855
11856 // Reorder for a more natural layout
11857 TpLoopBody->moveAfter(TpEntry);
11858 TpExit->moveAfter(TpLoopBody);
11859
11860 // Finally, remove the memcpy Psuedo Instruction
11861 MI.eraseFromParent();
11862
11863 // Return the exit block as it may contain other instructions requiring a
11864 // custom inserter
11865 return TpExit;
11866 }
11867
11868 // The Thumb2 pre-indexed stores have the same MI operands, they just
11869 // define them differently in the .td files from the isel patterns, so
11870 // they need pseudos.
11871 case ARM::t2STR_preidx:
11872 MI.setDesc(TII->get(ARM::t2STR_PRE));
11873 return BB;
11874 case ARM::t2STRB_preidx:
11875 MI.setDesc(TII->get(ARM::t2STRB_PRE));
11876 return BB;
11877 case ARM::t2STRH_preidx:
11878 MI.setDesc(TII->get(ARM::t2STRH_PRE));
11879 return BB;
11880
11881 case ARM::STRi_preidx:
11882 case ARM::STRBi_preidx: {
11883 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
11884 : ARM::STRB_PRE_IMM;
11885 // Decode the offset.
11886 unsigned Offset = MI.getOperand(4).getImm();
11887 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
11888 Offset = ARM_AM::getAM2Offset(Offset);
11889 if (isSub)
11890 Offset = -Offset;
11891
11892 MachineMemOperand *MMO = *MI.memoperands_begin();
11893 BuildMI(*BB, MI, dl, TII->get(NewOpc))
11894 .add(MI.getOperand(0)) // Rn_wb
11895 .add(MI.getOperand(1)) // Rt
11896 .add(MI.getOperand(2)) // Rn
11897 .addImm(Offset) // offset (skip GPR==zero_reg)
11898 .add(MI.getOperand(5)) // pred
11899 .add(MI.getOperand(6))
11900 .addMemOperand(MMO);
11901 MI.eraseFromParent();
11902 return BB;
11903 }
11904 case ARM::STRr_preidx:
11905 case ARM::STRBr_preidx:
11906 case ARM::STRH_preidx: {
11907 unsigned NewOpc;
11908 switch (MI.getOpcode()) {
11909 default: llvm_unreachable("unexpected opcode!")::llvm::llvm_unreachable_internal("unexpected opcode!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11909)
;
11910 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
11911 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
11912 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
11913 }
11914 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
11915 for (const MachineOperand &MO : MI.operands())
11916 MIB.add(MO);
11917 MI.eraseFromParent();
11918 return BB;
11919 }
11920
11921 case ARM::tMOVCCr_pseudo: {
11922 // To "insert" a SELECT_CC instruction, we actually have to insert the
11923 // diamond control-flow pattern. The incoming instruction knows the
11924 // destination vreg to set, the condition code register to branch on, the
11925 // true/false values to select between, and a branch opcode to use.
11926 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11927 MachineFunction::iterator It = ++BB->getIterator();
11928
11929 // thisMBB:
11930 // ...
11931 // TrueVal = ...
11932 // cmpTY ccX, r1, r2
11933 // bCC copy1MBB
11934 // fallthrough --> copy0MBB
11935 MachineBasicBlock *thisMBB = BB;
11936 MachineFunction *F = BB->getParent();
11937 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11938 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11939 F->insert(It, copy0MBB);
11940 F->insert(It, sinkMBB);
11941
11942 // Check whether CPSR is live past the tMOVCCr_pseudo.
11943 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
11944 if (!MI.killsRegister(ARM::CPSR) &&
11945 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
11946 copy0MBB->addLiveIn(ARM::CPSR);
11947 sinkMBB->addLiveIn(ARM::CPSR);
11948 }
11949
11950 // Transfer the remainder of BB and its successor edges to sinkMBB.
11951 sinkMBB->splice(sinkMBB->begin(), BB,
11952 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11953 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11954
11955 BB->addSuccessor(copy0MBB);
11956 BB->addSuccessor(sinkMBB);
11957
11958 BuildMI(BB, dl, TII->get(ARM::tBcc))
11959 .addMBB(sinkMBB)
11960 .addImm(MI.getOperand(3).getImm())
11961 .addReg(MI.getOperand(4).getReg());
11962
11963 // copy0MBB:
11964 // %FalseValue = ...
11965 // # fallthrough to sinkMBB
11966 BB = copy0MBB;
11967
11968 // Update machine-CFG edges
11969 BB->addSuccessor(sinkMBB);
11970
11971 // sinkMBB:
11972 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11973 // ...
11974 BB = sinkMBB;
11975 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
11976 .addReg(MI.getOperand(1).getReg())
11977 .addMBB(copy0MBB)
11978 .addReg(MI.getOperand(2).getReg())
11979 .addMBB(thisMBB);
11980
11981 MI.eraseFromParent(); // The pseudo instruction is gone now.
11982 return BB;
11983 }
11984
11985 case ARM::BCCi64:
11986 case ARM::BCCZi64: {
11987 // If there is an unconditional branch to the other successor, remove it.
11988 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
11989
11990 // Compare both parts that make up the double comparison separately for
11991 // equality.
11992 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
11993
11994 Register LHS1 = MI.getOperand(1).getReg();
11995 Register LHS2 = MI.getOperand(2).getReg();
11996 if (RHSisZero) {
11997 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11998 .addReg(LHS1)
11999 .addImm(0)
12000 .add(predOps(ARMCC::AL));
12001 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12002 .addReg(LHS2).addImm(0)
12003 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12004 } else {
12005 Register RHS1 = MI.getOperand(3).getReg();
12006 Register RHS2 = MI.getOperand(4).getReg();
12007 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12008 .addReg(LHS1)
12009 .addReg(RHS1)
12010 .add(predOps(ARMCC::AL));
12011 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12012 .addReg(LHS2).addReg(RHS2)
12013 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12014 }
12015
12016 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
12017 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
12018 if (MI.getOperand(0).getImm() == ARMCC::NE)
12019 std::swap(destMBB, exitMBB);
12020
12021 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12022 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
12023 if (isThumb2)
12024 BuildMI(BB, dl, TII->get(ARM::t2B))
12025 .addMBB(exitMBB)
12026 .add(predOps(ARMCC::AL));
12027 else
12028 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
12029
12030 MI.eraseFromParent(); // The pseudo instruction is gone now.
12031 return BB;
12032 }
12033
12034 case ARM::Int_eh_sjlj_setjmp:
12035 case ARM::Int_eh_sjlj_setjmp_nofp:
12036 case ARM::tInt_eh_sjlj_setjmp:
12037 case ARM::t2Int_eh_sjlj_setjmp:
12038 case ARM::t2Int_eh_sjlj_setjmp_nofp:
12039 return BB;
12040
12041 case ARM::Int_eh_sjlj_setup_dispatch:
12042 EmitSjLjDispatchBlock(MI, BB);
12043 return BB;
12044
12045 case ARM::ABS:
12046 case ARM::t2ABS: {
12047 // To insert an ABS instruction, we have to insert the
12048 // diamond control-flow pattern. The incoming instruction knows the
12049 // source vreg to test against 0, the destination vreg to set,
12050 // the condition code register to branch on, the
12051 // true/false values to select between, and a branch opcode to use.
12052 // It transforms
12053 // V1 = ABS V0
12054 // into
12055 // V2 = MOVS V0
12056 // BCC (branch to SinkBB if V0 >= 0)
12057 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
12058 // SinkBB: V1 = PHI(V2, V3)
12059 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12060 MachineFunction::iterator BBI = ++BB->getIterator();
12061 MachineFunction *Fn = BB->getParent();
12062 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
12063 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
12064 Fn->insert(BBI, RSBBB);
12065 Fn->insert(BBI, SinkBB);
12066
12067 Register ABSSrcReg = MI.getOperand(1).getReg();
12068 Register ABSDstReg = MI.getOperand(0).getReg();
12069 bool ABSSrcKIll = MI.getOperand(1).isKill();
12070 bool isThumb2 = Subtarget->isThumb2();
12071 MachineRegisterInfo &MRI = Fn->getRegInfo();
12072 // In Thumb mode S must not be specified if source register is the SP or
12073 // PC and if destination register is the SP, so restrict register class
12074 Register NewRsbDstReg = MRI.createVirtualRegister(
12075 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
12076
12077 // Transfer the remainder of BB and its successor edges to sinkMBB.
12078 SinkBB->splice(SinkBB->begin(), BB,
12079 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12080 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
12081
12082 BB->addSuccessor(RSBBB);
12083 BB->addSuccessor(SinkBB);
12084
12085 // fall through to SinkMBB
12086 RSBBB->addSuccessor(SinkBB);
12087
12088 // insert a cmp at the end of BB
12089 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12090 .addReg(ABSSrcReg)
12091 .addImm(0)
12092 .add(predOps(ARMCC::AL));
12093
12094 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
12095 BuildMI(BB, dl,
12096 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
12097 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
12098
12099 // insert rsbri in RSBBB
12100 // Note: BCC and rsbri will be converted into predicated rsbmi
12101 // by if-conversion pass
12102 BuildMI(*RSBBB, RSBBB->begin(), dl,
12103 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
12104 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
12105 .addImm(0)
12106 .add(predOps(ARMCC::AL))
12107 .add(condCodeOp());
12108
12109 // insert PHI in SinkBB,
12110 // reuse ABSDstReg to not change uses of ABS instruction
12111 BuildMI(*SinkBB, SinkBB->begin(), dl,
12112 TII->get(ARM::PHI), ABSDstReg)
12113 .addReg(NewRsbDstReg).addMBB(RSBBB)
12114 .addReg(ABSSrcReg).addMBB(BB);
12115
12116 // remove ABS instruction
12117 MI.eraseFromParent();
12118
12119 // return last added BB
12120 return SinkBB;
12121 }
12122 case ARM::COPY_STRUCT_BYVAL_I32:
12123 ++NumLoopByVals;
12124 return EmitStructByval(MI, BB);
12125 case ARM::WIN__CHKSTK:
12126 return EmitLowered__chkstk(MI, BB);
12127 case ARM::WIN__DBZCHK:
12128 return EmitLowered__dbzchk(MI, BB);
12129 }
12130}
12131
12132/// Attaches vregs to MEMCPY that it will use as scratch registers
12133/// when it is expanded into LDM/STM. This is done as a post-isel lowering
12134/// instead of as a custom inserter because we need the use list from the SDNode.
12135static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
12136 MachineInstr &MI, const SDNode *Node) {
12137 bool isThumb1 = Subtarget->isThumb1Only();
12138
12139 DebugLoc DL = MI.getDebugLoc();
12140 MachineFunction *MF = MI.getParent()->getParent();
12141 MachineRegisterInfo &MRI = MF->getRegInfo();
12142 MachineInstrBuilder MIB(*MF, MI);
12143
12144 // If the new dst/src is unused mark it as dead.
12145 if (!Node->hasAnyUseOfValue(0)) {
12146 MI.getOperand(0).setIsDead(true);
12147 }
12148 if (!Node->hasAnyUseOfValue(1)) {
12149 MI.getOperand(1).setIsDead(true);
12150 }
12151
12152 // The MEMCPY both defines and kills the scratch registers.
12153 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
12154 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
12155 : &ARM::GPRRegClass);
12156 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
12157 }
12158}
12159
12160void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
12161 SDNode *Node) const {
12162 if (MI.getOpcode() == ARM::MEMCPY) {
12163 attachMEMCPYScratchRegs(Subtarget, MI, Node);
12164 return;
12165 }
12166
12167 const MCInstrDesc *MCID = &MI.getDesc();
12168 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12169 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12170 // operand is still set to noreg. If needed, set the optional operand's
12171 // register to CPSR, and remove the redundant implicit def.
12172 //
12173 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12174
12175 // Rename pseudo opcodes.
12176 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
12177 unsigned ccOutIdx;
12178 if (NewOpc) {
12179 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12180 MCID = &TII->get(NewOpc);
12181
12182 assert(MCID->getNumOperands() ==(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12185, __extension__
__PRETTY_FUNCTION__))
12183 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12185, __extension__
__PRETTY_FUNCTION__))
12184 && "converted opcode should be the same except for cc_out"(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12185, __extension__
__PRETTY_FUNCTION__))
12185 " (and, on Thumb1, pred)")(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12185, __extension__
__PRETTY_FUNCTION__))
;
12186
12187 MI.setDesc(*MCID);
12188
12189 // Add the optional cc_out operand
12190 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12191
12192 // On Thumb1, move all input operands to the end, then add the predicate
12193 if (Subtarget->isThumb1Only()) {
12194 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12195 MI.addOperand(MI.getOperand(1));
12196 MI.removeOperand(1);
12197 }
12198
12199 // Restore the ties
12200 for (unsigned i = MI.getNumOperands(); i--;) {
12201 const MachineOperand& op = MI.getOperand(i);
12202 if (op.isReg() && op.isUse()) {
12203 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12204 if (DefIdx != -1)
12205 MI.tieOperands(DefIdx, i);
12206 }
12207 }
12208
12209 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
12210 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12211 ccOutIdx = 1;
12212 } else
12213 ccOutIdx = MCID->getNumOperands() - 1;
12214 } else
12215 ccOutIdx = MCID->getNumOperands() - 1;
12216
12217 // Any ARM instruction that sets the 's' bit should specify an optional
12218 // "cc_out" operand in the last operand position.
12219 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
12220 assert(!NewOpc && "Optional cc_out operand required")(static_cast <bool> (!NewOpc && "Optional cc_out operand required"
) ? void (0) : __assert_fail ("!NewOpc && \"Optional cc_out operand required\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12220, __extension__
__PRETTY_FUNCTION__))
;
12221 return;
12222 }
12223 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12224 // since we already have an optional CPSR def.
12225 bool definesCPSR = false;
12226 bool deadCPSR = false;
12227 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12228 ++i) {
12229 const MachineOperand &MO = MI.getOperand(i);
12230 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12231 definesCPSR = true;
12232 if (MO.isDead())
12233 deadCPSR = true;
12234 MI.removeOperand(i);
12235 break;
12236 }
12237 }
12238 if (!definesCPSR) {
12239 assert(!NewOpc && "Optional cc_out operand required")(static_cast <bool> (!NewOpc && "Optional cc_out operand required"
) ? void (0) : __assert_fail ("!NewOpc && \"Optional cc_out operand required\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12239, __extension__
__PRETTY_FUNCTION__))
;
12240 return;
12241 }
12242 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag")(static_cast <bool> (deadCPSR == !Node->hasAnyUseOfValue
(1) && "inconsistent dead flag") ? void (0) : __assert_fail
("deadCPSR == !Node->hasAnyUseOfValue(1) && \"inconsistent dead flag\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12242, __extension__
__PRETTY_FUNCTION__))
;
12243 if (deadCPSR) {
12244 assert(!MI.getOperand(ccOutIdx).getReg() &&(static_cast <bool> (!MI.getOperand(ccOutIdx).getReg() &&
"expect uninitialized optional cc_out operand") ? void (0) :
__assert_fail ("!MI.getOperand(ccOutIdx).getReg() && \"expect uninitialized optional cc_out operand\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12245, __extension__
__PRETTY_FUNCTION__))
12245 "expect uninitialized optional cc_out operand")(static_cast <bool> (!MI.getOperand(ccOutIdx).getReg() &&
"expect uninitialized optional cc_out operand") ? void (0) :
__assert_fail ("!MI.getOperand(ccOutIdx).getReg() && \"expect uninitialized optional cc_out operand\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12245, __extension__
__PRETTY_FUNCTION__))
;
12246 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12247 if (!Subtarget->isThumb1Only())
12248 return;
12249 }
12250
12251 // If this instruction was defined with an optional CPSR def and its dag node
12252 // had a live implicit CPSR def, then activate the optional CPSR def.
12253 MachineOperand &MO = MI.getOperand(ccOutIdx);
12254 MO.setReg(ARM::CPSR);
12255 MO.setIsDef(true);
12256}
12257
12258//===----------------------------------------------------------------------===//
12259// ARM Optimization Hooks
12260//===----------------------------------------------------------------------===//
12261
12262// Helper function that checks if N is a null or all ones constant.
12263static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12264 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
12265}
12266
12267// Return true if N is conditionally 0 or all ones.
12268// Detects these expressions where cc is an i1 value:
12269//
12270// (select cc 0, y) [AllOnes=0]
12271// (select cc y, 0) [AllOnes=0]
12272// (zext cc) [AllOnes=0]
12273// (sext cc) [AllOnes=0/1]
12274// (select cc -1, y) [AllOnes=1]
12275// (select cc y, -1) [AllOnes=1]
12276//
12277// Invert is set when N is the null/all ones constant when CC is false.
12278// OtherOp is set to the alternative value of N.
12279static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
12280 SDValue &CC, bool &Invert,
12281 SDValue &OtherOp,
12282 SelectionDAG &DAG) {
12283 switch (N->getOpcode()) {
12284 default: return false;
12285 case ISD::SELECT: {
12286 CC = N->getOperand(0);
12287 SDValue N1 = N->getOperand(1);
12288 SDValue N2 = N->getOperand(2);
12289 if (isZeroOrAllOnes(N1, AllOnes)) {
12290 Invert = false;
12291 OtherOp = N2;
12292 return true;
12293 }
12294 if (isZeroOrAllOnes(N2, AllOnes)) {
12295 Invert = true;
12296 OtherOp = N1;
12297 return true;
12298 }
12299 return false;
12300 }
12301 case ISD::ZERO_EXTEND:
12302 // (zext cc) can never be the all ones value.
12303 if (AllOnes)
12304 return false;
12305 [[fallthrough]];
12306 case ISD::SIGN_EXTEND: {
12307 SDLoc dl(N);
12308 EVT VT = N->getValueType(0);
12309 CC = N->getOperand(0);
12310 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12311 return false;
12312 Invert = !AllOnes;
12313 if (AllOnes)
12314 // When looking for an AllOnes constant, N is an sext, and the 'other'
12315 // value is 0.
12316 OtherOp = DAG.getConstant(0, dl, VT);
12317 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12318 // When looking for a 0 constant, N can be zext or sext.
12319 OtherOp = DAG.getConstant(1, dl, VT);
12320 else
12321 OtherOp = DAG.getAllOnesConstant(dl, VT);
12322 return true;
12323 }
12324 }
12325}
12326
12327// Combine a constant select operand into its use:
12328//
12329// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12330// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12331// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12332// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12333// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12334//
12335// The transform is rejected if the select doesn't have a constant operand that
12336// is null, or all ones when AllOnes is set.
12337//
12338// Also recognize sext/zext from i1:
12339//
12340// (add (zext cc), x) -> (select cc (add x, 1), x)
12341// (add (sext cc), x) -> (select cc (add x, -1), x)
12342//
12343// These transformations eventually create predicated instructions.
12344//
12345// @param N The node to transform.
12346// @param Slct The N operand that is a select.
12347// @param OtherOp The other N operand (x above).
12348// @param DCI Context.
12349// @param AllOnes Require the select constant to be all ones instead of null.
12350// @returns The new node, or SDValue() on failure.
12351static
12352SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
12353 TargetLowering::DAGCombinerInfo &DCI,
12354 bool AllOnes = false) {
12355 SelectionDAG &DAG = DCI.DAG;
12356 EVT VT = N->getValueType(0);
12357 SDValue NonConstantVal;
12358 SDValue CCOp;
12359 bool SwapSelectOps;
12360 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12361 NonConstantVal, DAG))
12362 return SDValue();
12363
12364 // Slct is now know to be the desired identity constant when CC is true.
12365 SDValue TrueVal = OtherOp;
12366 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12367 OtherOp, NonConstantVal);
12368 // Unless SwapSelectOps says CC should be false.
12369 if (SwapSelectOps)
12370 std::swap(TrueVal, FalseVal);
12371
12372 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12373 CCOp, TrueVal, FalseVal);
12374}
12375
12376// Attempt combineSelectAndUse on each operand of a commutative operator N.
12377static
12378SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
12379 TargetLowering::DAGCombinerInfo &DCI) {
12380 SDValue N0 = N->getOperand(0);
12381 SDValue N1 = N->getOperand(1);
12382 if (N0.getNode()->hasOneUse())
12383 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12384 return Result;
12385 if (N1.getNode()->hasOneUse())
12386 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12387 return Result;
12388 return SDValue();
12389}
12390
12391static bool IsVUZPShuffleNode(SDNode *N) {
12392 // VUZP shuffle node.
12393 if (N->getOpcode() == ARMISD::VUZP)
12394 return true;
12395
12396 // "VUZP" on i32 is an alias for VTRN.
12397 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12398 return true;
12399
12400 return false;
12401}
12402
12403static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
12404 TargetLowering::DAGCombinerInfo &DCI,
12405 const ARMSubtarget *Subtarget) {
12406 // Look for ADD(VUZP.0, VUZP.1).
12407 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12408 N0 == N1)
12409 return SDValue();
12410
12411 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12412 if (!N->getValueType(0).is64BitVector())
12413 return SDValue();
12414
12415 // Generate vpadd.
12416 SelectionDAG &DAG = DCI.DAG;
12417 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12418 SDLoc dl(N);
12419 SDNode *Unzip = N0.getNode();
12420 EVT VT = N->getValueType(0);
12421
12422 SmallVector<SDValue, 8> Ops;
12423 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12424 TLI.getPointerTy(DAG.getDataLayout())));
12425 Ops.push_back(Unzip->getOperand(0));
12426 Ops.push_back(Unzip->getOperand(1));
12427
12428 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12429}
12430
12431static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12432 TargetLowering::DAGCombinerInfo &DCI,
12433 const ARMSubtarget *Subtarget) {
12434 // Check for two extended operands.
12435 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12436 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12437 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12438 N1.getOpcode() == ISD::ZERO_EXTEND))
12439 return SDValue();
12440
12441 SDValue N00 = N0.getOperand(0);
12442 SDValue N10 = N1.getOperand(0);
12443
12444 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12445 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12446 N00 == N10)
12447 return SDValue();
12448
12449 // We only recognize Q register paddl here; this can't be reached until
12450 // after type legalization.
12451 if (!N00.getValueType().is64BitVector() ||
12452 !N0.getValueType().is128BitVector())
12453 return SDValue();
12454
12455 // Generate vpaddl.
12456 SelectionDAG &DAG = DCI.DAG;
12457 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12458 SDLoc dl(N);
12459 EVT VT = N->getValueType(0);
12460
12461 SmallVector<SDValue, 8> Ops;
12462 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12463 unsigned Opcode;
12464 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12465 Opcode = Intrinsic::arm_neon_vpaddls;
12466 else
12467 Opcode = Intrinsic::arm_neon_vpaddlu;
12468 Ops.push_back(DAG.getConstant(Opcode, dl,
12469 TLI.getPointerTy(DAG.getDataLayout())));
12470 EVT ElemTy = N00.getValueType().getVectorElementType();
12471 unsigned NumElts = VT.getVectorNumElements();
12472 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12473 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12474 N00.getOperand(0), N00.getOperand(1));
12475 Ops.push_back(Concat);
12476
12477 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12478}
12479
12480// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12481// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12482// much easier to match.
12483static SDValue
12484AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12485 TargetLowering::DAGCombinerInfo &DCI,
12486 const ARMSubtarget *Subtarget) {
12487 // Only perform optimization if after legalize, and if NEON is available. We
12488 // also expected both operands to be BUILD_VECTORs.
12489 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12490 || N0.getOpcode() != ISD::BUILD_VECTOR
12491 || N1.getOpcode() != ISD::BUILD_VECTOR)
12492 return SDValue();
12493
12494 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12495 EVT VT = N->getValueType(0);
12496 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12497 return SDValue();
12498
12499 // Check that the vector operands are of the right form.
12500 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12501 // operands, where N is the size of the formed vector.
12502 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12503 // index such that we have a pair wise add pattern.
12504
12505 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12506 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12507 return SDValue();
12508 SDValue Vec = N0->getOperand(0)->getOperand(0);
12509 SDNode *V = Vec.getNode();
12510 unsigned nextIndex = 0;
12511
12512 // For each operands to the ADD which are BUILD_VECTORs,
12513 // check to see if each of their operands are an EXTRACT_VECTOR with
12514 // the same vector and appropriate index.
12515 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12516 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
12517 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12518
12519 SDValue ExtVec0 = N0->getOperand(i);
12520 SDValue ExtVec1 = N1->getOperand(i);
12521
12522 // First operand is the vector, verify its the same.
12523 if (V != ExtVec0->getOperand(0).getNode() ||
12524 V != ExtVec1->getOperand(0).getNode())
12525 return SDValue();
12526
12527 // Second is the constant, verify its correct.
12528 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
12529 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
12530
12531 // For the constant, we want to see all the even or all the odd.
12532 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12533 || C1->getZExtValue() != nextIndex+1)
12534 return SDValue();
12535
12536 // Increment index.
12537 nextIndex+=2;
12538 } else
12539 return SDValue();
12540 }
12541
12542 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12543 // we're using the entire input vector, otherwise there's a size/legality
12544 // mismatch somewhere.
12545 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12546 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
12547 return SDValue();
12548
12549 // Create VPADDL node.
12550 SelectionDAG &DAG = DCI.DAG;
12551 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12552
12553 SDLoc dl(N);
12554
12555 // Build operand list.
12556 SmallVector<SDValue, 8> Ops;
12557 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12558 TLI.getPointerTy(DAG.getDataLayout())));
12559
12560 // Input is the vector.
12561 Ops.push_back(Vec);
12562
12563 // Get widened type and narrowed type.
12564 MVT widenType;
12565 unsigned numElem = VT.getVectorNumElements();
12566
12567 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12568 switch (inputLaneType.getSimpleVT().SimpleTy) {
12569 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12570 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12571 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12572 default:
12573 llvm_unreachable("Invalid vector element type for padd optimization.")::llvm::llvm_unreachable_internal("Invalid vector element type for padd optimization."
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12573)
;
12574 }
12575
12576 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12577 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12578 return DAG.getNode(ExtOp, dl, VT, tmp);
12579}
12580
12581static SDValue findMUL_LOHI(SDValue V) {
12582 if (V->getOpcode() == ISD::UMUL_LOHI ||
12583 V->getOpcode() == ISD::SMUL_LOHI)
12584 return V;
12585 return SDValue();
12586}
12587
12588static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12589 TargetLowering::DAGCombinerInfo &DCI,
12590 const ARMSubtarget *Subtarget) {
12591 if (!Subtarget->hasBaseDSP())
12592 return SDValue();
12593
12594 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12595 // accumulates the product into a 64-bit value. The 16-bit values will
12596 // be sign extended somehow or SRA'd into 32-bit values
12597 // (addc (adde (mul 16bit, 16bit), lo), hi)
12598 SDValue Mul = AddcNode->getOperand(0);
12599 SDValue Lo = AddcNode->getOperand(1);
12600 if (Mul.getOpcode() != ISD::MUL) {
12601 Lo = AddcNode->getOperand(0);
12602 Mul = AddcNode->getOperand(1);
12603 if (Mul.getOpcode() != ISD::MUL)
12604 return SDValue();
12605 }
12606
12607 SDValue SRA = AddeNode->getOperand(0);
12608 SDValue Hi = AddeNode->getOperand(1);
12609 if (SRA.getOpcode() != ISD::SRA) {
12610 SRA = AddeNode->getOperand(1);
12611 Hi = AddeNode->getOperand(0);
12612 if (SRA.getOpcode() != ISD::SRA)
12613 return SDValue();
12614 }
12615 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12616 if (Const->getZExtValue() != 31)
12617 return SDValue();
12618 } else
12619 return SDValue();
12620
12621 if (SRA.getOperand(0) != Mul)
12622 return SDValue();
12623
12624 SelectionDAG &DAG = DCI.DAG;
12625 SDLoc dl(AddcNode);
12626 unsigned Opcode = 0;
12627 SDValue Op0;
12628 SDValue Op1;
12629
12630 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12631 Opcode = ARMISD::SMLALBB;
12632 Op0 = Mul.getOperand(0);
12633 Op1 = Mul.getOperand(1);
12634 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12635 Opcode = ARMISD::SMLALBT;
12636 Op0 = Mul.getOperand(0);
12637 Op1 = Mul.getOperand(1).getOperand(0);
12638 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12639 Opcode = ARMISD::SMLALTB;
12640 Op0 = Mul.getOperand(0).getOperand(0);
12641 Op1 = Mul.getOperand(1);
12642 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12643 Opcode = ARMISD::SMLALTT;
12644 Op0 = Mul->getOperand(0).getOperand(0);
12645 Op1 = Mul->getOperand(1).getOperand(0);
12646 }
12647
12648 if (!Op0 || !Op1)
12649 return SDValue();
12650
12651 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12652 Op0, Op1, Lo, Hi);
12653 // Replace the ADDs' nodes uses by the MLA node's values.
12654 SDValue HiMLALResult(SMLAL.getNode(), 1);
12655 SDValue LoMLALResult(SMLAL.getNode(), 0);
12656
12657 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12658 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12659
12660 // Return original node to notify the driver to stop replacing.
12661 SDValue resNode(AddcNode, 0);
12662 return resNode;
12663}
12664
12665static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
12666 TargetLowering::DAGCombinerInfo &DCI,
12667 const ARMSubtarget *Subtarget) {
12668 // Look for multiply add opportunities.
12669 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12670 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12671 // a glue link from the first add to the second add.
12672 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12673 // a S/UMLAL instruction.
12674 // UMUL_LOHI
12675 // / :lo \ :hi
12676 // V \ [no multiline comment]
12677 // loAdd -> ADDC |
12678 // \ :carry /
12679 // V V
12680 // ADDE <- hiAdd
12681 //
12682 // In the special case where only the higher part of a signed result is used
12683 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12684 // a constant with the exact value of 0x80000000, we recognize we are dealing
12685 // with a "rounded multiply and add" (or subtract) and transform it into
12686 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12687
12688 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||(static_cast <bool> ((AddeSubeNode->getOpcode() == ARMISD
::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
"Expect an ADDE or SUBE") ? void (0) : __assert_fail ("(AddeSubeNode->getOpcode() == ARMISD::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) && \"Expect an ADDE or SUBE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12690, __extension__
__PRETTY_FUNCTION__))
12689 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&(static_cast <bool> ((AddeSubeNode->getOpcode() == ARMISD
::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
"Expect an ADDE or SUBE") ? void (0) : __assert_fail ("(AddeSubeNode->getOpcode() == ARMISD::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) && \"Expect an ADDE or SUBE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12690, __extension__
__PRETTY_FUNCTION__))
12690 "Expect an ADDE or SUBE")(static_cast <bool> ((AddeSubeNode->getOpcode() == ARMISD
::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
"Expect an ADDE or SUBE") ? void (0) : __assert_fail ("(AddeSubeNode->getOpcode() == ARMISD::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) && \"Expect an ADDE or SUBE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12690, __extension__
__PRETTY_FUNCTION__))
;
12691
12692 assert(AddeSubeNode->getNumOperands() == 3 &&(static_cast <bool> (AddeSubeNode->getNumOperands() ==
3 && AddeSubeNode->getOperand(2).getValueType() ==
MVT::i32 && "ADDE node has the wrong inputs") ? void
(0) : __assert_fail ("AddeSubeNode->getNumOperands() == 3 && AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && \"ADDE node has the wrong inputs\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12694, __extension__
__PRETTY_FUNCTION__))
12693 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&(static_cast <bool> (AddeSubeNode->getNumOperands() ==
3 && AddeSubeNode->getOperand(2).getValueType() ==
MVT::i32 && "ADDE node has the wrong inputs") ? void
(0) : __assert_fail ("AddeSubeNode->getNumOperands() == 3 && AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && \"ADDE node has the wrong inputs\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12694, __extension__
__PRETTY_FUNCTION__))
12694 "ADDE node has the wrong inputs")(static_cast <bool> (AddeSubeNode->getNumOperands() ==
3 && AddeSubeNode->getOperand(2).getValueType() ==
MVT::i32 && "ADDE node has the wrong inputs") ? void
(0) : __assert_fail ("AddeSubeNode->getNumOperands() == 3 && AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && \"ADDE node has the wrong inputs\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12694, __extension__
__PRETTY_FUNCTION__))
;
12695
12696 // Check that we are chained to the right ADDC or SUBC node.
12697 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
12698 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12699 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12700 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12701 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12702 return SDValue();
12703
12704 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
12705 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
12706
12707 // Check if the two operands are from the same mul_lohi node.
12708 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12709 return SDValue();
12710
12711 assert(AddcSubcNode->getNumValues() == 2 &&(static_cast <bool> (AddcSubcNode->getNumValues() ==
2 && AddcSubcNode->getValueType(0) == MVT::i32 &&
"Expect ADDC with two result values. First: i32") ? void (0)
: __assert_fail ("AddcSubcNode->getNumValues() == 2 && AddcSubcNode->getValueType(0) == MVT::i32 && \"Expect ADDC with two result values. First: i32\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12713, __extension__
__PRETTY_FUNCTION__))
12712 AddcSubcNode->getValueType(0) == MVT::i32 &&(static_cast <bool> (AddcSubcNode->getNumValues() ==
2 && AddcSubcNode->getValueType(0) == MVT::i32 &&
"Expect ADDC with two result values. First: i32") ? void (0)
: __assert_fail ("AddcSubcNode->getNumValues() == 2 && AddcSubcNode->getValueType(0) == MVT::i32 && \"Expect ADDC with two result values. First: i32\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12713, __extension__
__PRETTY_FUNCTION__))
12713 "Expect ADDC with two result values. First: i32")(static_cast <bool> (AddcSubcNode->getNumValues() ==
2 && AddcSubcNode->getValueType(0) == MVT::i32 &&
"Expect ADDC with two result values. First: i32") ? void (0)
: __assert_fail ("AddcSubcNode->getNumValues() == 2 && AddcSubcNode->getValueType(0) == MVT::i32 && \"Expect ADDC with two result values. First: i32\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 12713, __extension__
__PRETTY_FUNCTION__))
;
12714
12715 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12716 // maybe a SMLAL which multiplies two 16-bit values.
12717 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12718 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12719 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12720 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12721 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12722 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
12723
12724 // Check for the triangle shape.
12725 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
12726 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
12727
12728 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12729 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12730 return SDValue();
12731
12732 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12733 bool IsLeftOperandMUL = false;
12734 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
12735 if (MULOp == SDValue())
12736 MULOp = findMUL_LOHI(AddeSubeOp1);
12737 else
12738 IsLeftOperandMUL = true;
12739 if (MULOp == SDValue())
12740 return SDValue();
12741
12742 // Figure out the right opcode.
12743 unsigned Opc = MULOp->getOpcode();
12744 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12745
12746 // Figure out the high and low input values to the MLAL node.
12747 SDValue *HiAddSub = nullptr;
12748 SDValue *LoMul = nullptr;
12749 SDValue *LowAddSub = nullptr;
12750
12751 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12752 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
12753 return SDValue();
12754
12755 if (IsLeftOperandMUL)
12756 HiAddSub = &AddeSubeOp1;
12757 else
12758 HiAddSub = &AddeSubeOp0;
12759
12760 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12761 // whose low result is fed to the ADDC/SUBC we are checking.
12762
12763 if (AddcSubcOp0 == MULOp.getValue(0)) {
12764 LoMul = &AddcSubcOp0;
12765 LowAddSub = &AddcSubcOp1;
12766 }
12767 if (AddcSubcOp1 == MULOp.getValue(0)) {
12768 LoMul = &AddcSubcOp1;
12769 LowAddSub = &AddcSubcOp0;
12770 }
12771
12772 if (!LoMul)
12773 return SDValue();
12774
12775 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12776 // the replacement below will create a cycle.
12777 if (AddcSubcNode == HiAddSub->getNode() ||
12778 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
12779 return SDValue();
12780
12781 // Create the merged node.
12782 SelectionDAG &DAG = DCI.DAG;
12783
12784 // Start building operand list.
12785 SmallVector<SDValue, 8> Ops;
12786 Ops.push_back(LoMul->getOperand(0));
12787 Ops.push_back(LoMul->getOperand(1));
12788
12789 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12790 // the case, we must be doing signed multiplication and only use the higher
12791 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12792 // addition or subtraction with the value of 0x800000.
12793 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12794 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
12795 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12796 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12797 0x80000000) {
12798 Ops.push_back(*HiAddSub);
12799 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12800 FinalOpc = ARMISD::SMMLSR;
12801 } else {
12802 FinalOpc = ARMISD::SMMLAR;
12803 }
12804 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
12805 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
12806
12807 return SDValue(AddeSubeNode, 0);
12808 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12809 // SMMLS is generated during instruction selection and the rest of this
12810 // function can not handle the case where AddcSubcNode is a SUBC.
12811 return SDValue();
12812
12813 // Finish building the operand list for {U/S}MLAL
12814 Ops.push_back(*LowAddSub);
12815 Ops.push_back(*HiAddSub);
12816
12817 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
12818 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12819
12820 // Replace the ADDs' nodes uses by the MLA node's values.
12821 SDValue HiMLALResult(MLALNode.getNode(), 1);
12822 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
12823
12824 SDValue LoMLALResult(MLALNode.getNode(), 0);
12825 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
12826
12827 // Return original node to notify the driver to stop replacing.
12828 return SDValue(AddeSubeNode, 0);
12829}
12830
12831static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
12832 TargetLowering::DAGCombinerInfo &DCI,
12833 const ARMSubtarget *Subtarget) {
12834 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12835 // While trying to combine for the other MLAL nodes, first search for the
12836 // chance to use UMAAL. Check if Addc uses a node which has already
12837 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12838 // as the addend, and it's handled in PerformUMLALCombine.
12839
12840 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12841 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12842
12843 // Check that we have a glued ADDC node.
12844 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
12845 if (AddcNode->getOpcode() != ARMISD::ADDC)
12846 return SDValue();
12847
12848 // Find the converted UMAAL or quit if it doesn't exist.
12849 SDNode *UmlalNode = nullptr;
12850 SDValue AddHi;
12851 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12852 UmlalNode = AddcNode->getOperand(0).getNode();
12853 AddHi = AddcNode->getOperand(1);
12854 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12855 UmlalNode = AddcNode->getOperand(1).getNode();
12856 AddHi = AddcNode->getOperand(0);
12857 } else {
12858 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12859 }
12860
12861 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12862 // the ADDC as well as Zero.
12863 if (!isNullConstant(UmlalNode->getOperand(3)))
12864 return SDValue();
12865
12866 if ((isNullConstant(AddeNode->getOperand(0)) &&
12867 AddeNode->getOperand(1).getNode() == UmlalNode) ||
12868 (AddeNode->getOperand(0).getNode() == UmlalNode &&
12869 isNullConstant(AddeNode->getOperand(1)))) {
12870 SelectionDAG &DAG = DCI.DAG;
12871 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12872 UmlalNode->getOperand(2), AddHi };
12873 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12874 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12875
12876 // Replace the ADDs' nodes uses by the UMAAL node's values.
12877 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12878 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12879
12880 // Return original node to notify the driver to stop replacing.
12881 return SDValue(AddeNode, 0);
12882 }
12883 return SDValue();
12884}
12885
12886static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12887 const ARMSubtarget *Subtarget) {
12888 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12889 return SDValue();
12890
12891 // Check that we have a pair of ADDC and ADDE as operands.
12892 // Both addends of the ADDE must be zero.
12893 SDNode* AddcNode = N->getOperand(2).getNode();
12894 SDNode* AddeNode = N->getOperand(3).getNode();
12895 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12896 (AddeNode->getOpcode() == ARMISD::ADDE) &&
12897 isNullConstant(AddeNode->getOperand(0)) &&
12898 isNullConstant(AddeNode->getOperand(1)) &&
12899 (AddeNode->getOperand(2).getNode() == AddcNode))
12900 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12901 DAG.getVTList(MVT::i32, MVT::i32),
12902 {N->getOperand(0), N->getOperand(1),
12903 AddcNode->getOperand(0), AddcNode->getOperand(1)});
12904 else
12905 return SDValue();
12906}
12907
12908static SDValue PerformAddcSubcCombine(SDNode *N,
12909 TargetLowering::DAGCombinerInfo &DCI,
12910 const ARMSubtarget *Subtarget) {
12911 SelectionDAG &DAG(DCI.DAG);
12912
12913 if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(1)) {
12914 // (SUBC (ADDE 0, 0, C), 1) -> C
12915 SDValue LHS = N->getOperand(0);
12916 SDValue RHS = N->getOperand(1);
12917 if (LHS->getOpcode() == ARMISD::ADDE &&
12918 isNullConstant(LHS->getOperand(0)) &&
12919 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
12920 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
12921 }
12922 }
12923
12924 if (Subtarget->isThumb1Only()) {
12925 SDValue RHS = N->getOperand(1);
12926 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12927 int32_t imm = C->getSExtValue();
12928 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
12929 SDLoc DL(N);
12930 RHS = DAG.getConstant(-imm, DL, MVT::i32);
12931 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
12932 : ARMISD::ADDC;
12933 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
12934 }
12935 }
12936 }
12937
12938 return SDValue();
12939}
12940
12941static SDValue PerformAddeSubeCombine(SDNode *N,
12942 TargetLowering::DAGCombinerInfo &DCI,
12943 const ARMSubtarget *Subtarget) {
12944 if (Subtarget->isThumb1Only()) {
12945 SelectionDAG &DAG = DCI.DAG;
12946 SDValue RHS = N->getOperand(1);
12947 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12948 int64_t imm = C->getSExtValue();
12949 if (imm < 0) {
12950 SDLoc DL(N);
12951
12952 // The with-carry-in form matches bitwise not instead of the negation.
12953 // Effectively, the inverse interpretation of the carry flag already
12954 // accounts for part of the negation.
12955 RHS = DAG.getConstant(~imm, DL, MVT::i32);
12956
12957 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
12958 : ARMISD::ADDE;
12959 return DAG.getNode(Opcode, DL, N->getVTList(),
12960 N->getOperand(0), RHS, N->getOperand(2));
12961 }
12962 }
12963 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
12964 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
12965 }
12966 return SDValue();
12967}
12968
12969static SDValue PerformSELECTCombine(SDNode *N,
12970 TargetLowering::DAGCombinerInfo &DCI,
12971 const ARMSubtarget *Subtarget) {
12972 if (!Subtarget->hasMVEIntegerOps())
12973 return SDValue();
12974
12975 SDLoc dl(N);
12976 SDValue SetCC;
12977 SDValue LHS;
12978 SDValue RHS;
12979 ISD::CondCode CC;
12980 SDValue TrueVal;
12981 SDValue FalseVal;
12982
12983 if (N->getOpcode() == ISD::SELECT &&
12984 N->getOperand(0)->getOpcode() == ISD::SETCC) {
12985 SetCC = N->getOperand(0);
12986 LHS = SetCC->getOperand(0);
12987 RHS = SetCC->getOperand(1);
12988 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
12989 TrueVal = N->getOperand(1);
12990 FalseVal = N->getOperand(2);
12991 } else if (N->getOpcode() == ISD::SELECT_CC) {
12992 LHS = N->getOperand(0);
12993 RHS = N->getOperand(1);
12994 CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
12995 TrueVal = N->getOperand(2);
12996 FalseVal = N->getOperand(3);
12997 } else {
12998 return SDValue();
12999 }
13000
13001 unsigned int Opcode = 0;
13002 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13003 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13004 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13005 Opcode = ARMISD::VMINVu;
13006 if (CC == ISD::SETUGT)
13007 std::swap(TrueVal, FalseVal);
13008 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13009 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13010 (CC == ISD::SETLT || CC == ISD::SETGT)) {
13011 Opcode = ARMISD::VMINVs;
13012 if (CC == ISD::SETGT)
13013 std::swap(TrueVal, FalseVal);
13014 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13015 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13016 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13017 Opcode = ARMISD::VMAXVu;
13018 if (CC == ISD::SETULT)
13019 std::swap(TrueVal, FalseVal);
13020 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13021 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13022 (CC == ISD::SETGT || CC == ISD::SETLT)) {
13023 Opcode = ARMISD::VMAXVs;
13024 if (CC == ISD::SETLT)
13025 std::swap(TrueVal, FalseVal);
13026 } else
13027 return SDValue();
13028
13029 // Normalise to the right hand side being the vector reduction
13030 switch (TrueVal->getOpcode()) {
13031 case ISD::VECREDUCE_UMIN:
13032 case ISD::VECREDUCE_SMIN:
13033 case ISD::VECREDUCE_UMAX:
13034 case ISD::VECREDUCE_SMAX:
13035 std::swap(LHS, RHS);
13036 std::swap(TrueVal, FalseVal);
13037 break;
13038 }
13039
13040 EVT VectorType = FalseVal->getOperand(0).getValueType();
13041
13042 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13043 VectorType != MVT::v4i32)
13044 return SDValue();
13045
13046 EVT VectorScalarType = VectorType.getVectorElementType();
13047
13048 // The values being selected must also be the ones being compared
13049 if (TrueVal != LHS || FalseVal != RHS)
13050 return SDValue();
13051
13052 EVT LeftType = LHS->getValueType(0);
13053 EVT RightType = RHS->getValueType(0);
13054
13055 // The types must match the reduced type too
13056 if (LeftType != VectorScalarType || RightType != VectorScalarType)
13057 return SDValue();
13058
13059 // Legalise the scalar to an i32
13060 if (VectorScalarType != MVT::i32)
13061 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13062
13063 // Generate the reduction as an i32 for legalisation purposes
13064 auto Reduction =
13065 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
13066
13067 // The result isn't actually an i32 so truncate it back to its original type
13068 if (VectorScalarType != MVT::i32)
13069 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
13070
13071 return Reduction;
13072}
13073
13074// A special combine for the vqdmulh family of instructions. This is one of the
13075// potential set of patterns that could patch this instruction. The base pattern
13076// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13077// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13078// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13079// the max is unnecessary.
13080static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
13081 EVT VT = N->getValueType(0);
13082 SDValue Shft;
13083 ConstantSDNode *Clamp;
13084
13085 if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13086 return SDValue();
13087
13088 if (N->getOpcode() == ISD::SMIN) {
13089 Shft = N->getOperand(0);
13090 Clamp = isConstOrConstSplat(N->getOperand(1));
13091 } else if (N->getOpcode() == ISD::VSELECT) {
13092 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13093 SDValue Cmp = N->getOperand(0);
13094 if (Cmp.getOpcode() != ISD::SETCC ||
13095 cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
13096 Cmp.getOperand(0) != N->getOperand(1) ||
13097 Cmp.getOperand(1) != N->getOperand(2))
13098 return SDValue();
13099 Shft = N->getOperand(1);
13100 Clamp = isConstOrConstSplat(N->getOperand(2));
13101 } else
13102 return SDValue();
13103
13104 if (!Clamp)
13105 return SDValue();
13106
13107 MVT ScalarType;
13108 int ShftAmt = 0;
13109 switch (Clamp->getSExtValue()) {
13110 case (1 << 7) - 1:
13111 ScalarType = MVT::i8;
13112 ShftAmt = 7;
13113 break;
13114 case (1 << 15) - 1:
13115 ScalarType = MVT::i16;
13116 ShftAmt = 15;
13117 break;
13118 case (1ULL << 31) - 1:
13119 ScalarType = MVT::i32;
13120 ShftAmt = 31;
13121 break;
13122 default:
13123 return SDValue();
13124 }
13125
13126 if (Shft.getOpcode() != ISD::SRA)
13127 return SDValue();
13128 ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
13129 if (!N1 || N1->getSExtValue() != ShftAmt)
13130 return SDValue();
13131
13132 SDValue Mul = Shft.getOperand(0);
13133 if (Mul.getOpcode() != ISD::MUL)
13134 return SDValue();
13135
13136 SDValue Ext0 = Mul.getOperand(0);
13137 SDValue Ext1 = Mul.getOperand(1);
13138 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13139 Ext1.getOpcode() != ISD::SIGN_EXTEND)
13140 return SDValue();
13141 EVT VecVT = Ext0.getOperand(0).getValueType();
13142 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13143 return SDValue();
13144 if (Ext1.getOperand(0).getValueType() != VecVT ||
13145 VecVT.getScalarType() != ScalarType ||
13146 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13147 return SDValue();
13148
13149 SDLoc DL(Mul);
13150 unsigned LegalLanes = 128 / (ShftAmt + 1);
13151 EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
13152 // For types smaller than legal vectors extend to be legal and only use needed
13153 // lanes.
13154 if (VecVT.getSizeInBits() < 128) {
13155 EVT ExtVecVT =
13156 MVT::getVectorVT(MVT::getIntegerVT(128 / VecVT.getVectorNumElements()),
13157 VecVT.getVectorNumElements());
13158 SDValue Inp0 =
13159 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
13160 SDValue Inp1 =
13161 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
13162 Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
13163 Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
13164 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13165 SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
13166 Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
13167 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
13168 }
13169
13170 // For larger types, split into legal sized chunks.
13171 assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type")(static_cast <bool> (VecVT.getSizeInBits() % 128 == 0 &&
"Expected a power2 type") ? void (0) : __assert_fail ("VecVT.getSizeInBits() % 128 == 0 && \"Expected a power2 type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13171, __extension__
__PRETTY_FUNCTION__))
;
13172 unsigned NumParts = VecVT.getSizeInBits() / 128;
13173 SmallVector<SDValue> Parts;
13174 for (unsigned I = 0; I < NumParts; ++I) {
13175 SDValue Inp0 =
13176 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
13177 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13178 SDValue Inp1 =
13179 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
13180 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13181 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13182 Parts.push_back(VQDMULH);
13183 }
13184 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
13185 DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
13186}
13187
13188static SDValue PerformVSELECTCombine(SDNode *N,
13189 TargetLowering::DAGCombinerInfo &DCI,
13190 const ARMSubtarget *Subtarget) {
13191 if (!Subtarget->hasMVEIntegerOps())
13192 return SDValue();
13193
13194 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13195 return V;
13196
13197 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13198 //
13199 // We need to re-implement this optimization here as the implementation in the
13200 // Target-Independent DAGCombiner does not handle the kind of constant we make
13201 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13202 // good reason, allowing truncation there would break other targets).
13203 //
13204 // Currently, this is only done for MVE, as it's the only target that benefits
13205 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13206 if (N->getOperand(0).getOpcode() != ISD::XOR)
13207 return SDValue();
13208 SDValue XOR = N->getOperand(0);
13209
13210 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13211 // It is important to check with truncation allowed as the BUILD_VECTORs we
13212 // generate in those situations will truncate their operands.
13213 ConstantSDNode *Const =
13214 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13215 /*AllowTruncation*/ true);
13216 if (!Const || !Const->isOne())
13217 return SDValue();
13218
13219 // Rewrite into vselect(cond, rhs, lhs).
13220 SDValue Cond = XOR->getOperand(0);
13221 SDValue LHS = N->getOperand(1);
13222 SDValue RHS = N->getOperand(2);
13223 EVT Type = N->getValueType(0);
13224 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13225}
13226
13227// Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
13228static SDValue PerformVSetCCToVCTPCombine(SDNode *N,
13229 TargetLowering::DAGCombinerInfo &DCI,
13230 const ARMSubtarget *Subtarget) {
13231 SDValue Op0 = N->getOperand(0);
13232 SDValue Op1 = N->getOperand(1);
13233 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13234 EVT VT = N->getValueType(0);
13235
13236 if (!Subtarget->hasMVEIntegerOps() ||
13237 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13238 return SDValue();
13239
13240 if (CC == ISD::SETUGE) {
13241 std::swap(Op0, Op1);
13242 CC = ISD::SETULT;
13243 }
13244
13245 if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13246 Op0.getOpcode() != ISD::BUILD_VECTOR)
13247 return SDValue();
13248
13249 // Check first operand is BuildVector of 0,1,2,...
13250 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13251 if (!Op0.getOperand(I).isUndef() &&
13252 !(isa<ConstantSDNode>(Op0.getOperand(I)) &&
13253 Op0.getConstantOperandVal(I) == I))
13254 return SDValue();
13255 }
13256
13257 // The second is a Splat of Op1S
13258 SDValue Op1S = DCI.DAG.getSplatValue(Op1);
13259 if (!Op1S)
13260 return SDValue();
13261
13262 unsigned Opc;
13263 switch (VT.getVectorNumElements()) {
13264 case 2:
13265 Opc = Intrinsic::arm_mve_vctp64;
13266 break;
13267 case 4:
13268 Opc = Intrinsic::arm_mve_vctp32;
13269 break;
13270 case 8:
13271 Opc = Intrinsic::arm_mve_vctp16;
13272 break;
13273 case 16:
13274 Opc = Intrinsic::arm_mve_vctp8;
13275 break;
13276 default:
13277 return SDValue();
13278 }
13279
13280 SDLoc DL(N);
13281 return DCI.DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13282 DCI.DAG.getConstant(Opc, DL, MVT::i32),
13283 DCI.DAG.getZExtOrTrunc(Op1S, DL, MVT::i32));
13284}
13285
13286static SDValue PerformABSCombine(SDNode *N,
13287 TargetLowering::DAGCombinerInfo &DCI,
13288 const ARMSubtarget *Subtarget) {
13289 SelectionDAG &DAG = DCI.DAG;
13290 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13291
13292 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
13293 return SDValue();
13294
13295 return TLI.expandABS(N, DAG);
13296}
13297
13298/// PerformADDECombine - Target-specific dag combine transform from
13299/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13300/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13301static SDValue PerformADDECombine(SDNode *N,
13302 TargetLowering::DAGCombinerInfo &DCI,
13303 const ARMSubtarget *Subtarget) {
13304 // Only ARM and Thumb2 support UMLAL/SMLAL.
13305 if (Subtarget->isThumb1Only())
13306 return PerformAddeSubeCombine(N, DCI, Subtarget);
13307
13308 // Only perform the checks after legalize when the pattern is available.
13309 if (DCI.isBeforeLegalize()) return SDValue();
13310
13311 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13312}
13313
13314/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13315/// operands N0 and N1. This is a helper for PerformADDCombine that is
13316/// called with the default operands, and if that fails, with commuted
13317/// operands.
13318static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
13319 TargetLowering::DAGCombinerInfo &DCI,
13320 const ARMSubtarget *Subtarget){
13321 // Attempt to create vpadd for this add.
13322 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13323 return Result;
13324
13325 // Attempt to create vpaddl for this add.
13326 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13327 return Result;
13328 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13329 Subtarget))
13330 return Result;
13331
13332 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13333 if (N0.getNode()->hasOneUse())
13334 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13335 return Result;
13336 return SDValue();
13337}
13338
13339static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG) {
13340 EVT VT = N->getValueType(0);
13341 SDValue N0 = N->getOperand(0);
13342 SDValue N1 = N->getOperand(1);
13343 SDLoc dl(N);
13344
13345 auto IsVecReduce = [](SDValue Op) {
13346 switch (Op.getOpcode()) {
13347 case ISD::VECREDUCE_ADD:
13348 case ARMISD::VADDVs:
13349 case ARMISD::VADDVu:
13350 case ARMISD::VMLAVs:
13351 case ARMISD::VMLAVu:
13352 return true;
13353 }
13354 return false;
13355 };
13356
13357 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13358 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13359 // add(add(X, vecreduce(Y)), vecreduce(Z))
13360 // to make better use of vaddva style instructions.
13361 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13362 IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13363 !isa<ConstantSDNode>(N0) && N1->hasOneUse()) {
13364 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13365 return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13366 }
13367 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13368 // add(add(add(A, C), reduce(B)), reduce(D))
13369 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13370 N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13371 unsigned N0RedOp = 0;
13372 if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13373 N0RedOp = 1;
13374 if (!IsVecReduce(N0.getOperand(N0RedOp)))
13375 return SDValue();
13376 }
13377
13378 unsigned N1RedOp = 0;
13379 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13380 N1RedOp = 1;
13381 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13382 return SDValue();
13383
13384 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13385 N1.getOperand(1 - N1RedOp));
13386 SDValue Add1 =
13387 DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13388 return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13389 }
13390 return SDValue();
13391 };
13392 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13393 return R;
13394 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13395 return R;
13396
13397 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13398 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13399 // by ascending load offsets. This can help cores prefetch if the order of
13400 // loads is more predictable.
13401 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13402 // Check if two reductions are known to load data where one is before/after
13403 // another. Return negative if N0 loads data before N1, positive if N1 is
13404 // before N0 and 0 otherwise if nothing is known.
13405 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13406 // Look through to the first operand of a MUL, for the VMLA case.
13407 // Currently only looks at the first operand, in the hope they are equal.
13408 if (N0.getOpcode() == ISD::MUL)
13409 N0 = N0.getOperand(0);
13410 if (N1.getOpcode() == ISD::MUL)
13411 N1 = N1.getOperand(0);
13412
13413 // Return true if the two operands are loads to the same object and the
13414 // offset of the first is known to be less than the offset of the second.
13415 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13416 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13417 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13418 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13419 Load1->isIndexed())
13420 return 0;
13421
13422 auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13423 auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13424
13425 if (!BaseLocDecomp0.getBase() ||
13426 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13427 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13428 return 0;
13429 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13430 return -1;
13431 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13432 return 1;
13433 return 0;
13434 };
13435
13436 SDValue X;
13437 if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13438 if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13439 int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13440 N0.getOperand(1).getOperand(0));
13441 if (IsBefore < 0) {
13442 X = N0.getOperand(0);
13443 N0 = N0.getOperand(1);
13444 } else if (IsBefore > 0) {
13445 X = N0.getOperand(1);
13446 N0 = N0.getOperand(0);
13447 } else
13448 return SDValue();
13449 } else if (IsVecReduce(N0.getOperand(0))) {
13450 X = N0.getOperand(1);
13451 N0 = N0.getOperand(0);
13452 } else if (IsVecReduce(N0.getOperand(1))) {
13453 X = N0.getOperand(0);
13454 N0 = N0.getOperand(1);
13455 } else
13456 return SDValue();
13457 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13458 IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13459 // Note this is backward to how you would expect. We create
13460 // add(reduce(load + 16), reduce(load + 0)) so that the
13461 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13462 // the X as VADDV(load + 0)
13463 return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13464 } else
13465 return SDValue();
13466
13467 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13468 return SDValue();
13469
13470 if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13471 return SDValue();
13472
13473 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13474 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13475 return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13476 };
13477 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13478 return R;
13479 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13480 return R;
13481 return SDValue();
13482}
13483
13484static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG,
13485 const ARMSubtarget *Subtarget) {
13486 if (!Subtarget->hasMVEIntegerOps())
13487 return SDValue();
13488
13489 if (SDValue R = TryDistrubutionADDVecReduce(N, DAG))
13490 return R;
13491
13492 EVT VT = N->getValueType(0);
13493 SDValue N0 = N->getOperand(0);
13494 SDValue N1 = N->getOperand(1);
13495 SDLoc dl(N);
13496
13497 if (VT != MVT::i64)
13498 return SDValue();
13499
13500 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13501 // will look like:
13502 // t1: i32,i32 = ARMISD::VADDLVs x
13503 // t2: i64 = build_pair t1, t1:1
13504 // t3: i64 = add t2, y
13505 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13506 // the add to be simplified seperately.
13507 // We also need to check for sext / zext and commutitive adds.
13508 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13509 SDValue NB) {
13510 if (NB->getOpcode() != ISD::BUILD_PAIR)
13511 return SDValue();
13512 SDValue VecRed = NB->getOperand(0);
13513 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13514 VecRed.getResNo() != 0 ||
13515 NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13516 return SDValue();
13517
13518 if (VecRed->getOpcode() == OpcodeA) {
13519 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13520 SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13521 VecRed.getOperand(0), VecRed.getOperand(1));
13522 NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13523 }
13524
13525 SmallVector<SDValue, 4> Ops;
13526 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
13527 DAG.getConstant(0, dl, MVT::i32)));
13528 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
13529 DAG.getConstant(1, dl, MVT::i32)));
13530 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13531 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13532 Ops.push_back(VecRed->getOperand(I));
13533 SDValue Red =
13534 DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13535 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13536 SDValue(Red.getNode(), 1));
13537 };
13538
13539 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13540 return M;
13541 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13542 return M;
13543 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13544 return M;
13545 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13546 return M;
13547 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13548 return M;
13549 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13550 return M;
13551 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13552 return M;
13553 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13554 return M;
13555 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13556 return M;
13557 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13558 return M;
13559 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13560 return M;
13561 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13562 return M;
13563 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13564 return M;
13565 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13566 return M;
13567 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13568 return M;
13569 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13570 return M;
13571 return SDValue();
13572}
13573
13574bool
13575ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13576 CombineLevel Level) const {
13577 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||(static_cast <bool> ((N->getOpcode() == ISD::SHL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL
) && "Expected shift op") ? void (0) : __assert_fail (
"(N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && \"Expected shift op\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13579, __extension__
__PRETTY_FUNCTION__))
13578 N->getOpcode() == ISD::SRL) &&(static_cast <bool> ((N->getOpcode() == ISD::SHL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL
) && "Expected shift op") ? void (0) : __assert_fail (
"(N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && \"Expected shift op\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13579, __extension__
__PRETTY_FUNCTION__))
13579 "Expected shift op")(static_cast <bool> ((N->getOpcode() == ISD::SHL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL
) && "Expected shift op") ? void (0) : __assert_fail (
"(N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && \"Expected shift op\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13579, __extension__
__PRETTY_FUNCTION__))
;
13580
13581 if (Level == BeforeLegalizeTypes)
13582 return true;
13583
13584 if (N->getOpcode() != ISD::SHL)
13585 return true;
13586
13587 if (Subtarget->isThumb1Only()) {
13588 // Avoid making expensive immediates by commuting shifts. (This logic
13589 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13590 // for free.)
13591 if (N->getOpcode() != ISD::SHL)
13592 return true;
13593 SDValue N1 = N->getOperand(0);
13594 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13595 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13596 return true;
13597 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13598 if (Const->getAPIntValue().ult(256))
13599 return false;
13600 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13601 Const->getAPIntValue().sgt(-256))
13602 return false;
13603 }
13604 return true;
13605 }
13606
13607 // Turn off commute-with-shift transform after legalization, so it doesn't
13608 // conflict with PerformSHLSimplify. (We could try to detect when
13609 // PerformSHLSimplify would trigger more precisely, but it isn't
13610 // really necessary.)
13611 return false;
13612}
13613
13614bool ARMTargetLowering::isDesirableToCommuteXorWithShift(
13615 const SDNode *N) const {
13616 assert(N->getOpcode() == ISD::XOR &&(static_cast <bool> (N->getOpcode() == ISD::XOR &&
(N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand
(0).getOpcode() == ISD::SRL) && "Expected XOR(SHIFT) pattern"
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::XOR && (N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand(0).getOpcode() == ISD::SRL) && \"Expected XOR(SHIFT) pattern\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13619, __extension__
__PRETTY_FUNCTION__))
13617 (N->getOperand(0).getOpcode() == ISD::SHL ||(static_cast <bool> (N->getOpcode() == ISD::XOR &&
(N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand
(0).getOpcode() == ISD::SRL) && "Expected XOR(SHIFT) pattern"
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::XOR && (N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand(0).getOpcode() == ISD::SRL) && \"Expected XOR(SHIFT) pattern\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13619, __extension__
__PRETTY_FUNCTION__))
13618 N->getOperand(0).getOpcode() == ISD::SRL) &&(static_cast <bool> (N->getOpcode() == ISD::XOR &&
(N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand
(0).getOpcode() == ISD::SRL) && "Expected XOR(SHIFT) pattern"
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::XOR && (N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand(0).getOpcode() == ISD::SRL) && \"Expected XOR(SHIFT) pattern\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13619, __extension__
__PRETTY_FUNCTION__))
13619 "Expected XOR(SHIFT) pattern")(static_cast <bool> (N->getOpcode() == ISD::XOR &&
(N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand
(0).getOpcode() == ISD::SRL) && "Expected XOR(SHIFT) pattern"
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::XOR && (N->getOperand(0).getOpcode() == ISD::SHL || N->getOperand(0).getOpcode() == ISD::SRL) && \"Expected XOR(SHIFT) pattern\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13619, __extension__
__PRETTY_FUNCTION__))
;
13620
13621 // Only commute if the entire NOT mask is a hidden shifted mask.
13622 auto *XorC = dyn_cast<ConstantSDNode>(N->getOperand(1));
13623 auto *ShiftC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
13624 if (XorC && ShiftC) {
13625 unsigned MaskIdx, MaskLen;
13626 if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13627 unsigned ShiftAmt = ShiftC->getZExtValue();
13628 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
13629 if (N->getOperand(0).getOpcode() == ISD::SHL)
13630 return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13631 return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13632 }
13633 }
13634
13635 return false;
13636}
13637
13638bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
13639 const SDNode *N, CombineLevel Level) const {
13640 assert(((N->getOpcode() == ISD::SHL &&(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13644, __extension__
__PRETTY_FUNCTION__))
13641 N->getOperand(0).getOpcode() == ISD::SRL) ||(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13644, __extension__
__PRETTY_FUNCTION__))
13642 (N->getOpcode() == ISD::SRL &&(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13644, __extension__
__PRETTY_FUNCTION__))
13643 N->getOperand(0).getOpcode() == ISD::SHL)) &&(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13644, __extension__
__PRETTY_FUNCTION__))
13644 "Expected shift-shift mask")(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 13644, __extension__
__PRETTY_FUNCTION__))
;
13645
13646 if (!Subtarget->isThumb1Only())
13647 return true;
13648
13649 if (Level == BeforeLegalizeTypes)
13650 return true;
13651
13652 return false;
13653}
13654
13655bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13656 if (!Subtarget->hasNEON()) {
13657 if (Subtarget->isThumb1Only())
13658 return VT.getScalarSizeInBits() <= 32;
13659 return true;
13660 }
13661 return VT.isScalarInteger();
13662}
13663
13664bool ARMTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
13665 EVT VT) const {
13666 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13667 return false;
13668
13669 switch (FPVT.getSimpleVT().SimpleTy) {
13670 case MVT::f16:
13671 return Subtarget->hasVFP2Base();
13672 case MVT::f32:
13673 return Subtarget->hasVFP2Base();
13674 case MVT::f64:
13675 return Subtarget->hasFP64();
13676 case MVT::v4f32:
13677 case MVT::v8f16:
13678 return Subtarget->hasMVEFloatOps();
13679 default:
13680 return false;
13681 }
13682}
13683
13684static SDValue PerformSHLSimplify(SDNode *N,
13685 TargetLowering::DAGCombinerInfo &DCI,
13686 const ARMSubtarget *ST) {
13687 // Allow the generic combiner to identify potential bswaps.
13688 if (DCI.isBeforeLegalize())
13689 return SDValue();
13690
13691 // DAG combiner will fold:
13692 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13693 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13694 // Other code patterns that can be also be modified have the following form:
13695 // b + ((a << 1) | 510)
13696 // b + ((a << 1) & 510)
13697 // b + ((a << 1) ^ 510)
13698 // b + ((a << 1) + 510)
13699
13700 // Many instructions can perform the shift for free, but it requires both
13701 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13702 // instruction will needed. So, unfold back to the original pattern if:
13703 // - if c1 and c2 are small enough that they don't require mov imms.
13704 // - the user(s) of the node can perform an shl
13705
13706 // No shifted operands for 16-bit instructions.
13707 if (ST->isThumb() && ST->isThumb1Only())
13708 return SDValue();
13709
13710 // Check that all the users could perform the shl themselves.
13711 for (auto *U : N->uses()) {
13712 switch(U->getOpcode()) {
13713 default:
13714 return SDValue();
13715 case ISD::SUB:
13716 case ISD::ADD:
13717 case ISD::AND:
13718 case ISD::OR:
13719 case ISD::XOR:
13720 case ISD::SETCC:
13721 case ARMISD::CMP:
13722 // Check that the user isn't already using a constant because there
13723 // aren't any instructions that support an immediate operand and a
13724 // shifted operand.
13725 if (isa<ConstantSDNode>(U->getOperand(0)) ||
13726 isa<ConstantSDNode>(U->getOperand(1)))
13727 return SDValue();
13728
13729 // Check that it's not already using a shift.
13730 if (U->getOperand(0).getOpcode() == ISD::SHL ||
13731 U->getOperand(1).getOpcode() == ISD::SHL)
13732 return SDValue();
13733 break;
13734 }
13735 }
13736
13737 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13738 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13739 return SDValue();
13740
13741 if (N->getOperand(0).getOpcode() != ISD::SHL)
13742 return SDValue();
13743
13744 SDValue SHL = N->getOperand(0);
13745
13746 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
13747 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
13748 if (!C1ShlC2 || !C2)
13749 return SDValue();
13750
13751 APInt C2Int = C2->getAPIntValue();
13752 APInt C1Int = C1ShlC2->getAPIntValue();
13753
13754 // Check that performing a lshr will not lose any information.
13755 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
13756 C2Int.getBitWidth() - C2->getZExtValue());
13757 if ((C1Int & Mask) != C1Int)
13758 return SDValue();
13759
13760 // Shift the first constant.
13761 C1Int.lshrInPlace(C2Int);
13762
13763 // The immediates are encoded as an 8-bit value that can be rotated.
13764 auto LargeImm = [](const APInt &Imm) {
13765 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
13766 return Imm.getBitWidth() - Zeros > 8;
13767 };
13768
13769 if (LargeImm(C1Int) || LargeImm(C2Int))
13770 return SDValue();
13771
13772 SelectionDAG &DAG = DCI.DAG;
13773 SDLoc dl(N);
13774 SDValue X = SHL.getOperand(0);
13775 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
13776 DAG.getConstant(C1Int, dl, MVT::i32));
13777 // Shift left to compensate for the lshr of C1Int.
13778 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
13779
13780 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Simplify shl use:\n"; SHL.getOperand
(0).dump(); SHL.dump(); N->dump(); } } while (false)
13781 SHL.dump(); N->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Simplify shl use:\n"; SHL.getOperand
(0).dump(); SHL.dump(); N->dump(); } } while (false)
;
13782 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Into:\n"; X.dump(); BinOp.dump
(); Res.dump(); } } while (false)
;
13783 return Res;
13784}
13785
13786
13787/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13788///
13789static SDValue PerformADDCombine(SDNode *N,
13790 TargetLowering::DAGCombinerInfo &DCI,
13791 const ARMSubtarget *Subtarget) {
13792 SDValue N0 = N->getOperand(0);
13793 SDValue N1 = N->getOperand(1);
13794
13795 // Only works one way, because it needs an immediate operand.
13796 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13797 return Result;
13798
13799 if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
13800 return Result;
13801
13802 // First try with the default operand order.
13803 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13804 return Result;
13805
13806 // If that didn't work, try again with the operands commuted.
13807 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
13808}
13809
13810// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13811// providing -X is as cheap as X (currently, just a constant).
13812static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG) {
13813 if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
13814 return SDValue();
13815 SDValue CSINC = N->getOperand(1);
13816 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13817 return SDValue();
13818
13819 ConstantSDNode *X = dyn_cast<ConstantSDNode>(CSINC.getOperand(0));
13820 if (!X)
13821 return SDValue();
13822
13823 return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
13824 DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
13825 CSINC.getOperand(0)),
13826 CSINC.getOperand(1), CSINC.getOperand(2),
13827 CSINC.getOperand(3));
13828}
13829
13830/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
13831///
13832static SDValue PerformSUBCombine(SDNode *N,
13833 TargetLowering::DAGCombinerInfo &DCI,
13834 const ARMSubtarget *Subtarget) {
13835 SDValue N0 = N->getOperand(0);
13836 SDValue N1 = N->getOperand(1);
13837
13838 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
13839 if (N1.getNode()->hasOneUse())
13840 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
13841 return Result;
13842
13843 if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
13844 return R;
13845
13846 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
13847 return SDValue();
13848
13849 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
13850 // so that we can readily pattern match more mve instructions which can use
13851 // a scalar operand.
13852 SDValue VDup = N->getOperand(1);
13853 if (VDup->getOpcode() != ARMISD::VDUP)
13854 return SDValue();
13855
13856 SDValue VMov = N->getOperand(0);
13857 if (VMov->getOpcode() == ISD::BITCAST)
13858 VMov = VMov->getOperand(0);
13859
13860 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
13861 return SDValue();
13862
13863 SDLoc dl(N);
13864 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
13865 DCI.DAG.getConstant(0, dl, MVT::i32),
13866 VDup->getOperand(0));
13867 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
13868}
13869
13870/// PerformVMULCombine
13871/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
13872/// special multiplier accumulator forwarding.
13873/// vmul d3, d0, d2
13874/// vmla d3, d1, d2
13875/// is faster than
13876/// vadd d3, d0, d1
13877/// vmul d3, d3, d2
13878// However, for (A + B) * (A + B),
13879// vadd d2, d0, d1
13880// vmul d3, d0, d2
13881// vmla d3, d1, d2
13882// is slower than
13883// vadd d2, d0, d1
13884// vmul d3, d2, d2
13885static SDValue PerformVMULCombine(SDNode *N,
13886 TargetLowering::DAGCombinerInfo &DCI,
13887 const ARMSubtarget *Subtarget) {
13888 if (!Subtarget->hasVMLxForwarding())
13889 return SDValue();
13890
13891 SelectionDAG &DAG = DCI.DAG;
13892 SDValue N0 = N->getOperand(0);
13893 SDValue N1 = N->getOperand(1);
13894 unsigned Opcode = N0.getOpcode();
13895 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
13896 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
13897 Opcode = N1.getOpcode();
13898 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
13899 Opcode != ISD::FADD && Opcode != ISD::FSUB)
13900 return SDValue();
13901 std::swap(N0, N1);
13902 }
13903
13904 if (N0 == N1)
13905 return SDValue();
13906
13907 EVT VT = N->getValueType(0);
13908 SDLoc DL(N);
13909 SDValue N00 = N0->getOperand(0);
13910 SDValue N01 = N0->getOperand(1);
13911 return DAG.getNode(Opcode, DL, VT,
13912 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
13913 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
13914}
13915
13916static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
13917 const ARMSubtarget *Subtarget) {
13918 EVT VT = N->getValueType(0);
13919 if (VT != MVT::v2i64)
13920 return SDValue();
13921
13922 SDValue N0 = N->getOperand(0);
13923 SDValue N1 = N->getOperand(1);
13924
13925 auto IsSignExt = [&](SDValue Op) {
13926 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
13927 return SDValue();
13928 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
13929 if (VT.getScalarSizeInBits() == 32)
13930 return Op->getOperand(0);
13931 return SDValue();
13932 };
13933 auto IsZeroExt = [&](SDValue Op) {
13934 // Zero extends are a little more awkward. At the point we are matching
13935 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
13936 // That might be before of after a bitcast depending on how the and is
13937 // placed. Because this has to look through bitcasts, it is currently only
13938 // supported on LE.
13939 if (!Subtarget->isLittle())
13940 return SDValue();
13941
13942 SDValue And = Op;
13943 if (And->getOpcode() == ISD::BITCAST)
13944 And = And->getOperand(0);
13945 if (And->getOpcode() != ISD::AND)
13946 return SDValue();
13947 SDValue Mask = And->getOperand(1);
13948 if (Mask->getOpcode() == ISD::BITCAST)
13949 Mask = Mask->getOperand(0);
13950
13951 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
13952 Mask.getValueType() != MVT::v4i32)
13953 return SDValue();
13954 if (isAllOnesConstant(Mask->getOperand(0)) &&
13955 isNullConstant(Mask->getOperand(1)) &&
13956 isAllOnesConstant(Mask->getOperand(2)) &&
13957 isNullConstant(Mask->getOperand(3)))
13958 return And->getOperand(0);
13959 return SDValue();
13960 };
13961
13962 SDLoc dl(N);
13963 if (SDValue Op0 = IsSignExt(N0)) {
13964 if (SDValue Op1 = IsSignExt(N1)) {
13965 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
13966 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
13967 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
13968 }
13969 }
13970 if (SDValue Op0 = IsZeroExt(N0)) {
13971 if (SDValue Op1 = IsZeroExt(N1)) {
13972 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
13973 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
13974 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
13975 }
13976 }
13977
13978 return SDValue();
13979}
13980
13981static SDValue PerformMULCombine(SDNode *N,
13982 TargetLowering::DAGCombinerInfo &DCI,
13983 const ARMSubtarget *Subtarget) {
13984 SelectionDAG &DAG = DCI.DAG;
13985
13986 EVT VT = N->getValueType(0);
13987 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
13988 return PerformMVEVMULLCombine(N, DAG, Subtarget);
13989
13990 if (Subtarget->isThumb1Only())
13991 return SDValue();
13992
13993 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13994 return SDValue();
13995
13996 if (VT.is64BitVector() || VT.is128BitVector())
13997 return PerformVMULCombine(N, DCI, Subtarget);
13998 if (VT != MVT::i32)
13999 return SDValue();
14000
14001 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14002 if (!C)
14003 return SDValue();
14004
14005 int64_t MulAmt = C->getSExtValue();
14006 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
14007
14008 ShiftAmt = ShiftAmt & (32 - 1);
14009 SDValue V = N->getOperand(0);
14010 SDLoc DL(N);
14011
14012 SDValue Res;
14013 MulAmt >>= ShiftAmt;
14014
14015 if (MulAmt >= 0) {
14016 if (isPowerOf2_32(MulAmt - 1)) {
14017 // (mul x, 2^N + 1) => (add (shl x, N), x)
14018 Res = DAG.getNode(ISD::ADD, DL, VT,
14019 V,
14020 DAG.getNode(ISD::SHL, DL, VT,
14021 V,
14022 DAG.getConstant(Log2_32(MulAmt - 1), DL,
14023 MVT::i32)));
14024 } else if (isPowerOf2_32(MulAmt + 1)) {
14025 // (mul x, 2^N - 1) => (sub (shl x, N), x)
14026 Res = DAG.getNode(ISD::SUB, DL, VT,
14027 DAG.getNode(ISD::SHL, DL, VT,
14028 V,
14029 DAG.getConstant(Log2_32(MulAmt + 1), DL,
14030 MVT::i32)),
14031 V);
14032 } else
14033 return SDValue();
14034 } else {
14035 uint64_t MulAmtAbs = -MulAmt;
14036 if (isPowerOf2_32(MulAmtAbs + 1)) {
14037 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14038 Res = DAG.getNode(ISD::SUB, DL, VT,
14039 V,
14040 DAG.getNode(ISD::SHL, DL, VT,
14041 V,
14042 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
14043 MVT::i32)));
14044 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
14045 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14046 Res = DAG.getNode(ISD::ADD, DL, VT,
14047 V,
14048 DAG.getNode(ISD::SHL, DL, VT,
14049 V,
14050 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
14051 MVT::i32)));
14052 Res = DAG.getNode(ISD::SUB, DL, VT,
14053 DAG.getConstant(0, DL, MVT::i32), Res);
14054 } else
14055 return SDValue();
14056 }
14057
14058 if (ShiftAmt != 0)
14059 Res = DAG.getNode(ISD::SHL, DL, VT,
14060 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
14061
14062 // Do not add new nodes to DAG combiner worklist.
14063 DCI.CombineTo(N, Res, false);
14064 return SDValue();
14065}
14066
14067static SDValue CombineANDShift(SDNode *N,
14068 TargetLowering::DAGCombinerInfo &DCI,
14069 const ARMSubtarget *Subtarget) {
14070 // Allow DAGCombine to pattern-match before we touch the canonical form.
14071 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14072 return SDValue();
14073
14074 if (N->getValueType(0) != MVT::i32)
14075 return SDValue();
14076
14077 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14078 if (!N1C)
14079 return SDValue();
14080
14081 uint32_t C1 = (uint32_t)N1C->getZExtValue();
14082 // Don't transform uxtb/uxth.
14083 if (C1 == 255 || C1 == 65535)
14084 return SDValue();
14085
14086 SDNode *N0 = N->getOperand(0).getNode();
14087 if (!N0->hasOneUse())
14088 return SDValue();
14089
14090 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14091 return SDValue();
14092
14093 bool LeftShift = N0->getOpcode() == ISD::SHL;
14094
14095 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14096 if (!N01C)
14097 return SDValue();
14098
14099 uint32_t C2 = (uint32_t)N01C->getZExtValue();
14100 if (!C2 || C2 >= 32)
14101 return SDValue();
14102
14103 // Clear irrelevant bits in the mask.
14104 if (LeftShift)
14105 C1 &= (-1U << C2);
14106 else
14107 C1 &= (-1U >> C2);
14108
14109 SelectionDAG &DAG = DCI.DAG;
14110 SDLoc DL(N);
14111
14112 // We have a pattern of the form "(and (shl x, c2) c1)" or
14113 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14114 // transform to a pair of shifts, to save materializing c1.
14115
14116 // First pattern: right shift, then mask off leading bits.
14117 // FIXME: Use demanded bits?
14118 if (!LeftShift && isMask_32(C1)) {
14119 uint32_t C3 = countLeadingZeros(C1);
14120 if (C2 < C3) {
14121 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14122 DAG.getConstant(C3 - C2, DL, MVT::i32));
14123 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14124 DAG.getConstant(C3, DL, MVT::i32));
14125 }
14126 }
14127
14128 // First pattern, reversed: left shift, then mask off trailing bits.
14129 if (LeftShift && isMask_32(~C1)) {
14130 uint32_t C3 = countTrailingZeros(C1);
14131 if (C2 < C3) {
14132 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14133 DAG.getConstant(C3 - C2, DL, MVT::i32));
14134 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14135 DAG.getConstant(C3, DL, MVT::i32));
14136 }
14137 }
14138
14139 // Second pattern: left shift, then mask off leading bits.
14140 // FIXME: Use demanded bits?
14141 if (LeftShift && isShiftedMask_32(C1)) {
14142 uint32_t Trailing = countTrailingZeros(C1);
14143 uint32_t C3 = countLeadingZeros(C1);
14144 if (Trailing == C2 && C2 + C3 < 32) {
14145 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14146 DAG.getConstant(C2 + C3, DL, MVT::i32));
14147 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14148 DAG.getConstant(C3, DL, MVT::i32));
14149 }
14150 }
14151
14152 // Second pattern, reversed: right shift, then mask off trailing bits.
14153 // FIXME: Handle other patterns of known/demanded bits.
14154 if (!LeftShift && isShiftedMask_32(C1)) {
14155 uint32_t Leading = countLeadingZeros(C1);
14156 uint32_t C3 = countTrailingZeros(C1);
14157 if (Leading == C2 && C2 + C3 < 32) {
14158 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14159 DAG.getConstant(C2 + C3, DL, MVT::i32));
14160 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14161 DAG.getConstant(C3, DL, MVT::i32));
14162 }
14163 }
14164
14165 // FIXME: Transform "(and (shl x, c2) c1)" ->
14166 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
14167 // c1.
14168 return SDValue();
14169}
14170
14171static SDValue PerformANDCombine(SDNode *N,
14172 TargetLowering::DAGCombinerInfo &DCI,
14173 const ARMSubtarget *Subtarget) {
14174 // Attempt to use immediate-form VBIC
14175 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14176 SDLoc dl(N);
14177 EVT VT = N->getValueType(0);
14178 SelectionDAG &DAG = DCI.DAG;
14179
14180 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14181 VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14182 return SDValue();
14183
14184 APInt SplatBits, SplatUndef;
14185 unsigned SplatBitSize;
14186 bool HasAnyUndefs;
14187 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14188 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14189 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14190 SplatBitSize == 64) {
14191 EVT VbicVT;
14192 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
14193 SplatUndef.getZExtValue(), SplatBitSize,
14194 DAG, dl, VbicVT, VT, OtherModImm);
14195 if (Val.getNode()) {
14196 SDValue Input =
14197 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
14198 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
14199 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
14200 }
14201 }
14202 }
14203
14204 if (!Subtarget->isThumb1Only()) {
14205 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14206 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
14207 return Result;
14208
14209 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14210 return Result;
14211 }
14212
14213 if (Subtarget->isThumb1Only())
14214 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14215 return Result;
14216
14217 return SDValue();
14218}
14219
14220// Try combining OR nodes to SMULWB, SMULWT.
14221static SDValue PerformORCombineToSMULWBT(SDNode *OR,
14222 TargetLowering::DAGCombinerInfo &DCI,
14223 const ARMSubtarget *Subtarget) {
14224 if (!Subtarget->hasV6Ops() ||
14225 (Subtarget->isThumb() &&
14226 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14227 return SDValue();
14228
14229 SDValue SRL = OR->getOperand(0);
14230 SDValue SHL = OR->getOperand(1);
14231
14232 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14233 SRL = OR->getOperand(1);
14234 SHL = OR->getOperand(0);
14235 }
14236 if (!isSRL16(SRL) || !isSHL16(SHL))
14237 return SDValue();
14238
14239 // The first operands to the shifts need to be the two results from the
14240 // same smul_lohi node.
14241 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
14242 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
14243 return SDValue();
14244
14245 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
14246 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
14247 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
14248 return SDValue();
14249
14250 // Now we have:
14251 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14252 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14253 // For SMUWB the 16-bit value will signed extended somehow.
14254 // For SMULWT only the SRA is required.
14255 // Check both sides of SMUL_LOHI
14256 SDValue OpS16 = SMULLOHI->getOperand(0);
14257 SDValue OpS32 = SMULLOHI->getOperand(1);
14258
14259 SelectionDAG &DAG = DCI.DAG;
14260 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
14261 OpS16 = OpS32;
14262 OpS32 = SMULLOHI->getOperand(0);
14263 }
14264
14265 SDLoc dl(OR);
14266 unsigned Opcode = 0;
14267 if (isS16(OpS16, DAG))
14268 Opcode = ARMISD::SMULWB;
14269 else if (isSRA16(OpS16)) {
14270 Opcode = ARMISD::SMULWT;
14271 OpS16 = OpS16->getOperand(0);
14272 }
14273 else
14274 return SDValue();
14275
14276 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
14277 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
14278 return SDValue(OR, 0);
14279}
14280
14281static SDValue PerformORCombineToBFI(SDNode *N,
14282 TargetLowering::DAGCombinerInfo &DCI,
14283 const ARMSubtarget *Subtarget) {
14284 // BFI is only available on V6T2+
14285 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14286 return SDValue();
14287
14288 EVT VT = N->getValueType(0);
14289 SDValue N0 = N->getOperand(0);
14290 SDValue N1 = N->getOperand(1);
14291 SelectionDAG &DAG = DCI.DAG;
14292 SDLoc DL(N);
14293 // 1) or (and A, mask), val => ARMbfi A, val, mask
14294 // iff (val & mask) == val
14295 //
14296 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14297 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14298 // && mask == ~mask2
14299 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14300 // && ~mask == mask2
14301 // (i.e., copy a bitfield value into another bitfield of the same width)
14302
14303 if (VT != MVT::i32)
14304 return SDValue();
14305
14306 SDValue N00 = N0.getOperand(0);
14307
14308 // The value and the mask need to be constants so we can verify this is
14309 // actually a bitfield set. If the mask is 0xffff, we can do better
14310 // via a movt instruction, so don't use BFI in that case.
14311 SDValue MaskOp = N0.getOperand(1);
14312 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
14313 if (!MaskC)
14314 return SDValue();
14315 unsigned Mask = MaskC->getZExtValue();
14316 if (Mask == 0xffff)
14317 return SDValue();
14318 SDValue Res;
14319 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14320 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14321 if (N1C) {
14322 unsigned Val = N1C->getZExtValue();
14323 if ((Val & ~Mask) != Val)
14324 return SDValue();
14325
14326 if (ARM::isBitFieldInvertedMask(Mask)) {
14327 Val >>= countTrailingZeros(~Mask);
14328
14329 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14330 DAG.getConstant(Val, DL, MVT::i32),
14331 DAG.getConstant(Mask, DL, MVT::i32));
14332
14333 DCI.CombineTo(N, Res, false);
14334 // Return value from the original node to inform the combiner than N is
14335 // now dead.
14336 return SDValue(N, 0);
14337 }
14338 } else if (N1.getOpcode() == ISD::AND) {
14339 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14340 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14341 if (!N11C)
14342 return SDValue();
14343 unsigned Mask2 = N11C->getZExtValue();
14344
14345 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14346 // as is to match.
14347 if (ARM::isBitFieldInvertedMask(Mask) &&
14348 (Mask == ~Mask2)) {
14349 // The pack halfword instruction works better for masks that fit it,
14350 // so use that when it's available.
14351 if (Subtarget->hasDSP() &&
14352 (Mask == 0xffff || Mask == 0xffff0000))
14353 return SDValue();
14354 // 2a
14355 unsigned amt = countTrailingZeros(Mask2);
14356 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14357 DAG.getConstant(amt, DL, MVT::i32));
14358 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14359 DAG.getConstant(Mask, DL, MVT::i32));
14360 DCI.CombineTo(N, Res, false);
14361 // Return value from the original node to inform the combiner than N is
14362 // now dead.
14363 return SDValue(N, 0);
14364 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14365 (~Mask == Mask2)) {
14366 // The pack halfword instruction works better for masks that fit it,
14367 // so use that when it's available.
14368 if (Subtarget->hasDSP() &&
14369 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14370 return SDValue();
14371 // 2b
14372 unsigned lsb = countTrailingZeros(Mask);
14373 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14374 DAG.getConstant(lsb, DL, MVT::i32));
14375 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14376 DAG.getConstant(Mask2, DL, MVT::i32));
14377 DCI.CombineTo(N, Res, false);
14378 // Return value from the original node to inform the combiner than N is
14379 // now dead.
14380 return SDValue(N, 0);
14381 }
14382 }
14383
14384 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14385 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14386 ARM::isBitFieldInvertedMask(~Mask)) {
14387 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14388 // where lsb(mask) == #shamt and masked bits of B are known zero.
14389 SDValue ShAmt = N00.getOperand(1);
14390 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
14391 unsigned LSB = countTrailingZeros(Mask);
14392 if (ShAmtC != LSB)
14393 return SDValue();
14394
14395 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14396 DAG.getConstant(~Mask, DL, MVT::i32));
14397
14398 DCI.CombineTo(N, Res, false);
14399 // Return value from the original node to inform the combiner than N is
14400 // now dead.
14401 return SDValue(N, 0);
14402 }
14403
14404 return SDValue();
14405}
14406
14407static bool isValidMVECond(unsigned CC, bool IsFloat) {
14408 switch (CC) {
14409 case ARMCC::EQ:
14410 case ARMCC::NE:
14411 case ARMCC::LE:
14412 case ARMCC::GT:
14413 case ARMCC::GE:
14414 case ARMCC::LT:
14415 return true;
14416 case ARMCC::HS:
14417 case ARMCC::HI:
14418 return !IsFloat;
14419 default:
14420 return false;
14421 };
14422}
14423
14424static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
14425 if (N->getOpcode() == ARMISD::VCMP)
14426 return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14427 else if (N->getOpcode() == ARMISD::VCMPZ)
14428 return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14429 else
14430 llvm_unreachable("Not a VCMP/VCMPZ!")::llvm::llvm_unreachable_internal("Not a VCMP/VCMPZ!", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14430)
;
14431}
14432
14433static bool CanInvertMVEVCMP(SDValue N) {
14434 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
14435 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14436}
14437
14438static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG,
14439 const ARMSubtarget *Subtarget) {
14440 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14441 // together with predicates
14442 EVT VT = N->getValueType(0);
14443 SDLoc DL(N);
14444 SDValue N0 = N->getOperand(0);
14445 SDValue N1 = N->getOperand(1);
14446
14447 auto IsFreelyInvertable = [&](SDValue V) {
14448 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14449 return CanInvertMVEVCMP(V);
14450 return false;
14451 };
14452
14453 // At least one operand must be freely invertable.
14454 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14455 return SDValue();
14456
14457 SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14458 SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14459 SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14460 return DAG.getLogicalNOT(DL, And, VT);
14461}
14462
14463/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14464static SDValue PerformORCombine(SDNode *N,
14465 TargetLowering::DAGCombinerInfo &DCI,
14466 const ARMSubtarget *Subtarget) {
14467 // Attempt to use immediate-form VORR
14468 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14469 SDLoc dl(N);
14470 EVT VT = N->getValueType(0);
14471 SelectionDAG &DAG = DCI.DAG;
14472
14473 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14474 return SDValue();
14475
14476 if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14477 VT == MVT::v8i1 || VT == MVT::v16i1))
14478 return PerformORCombine_i1(N, DAG, Subtarget);
14479
14480 APInt SplatBits, SplatUndef;
14481 unsigned SplatBitSize;
14482 bool HasAnyUndefs;
14483 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14484 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14485 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14486 SplatBitSize == 64) {
14487 EVT VorrVT;
14488 SDValue Val =
14489 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14490 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14491 if (Val.getNode()) {
14492 SDValue Input =
14493 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
14494 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14495 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
14496 }
14497 }
14498 }
14499
14500 if (!Subtarget->isThumb1Only()) {
14501 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14502 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14503 return Result;
14504 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14505 return Result;
14506 }
14507
14508 SDValue N0 = N->getOperand(0);
14509 SDValue N1 = N->getOperand(1);
14510
14511 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14512 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14513 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14514
14515 // The code below optimizes (or (and X, Y), Z).
14516 // The AND operand needs to have a single user to make these optimizations
14517 // profitable.
14518 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14519 return SDValue();
14520
14521 APInt SplatUndef;
14522 unsigned SplatBitSize;
14523 bool HasAnyUndefs;
14524
14525 APInt SplatBits0, SplatBits1;
14526 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
14527 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
14528 // Ensure that the second operand of both ands are constants
14529 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14530 HasAnyUndefs) && !HasAnyUndefs) {
14531 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14532 HasAnyUndefs) && !HasAnyUndefs) {
14533 // Ensure that the bit width of the constants are the same and that
14534 // the splat arguments are logical inverses as per the pattern we
14535 // are trying to simplify.
14536 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14537 SplatBits0 == ~SplatBits1) {
14538 // Canonicalize the vector type to make instruction selection
14539 // simpler.
14540 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14541 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
14542 N0->getOperand(1),
14543 N0->getOperand(0),
14544 N1->getOperand(0));
14545 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14546 }
14547 }
14548 }
14549 }
14550
14551 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14552 // reasonable.
14553 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14554 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14555 return Res;
14556 }
14557
14558 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14559 return Result;
14560
14561 return SDValue();
14562}
14563
14564static SDValue PerformXORCombine(SDNode *N,
14565 TargetLowering::DAGCombinerInfo &DCI,
14566 const ARMSubtarget *Subtarget) {
14567 EVT VT = N->getValueType(0);
14568 SelectionDAG &DAG = DCI.DAG;
14569
14570 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14571 return SDValue();
14572
14573 if (!Subtarget->isThumb1Only()) {
14574 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14575 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14576 return Result;
14577
14578 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14579 return Result;
14580 }
14581
14582 if (Subtarget->hasMVEIntegerOps()) {
14583 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14584 SDValue N0 = N->getOperand(0);
14585 SDValue N1 = N->getOperand(1);
14586 const TargetLowering *TLI = Subtarget->getTargetLowering();
14587 if (TLI->isConstTrueVal(N1) &&
14588 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14589 if (CanInvertMVEVCMP(N0)) {
14590 SDLoc DL(N0);
14591 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
14592
14593 SmallVector<SDValue, 4> Ops;
14594 Ops.push_back(N0->getOperand(0));
14595 if (N0->getOpcode() == ARMISD::VCMP)
14596 Ops.push_back(N0->getOperand(1));
14597 Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14598 return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14599 }
14600 }
14601 }
14602
14603 return SDValue();
14604}
14605
14606// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14607// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14608// their position in "to" (Rd).
14609static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14610 assert(N->getOpcode() == ARMISD::BFI)(static_cast <bool> (N->getOpcode() == ARMISD::BFI) ?
void (0) : __assert_fail ("N->getOpcode() == ARMISD::BFI"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 14610, __extension__
__PRETTY_FUNCTION__))
;
14611
14612 SDValue From = N->getOperand(1);
14613 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
14614 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
14615
14616 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14617 // #C in the base of the SHR.
14618 if (From->getOpcode() == ISD::SRL &&
14619 isa<ConstantSDNode>(From->getOperand(1))) {
14620 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
14621 assert(Shift.getLimitedValue() < 32 && "Shift too large!")(static_cast <bool> (Shift.getLimitedValue() < 32 &&
"Shift too large!") ? void (0) : __assert_fail ("Shift.getLimitedValue() < 32 && \"Shift too large!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 14621, __extension__
__PRETTY_FUNCTION__))
;
14622 FromMask <<= Shift.getLimitedValue(31);
14623 From = From->getOperand(0);
14624 }
14625
14626 return From;
14627}
14628
14629// If A and B contain one contiguous set of bits, does A | B == A . B?
14630//
14631// Neither A nor B must be zero.
14632static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14633 unsigned LastActiveBitInA = A.countTrailingZeros();
14634 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
14635 return LastActiveBitInA - 1 == FirstActiveBitInB;
14636}
14637
14638static SDValue FindBFIToCombineWith(SDNode *N) {
14639 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14640 APInt ToMask, FromMask;
14641 SDValue From = ParseBFI(N, ToMask, FromMask);
14642 SDValue To = N->getOperand(0);
14643
14644 SDValue V = To;
14645 if (V.getOpcode() != ARMISD::BFI)
14646 return SDValue();
14647
14648 APInt NewToMask, NewFromMask;
14649 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14650 if (NewFrom != From)
14651 return SDValue();
14652
14653 // Do the written bits conflict with any we've seen so far?
14654 if ((NewToMask & ToMask).getBoolValue())
14655 // Conflicting bits.
14656 return SDValue();
14657
14658 // Are the new bits contiguous when combined with the old bits?
14659 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14660 BitsProperlyConcatenate(FromMask, NewFromMask))
14661 return V;
14662 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14663 BitsProperlyConcatenate(NewFromMask, FromMask))
14664 return V;
14665
14666 return SDValue();
14667}
14668
14669static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG) {
14670 SDValue N0 = N->getOperand(0);
14671 SDValue N1 = N->getOperand(1);
14672
14673 if (N1.getOpcode() == ISD::AND) {
14674 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14675 // the bits being cleared by the AND are not demanded by the BFI.
14676 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14677 if (!N11C)
14678 return SDValue();
14679 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14680 unsigned LSB = countTrailingZeros(~InvMask);
14681 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
14682 assert(Width <(static_cast <bool> (Width < static_cast<unsigned
>(std::numeric_limits<unsigned>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Width < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 14684, __extension__
__PRETTY_FUNCTION__))
14683 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&(static_cast <bool> (Width < static_cast<unsigned
>(std::numeric_limits<unsigned>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Width < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 14684, __extension__
__PRETTY_FUNCTION__))
14684 "undefined behavior")(static_cast <bool> (Width < static_cast<unsigned
>(std::numeric_limits<unsigned>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Width < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 14684, __extension__
__PRETTY_FUNCTION__))
;
14685 unsigned Mask = (1u << Width) - 1;
14686 unsigned Mask2 = N11C->getZExtValue();
14687 if ((Mask & (~Mask2)) == 0)
14688 return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
14689 N->getOperand(0), N1.getOperand(0), N->getOperand(2));
14690 return SDValue();
14691 }
14692
14693 // Look for another BFI to combine with.
14694 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14695 // We've found a BFI.
14696 APInt ToMask1, FromMask1;
14697 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
14698
14699 APInt ToMask2, FromMask2;
14700 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
14701 assert(From1 == From2)(static_cast <bool> (From1 == From2) ? void (0) : __assert_fail
("From1 == From2", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14701, __extension__ __PRETTY_FUNCTION__))
;
14702 (void)From2;
14703
14704 // Create a new BFI, combining the two together.
14705 APInt NewFromMask = FromMask1 | FromMask2;
14706 APInt NewToMask = ToMask1 | ToMask2;
14707
14708 EVT VT = N->getValueType(0);
14709 SDLoc dl(N);
14710
14711 if (NewFromMask[0] == 0)
14712 From1 = DAG.getNode(
14713 ISD::SRL, dl, VT, From1,
14714 DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
14715 return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
14716 DAG.getConstant(~NewToMask, dl, VT));
14717 }
14718
14719 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14720 // that lower bit insertions are performed first, providing that M1 and M2
14721 // do no overlap. This can allow multiple BFI instructions to be combined
14722 // together by the other folds above.
14723 if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
14724 APInt ToMask1 = ~N->getConstantOperandAPInt(2);
14725 APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
14726
14727 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14728 ToMask1.countLeadingZeros() < ToMask2.countLeadingZeros())
14729 return SDValue();
14730
14731 EVT VT = N->getValueType(0);
14732 SDLoc dl(N);
14733 SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
14734 N->getOperand(1), N->getOperand(2));
14735 return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
14736 N0.getOperand(2));
14737 }
14738
14739 return SDValue();
14740}
14741
14742// Check that N is CMPZ(CSINC(0, 0, CC, X)),
14743// or CMPZ(CMOV(1, 0, CC, $cpsr, X))
14744// return X if valid.
14745static SDValue IsCMPZCSINC(SDNode *Cmp, ARMCC::CondCodes &CC) {
14746 if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(Cmp->getOperand(1)))
14747 return SDValue();
14748 SDValue CSInc = Cmp->getOperand(0);
14749
14750 // Ignore any `And 1` nodes that may not yet have been removed. We are
14751 // looking for a value that produces 1/0, so these have no effect on the
14752 // code.
14753 while (CSInc.getOpcode() == ISD::AND &&
14754 isa<ConstantSDNode>(CSInc.getOperand(1)) &&
14755 CSInc.getConstantOperandVal(1) == 1 && CSInc->hasOneUse())
14756 CSInc = CSInc.getOperand(0);
14757
14758 if (CSInc.getOpcode() == ARMISD::CSINC &&
14759 isNullConstant(CSInc.getOperand(0)) &&
14760 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
14761 CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(2);
14762 return CSInc.getOperand(3);
14763 }
14764 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(0)) &&
14765 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
14766 CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(2);
14767 return CSInc.getOperand(4);
14768 }
14769 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(1)) &&
14770 isNullConstant(CSInc.getOperand(0)) && CSInc->hasOneUse()) {
14771 CC = ARMCC::getOppositeCondition(
14772 (ARMCC::CondCodes)CSInc.getConstantOperandVal(2));
14773 return CSInc.getOperand(4);
14774 }
14775 return SDValue();
14776}
14777
14778static SDValue PerformCMPZCombine(SDNode *N, SelectionDAG &DAG) {
14779 // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
14780 // t92: glue = ARMISD::CMPZ t74, 0
14781 // t93: i32 = ARMISD::CSINC 0, 0, 1, t92
14782 // t96: glue = ARMISD::CMPZ t93, 0
14783 // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
14784 ARMCC::CondCodes Cond;
14785 if (SDValue C = IsCMPZCSINC(N, Cond))
14786 if (Cond == ARMCC::EQ)
14787 return C;
14788 return SDValue();
14789}
14790
14791static SDValue PerformCSETCombine(SDNode *N, SelectionDAG &DAG) {
14792 // Fold away an unneccessary CMPZ/CSINC
14793 // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
14794 // if C1==EQ -> CSXYZ A, B, C2, D
14795 // if C1==NE -> CSXYZ A, B, NOT(C2), D
14796 ARMCC::CondCodes Cond;
14797 if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
14798 if (N->getConstantOperandVal(2) == ARMCC::EQ)
14799 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
14800 N->getOperand(1),
14801 DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
14802 if (N->getConstantOperandVal(2) == ARMCC::NE)
14803 return DAG.getNode(
14804 N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
14805 N->getOperand(1),
14806 DAG.getConstant(ARMCC::getOppositeCondition(Cond), SDLoc(N), MVT::i32), C);
14807 }
14808 return SDValue();
14809}
14810
14811/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
14812/// ARMISD::VMOVRRD.
14813static SDValue PerformVMOVRRDCombine(SDNode *N,
14814 TargetLowering::DAGCombinerInfo &DCI,
14815 const ARMSubtarget *Subtarget) {
14816 // vmovrrd(vmovdrr x, y) -> x,y
14817 SDValue InDouble = N->getOperand(0);
14818 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
14819 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
14820
14821 // vmovrrd(load f64) -> (load i32), (load i32)
14822 SDNode *InNode = InDouble.getNode();
14823 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
14824 InNode->getValueType(0) == MVT::f64 &&
14825 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
14826 !cast<LoadSDNode>(InNode)->isVolatile()) {
14827 // TODO: Should this be done for non-FrameIndex operands?
14828 LoadSDNode *LD = cast<LoadSDNode>(InNode);
14829
14830 SelectionDAG &DAG = DCI.DAG;
14831 SDLoc DL(LD);
14832 SDValue BasePtr = LD->getBasePtr();
14833 SDValue NewLD1 =
14834 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
14835 LD->getAlign(), LD->getMemOperand()->getFlags());
14836
14837 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14838 DAG.getConstant(4, DL, MVT::i32));
14839
14840 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
14841 LD->getPointerInfo().getWithOffset(4),
14842 commonAlignment(LD->getAlign(), 4),
14843 LD->getMemOperand()->getFlags());
14844
14845 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
14846 if (DCI.DAG.getDataLayout().isBigEndian())
14847 std::swap (NewLD1, NewLD2);
14848 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
14849 return Result;
14850 }
14851
14852 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
14853 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
14854 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14855 isa<ConstantSDNode>(InDouble.getOperand(1))) {
14856 SDValue BV = InDouble.getOperand(0);
14857 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
14858 // change lane order under big endian.
14859 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
14860 while (
14861 (BV.getOpcode() == ISD::BITCAST ||
14862 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
14863 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
14864 BVSwap = BV.getOpcode() == ISD::BITCAST;
14865 BV = BV.getOperand(0);
14866 }
14867 if (BV.getValueType() != MVT::v4i32)
14868 return SDValue();
14869
14870 // Handle buildvectors, pulling out the correct lane depending on
14871 // endianness.
14872 unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
14873 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
14874 SDValue Op0 = BV.getOperand(Offset);
14875 SDValue Op1 = BV.getOperand(Offset + 1);
14876 if (!Subtarget->isLittle() && BVSwap)
14877 std::swap(Op0, Op1);
14878
14879 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
14880 }
14881
14882 // A chain of insert_vectors, grabbing the correct value of the chain of
14883 // inserts.
14884 SDValue Op0, Op1;
14885 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14886 if (isa<ConstantSDNode>(BV.getOperand(2))) {
14887 if (BV.getConstantOperandVal(2) == Offset)
14888 Op0 = BV.getOperand(1);
14889 if (BV.getConstantOperandVal(2) == Offset + 1)
14890 Op1 = BV.getOperand(1);
14891 }
14892 BV = BV.getOperand(0);
14893 }
14894 if (!Subtarget->isLittle() && BVSwap)
14895 std::swap(Op0, Op1);
14896 if (Op0 && Op1)
14897 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
14898 }
14899
14900 return SDValue();
14901}
14902
14903/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
14904/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
14905static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
14906 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
14907 SDValue Op0 = N->getOperand(0);
14908 SDValue Op1 = N->getOperand(1);
14909 if (Op0.getOpcode() == ISD::BITCAST)
14910 Op0 = Op0.getOperand(0);
14911 if (Op1.getOpcode() == ISD::BITCAST)
14912 Op1 = Op1.getOperand(0);
14913 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
14914 Op0.getNode() == Op1.getNode() &&
14915 Op0.getResNo() == 0 && Op1.getResNo() == 1)
14916 return DAG.getNode(ISD::BITCAST, SDLoc(N),
14917 N->getValueType(0), Op0.getOperand(0));
14918 return SDValue();
14919}
14920
14921static SDValue PerformVMOVhrCombine(SDNode *N,
14922 TargetLowering::DAGCombinerInfo &DCI) {
14923 SDValue Op0 = N->getOperand(0);
14924
14925 // VMOVhr (VMOVrh (X)) -> X
14926 if (Op0->getOpcode() == ARMISD::VMOVrh)
14927 return Op0->getOperand(0);
14928
14929 // FullFP16: half values are passed in S-registers, and we don't
14930 // need any of the bitcast and moves:
14931 //
14932 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
14933 // t5: i32 = bitcast t2
14934 // t18: f16 = ARMISD::VMOVhr t5
14935 if (Op0->getOpcode() == ISD::BITCAST) {
14936 SDValue Copy = Op0->getOperand(0);
14937 if (Copy.getValueType() == MVT::f32 &&
14938 Copy->getOpcode() == ISD::CopyFromReg) {
14939 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
14940 SDValue NewCopy =
14941 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops);
14942 return NewCopy;
14943 }
14944 }
14945
14946 // fold (VMOVhr (load x)) -> (load (f16*)x)
14947 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
14948 if (LN0->hasOneUse() && LN0->isUnindexed() &&
14949 LN0->getMemoryVT() == MVT::i16) {
14950 SDValue Load =
14951 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
14952 LN0->getBasePtr(), LN0->getMemOperand());
14953 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
14954 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
14955 return Load;
14956 }
14957 }
14958
14959 // Only the bottom 16 bits of the source register are used.
14960 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
14961 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14962 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
14963 return SDValue(N, 0);
14964
14965 return SDValue();
14966}
14967
14968static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG) {
14969 SDValue N0 = N->getOperand(0);
14970 EVT VT = N->getValueType(0);
14971
14972 // fold (VMOVrh (fpconst x)) -> const x
14973 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
14974 APFloat V = C->getValueAPF();
14975 return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
14976 }
14977
14978 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
14979 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
14980 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
14981
14982 SDValue Load =
14983 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
14984 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
14985 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
14986 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
14987 return Load;
14988 }
14989
14990 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
14991 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14992 isa<ConstantSDNode>(N0->getOperand(1)))
14993 return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
14994 N0->getOperand(1));
14995
14996 return SDValue();
14997}
14998
14999/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15000/// are normal, non-volatile loads. If so, it is profitable to bitcast an
15001/// i64 vector to have f64 elements, since the value can then be loaded
15002/// directly into a VFP register.
15003static bool hasNormalLoadOperand(SDNode *N) {
15004 unsigned NumElts = N->getValueType(0).getVectorNumElements();
15005 for (unsigned i = 0; i < NumElts; ++i) {
15006 SDNode *Elt = N->getOperand(i).getNode();
15007 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
15008 return true;
15009 }
15010 return false;
15011}
15012
15013/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15014/// ISD::BUILD_VECTOR.
15015static SDValue PerformBUILD_VECTORCombine(SDNode *N,
15016 TargetLowering::DAGCombinerInfo &DCI,
15017 const ARMSubtarget *Subtarget) {
15018 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15019 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
15020 // into a pair of GPRs, which is fine when the value is used as a scalar,
15021 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15022 SelectionDAG &DAG = DCI.DAG;
15023 if (N->getNumOperands() == 2)
15024 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15025 return RV;
15026
15027 // Load i64 elements as f64 values so that type legalization does not split
15028 // them up into i32 values.
15029 EVT VT = N->getValueType(0);
15030 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15031 return SDValue();
15032 SDLoc dl(N);
15033 SmallVector<SDValue, 8> Ops;
15034 unsigned NumElts = VT.getVectorNumElements();
15035 for (unsigned i = 0; i < NumElts; ++i) {
15036 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
15037 Ops.push_back(V);
15038 // Make the DAGCombiner fold the bitcast.
15039 DCI.AddToWorklist(V.getNode());
15040 }
15041 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
15042 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
15043 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
15044}
15045
15046/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15047static SDValue
15048PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15049 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15050 // At that time, we may have inserted bitcasts from integer to float.
15051 // If these bitcasts have survived DAGCombine, change the lowering of this
15052 // BUILD_VECTOR in something more vector friendly, i.e., that does not
15053 // force to use floating point types.
15054
15055 // Make sure we can change the type of the vector.
15056 // This is possible iff:
15057 // 1. The vector is only used in a bitcast to a integer type. I.e.,
15058 // 1.1. Vector is used only once.
15059 // 1.2. Use is a bit convert to an integer type.
15060 // 2. The size of its operands are 32-bits (64-bits are not legal).
15061 EVT VT = N->getValueType(0);
15062 EVT EltVT = VT.getVectorElementType();
15063
15064 // Check 1.1. and 2.
15065 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15066 return SDValue();
15067
15068 // By construction, the input type must be float.
15069 assert(EltVT == MVT::f32 && "Unexpected type!")(static_cast <bool> (EltVT == MVT::f32 && "Unexpected type!"
) ? void (0) : __assert_fail ("EltVT == MVT::f32 && \"Unexpected type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 15069, __extension__
__PRETTY_FUNCTION__))
;
15070
15071 // Check 1.2.
15072 SDNode *Use = *N->use_begin();
15073 if (Use->getOpcode() != ISD::BITCAST ||
15074 Use->getValueType(0).isFloatingPoint())
15075 return SDValue();
15076
15077 // Check profitability.
15078 // Model is, if more than half of the relevant operands are bitcast from
15079 // i32, turn the build_vector into a sequence of insert_vector_elt.
15080 // Relevant operands are everything that is not statically
15081 // (i.e., at compile time) bitcasted.
15082 unsigned NumOfBitCastedElts = 0;
15083 unsigned NumElts = VT.getVectorNumElements();
15084 unsigned NumOfRelevantElts = NumElts;
15085 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15086 SDValue Elt = N->getOperand(Idx);
15087 if (Elt->getOpcode() == ISD::BITCAST) {
15088 // Assume only bit cast to i32 will go away.
15089 if (Elt->getOperand(0).getValueType() == MVT::i32)
15090 ++NumOfBitCastedElts;
15091 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
15092 // Constants are statically casted, thus do not count them as
15093 // relevant operands.
15094 --NumOfRelevantElts;
15095 }
15096
15097 // Check if more than half of the elements require a non-free bitcast.
15098 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15099 return SDValue();
15100
15101 SelectionDAG &DAG = DCI.DAG;
15102 // Create the new vector type.
15103 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
15104 // Check if the type is legal.
15105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15106 if (!TLI.isTypeLegal(VecVT))
15107 return SDValue();
15108
15109 // Combine:
15110 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15111 // => BITCAST INSERT_VECTOR_ELT
15112 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15113 // (BITCAST EN), N.
15114 SDValue Vec = DAG.getUNDEF(VecVT);
15115 SDLoc dl(N);
15116 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15117 SDValue V = N->getOperand(Idx);
15118 if (V.isUndef())
15119 continue;
15120 if (V.getOpcode() == ISD::BITCAST &&
15121 V->getOperand(0).getValueType() == MVT::i32)
15122 // Fold obvious case.
15123 V = V.getOperand(0);
15124 else {
15125 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
15126 // Make the DAGCombiner fold the bitcasts.
15127 DCI.AddToWorklist(V.getNode());
15128 }
15129 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
15130 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
15131 }
15132 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
15133 // Make the DAGCombiner fold the bitcasts.
15134 DCI.AddToWorklist(Vec.getNode());
15135 return Vec;
15136}
15137
15138static SDValue
15139PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15140 EVT VT = N->getValueType(0);
15141 SDValue Op = N->getOperand(0);
15142 SDLoc dl(N);
15143
15144 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15145 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15146 // If the valuetypes are the same, we can remove the cast entirely.
15147 if (Op->getOperand(0).getValueType() == VT)
15148 return Op->getOperand(0);
15149 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15150 }
15151
15152 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15153 // more VPNOT which might get folded as else predicates.
15154 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
15155 SDValue X =
15156 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15157 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
15158 DCI.DAG.getConstant(65535, dl, MVT::i32));
15159 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
15160 }
15161
15162 // Only the bottom 16 bits of the source register are used.
15163 if (Op.getValueType() == MVT::i32) {
15164 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15165 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15166 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15167 return SDValue(N, 0);
15168 }
15169 return SDValue();
15170}
15171
15172static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG,
15173 const ARMSubtarget *ST) {
15174 EVT VT = N->getValueType(0);
15175 SDValue Op = N->getOperand(0);
15176 SDLoc dl(N);
15177
15178 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15179 if (ST->isLittle())
15180 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
15181
15182 // VECTOR_REG_CAST undef -> undef
15183 if (Op.isUndef())
15184 return DAG.getUNDEF(VT);
15185
15186 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15187 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15188 // If the valuetypes are the same, we can remove the cast entirely.
15189 if (Op->getOperand(0).getValueType() == VT)
15190 return Op->getOperand(0);
15191 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
15192 }
15193
15194 return SDValue();
15195}
15196
15197static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG,
15198 const ARMSubtarget *Subtarget) {
15199 if (!Subtarget->hasMVEIntegerOps())
15200 return SDValue();
15201
15202 EVT VT = N->getValueType(0);
15203 SDValue Op0 = N->getOperand(0);
15204 SDValue Op1 = N->getOperand(1);
15205 ARMCC::CondCodes Cond =
15206 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15207 SDLoc dl(N);
15208
15209 // vcmp X, 0, cc -> vcmpz X, cc
15210 if (isZeroVector(Op1))
15211 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
15212
15213 unsigned SwappedCond = getSwappedCondition(Cond);
15214 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
15215 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15216 if (isZeroVector(Op0))
15217 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
15218 DAG.getConstant(SwappedCond, dl, MVT::i32));
15219 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15220 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15221 return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
15222 DAG.getConstant(SwappedCond, dl, MVT::i32));
15223 }
15224
15225 return SDValue();
15226}
15227
15228/// PerformInsertEltCombine - Target-specific dag combine xforms for
15229/// ISD::INSERT_VECTOR_ELT.
15230static SDValue PerformInsertEltCombine(SDNode *N,
15231 TargetLowering::DAGCombinerInfo &DCI) {
15232 // Bitcast an i64 load inserted into a vector to f64.
15233 // Otherwise, the i64 value will be legalized to a pair of i32 values.
15234 EVT VT = N->getValueType(0);
15235 SDNode *Elt = N->getOperand(1).getNode();
15236 if (VT.getVectorElementType() != MVT::i64 ||
15237 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
15238 return SDValue();
15239
15240 SelectionDAG &DAG = DCI.DAG;
15241 SDLoc dl(N);
15242 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
15243 VT.getVectorNumElements());
15244 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
15245 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
15246 // Make the DAGCombiner fold the bitcasts.
15247 DCI.AddToWorklist(Vec.getNode());
15248 DCI.AddToWorklist(V.getNode());
15249 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
15250 Vec, V, N->getOperand(2));
15251 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
15252}
15253
15254// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15255// directly or bitcast to an integer if the original is a float vector.
15256// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
15257// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
15258static SDValue
15259PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15260 EVT VT = N->getValueType(0);
15261 SDLoc dl(N);
15262
15263 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15264 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
15265 return SDValue();
15266
15267 SDValue Ext = SDValue(N, 0);
15268 if (Ext.getOpcode() == ISD::BITCAST &&
15269 Ext.getOperand(0).getValueType() == MVT::f32)
15270 Ext = Ext.getOperand(0);
15271 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15272 !isa<ConstantSDNode>(Ext.getOperand(1)) ||
15273 Ext.getConstantOperandVal(1) % 2 != 0)
15274 return SDValue();
15275 if (Ext->use_size() == 1 &&
15276 (Ext->use_begin()->getOpcode() == ISD::SINT_TO_FP ||
15277 Ext->use_begin()->getOpcode() == ISD::UINT_TO_FP))
15278 return SDValue();
15279
15280 SDValue Op0 = Ext.getOperand(0);
15281 EVT VecVT = Op0.getValueType();
15282 unsigned ResNo = Op0.getResNo();
15283 unsigned Lane = Ext.getConstantOperandVal(1);
15284 if (VecVT.getVectorNumElements() != 4)
15285 return SDValue();
15286
15287 // Find another extract, of Lane + 1
15288 auto OtherIt = find_if(Op0->uses(), [&](SDNode *V) {
15289 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15290 isa<ConstantSDNode>(V->getOperand(1)) &&
15291 V->getConstantOperandVal(1) == Lane + 1 &&
15292 V->getOperand(0).getResNo() == ResNo;
15293 });
15294 if (OtherIt == Op0->uses().end())
15295 return SDValue();
15296
15297 // For float extracts, we need to be converting to a i32 for both vector
15298 // lanes.
15299 SDValue OtherExt(*OtherIt, 0);
15300 if (OtherExt.getValueType() != MVT::i32) {
15301 if (OtherExt->use_size() != 1 ||
15302 OtherExt->use_begin()->getOpcode() != ISD::BITCAST ||
15303 OtherExt->use_begin()->getValueType(0) != MVT::i32)
15304 return SDValue();
15305 OtherExt = SDValue(*OtherExt->use_begin(), 0);
15306 }
15307
15308 // Convert the type to a f64 and extract with a VMOVRRD.
15309 SDValue F64 = DCI.DAG.getNode(
15310 ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
15311 DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
15312 DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
15313 SDValue VMOVRRD =
15314 DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
15315
15316 DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
15317 return VMOVRRD;
15318}
15319
15320static SDValue PerformExtractEltCombine(SDNode *N,
15321 TargetLowering::DAGCombinerInfo &DCI,
15322 const ARMSubtarget *ST) {
15323 SDValue Op0 = N->getOperand(0);
15324 EVT VT = N->getValueType(0);
15325 SDLoc dl(N);
15326
15327 // extract (vdup x) -> x
15328 if (Op0->getOpcode() == ARMISD::VDUP) {
15329 SDValue X = Op0->getOperand(0);
15330 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15331 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
15332 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15333 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
15334 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15335 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
15336
15337 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15338 X = X->getOperand(0);
15339 if (X.getValueType() == VT)
15340 return X;
15341 }
15342
15343 // extract ARM_BUILD_VECTOR -> x
15344 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15345 isa<ConstantSDNode>(N->getOperand(1)) &&
15346 N->getConstantOperandVal(1) < Op0.getNumOperands()) {
15347 return Op0.getOperand(N->getConstantOperandVal(1));
15348 }
15349
15350 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15351 if (Op0.getValueType() == MVT::v4i32 &&
15352 isa<ConstantSDNode>(N->getOperand(1)) &&
15353 Op0.getOpcode() == ISD::BITCAST &&
15354 Op0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
15355 Op0.getOperand(0).getValueType() == MVT::v2f64) {
15356 SDValue BV = Op0.getOperand(0);
15357 unsigned Offset = N->getConstantOperandVal(1);
15358 SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
15359 if (MOV.getOpcode() == ARMISD::VMOVDRR)
15360 return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15361 }
15362
15363 // extract x, n; extract x, n+1 -> VMOVRRD x
15364 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15365 return R;
15366
15367 // extract (MVETrunc(x)) -> extract x
15368 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15369 unsigned Idx = N->getConstantOperandVal(1);
15370 unsigned Vec =
15371 Idx / Op0->getOperand(0).getValueType().getVectorNumElements();
15372 unsigned SubIdx =
15373 Idx % Op0->getOperand(0).getValueType().getVectorNumElements();
15374 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15375 DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15376 }
15377
15378 return SDValue();
15379}
15380
15381static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) {
15382 SDValue Op = N->getOperand(0);
15383 EVT VT = N->getValueType(0);
15384
15385 // sext_inreg(VGETLANEu) -> VGETLANEs
15386 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15387 cast<VTSDNode>(N->getOperand(1))->getVT() ==
15388 Op.getOperand(0).getValueType().getScalarType())
15389 return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15390 Op.getOperand(1));
15391
15392 return SDValue();
15393}
15394
15395// When lowering complex nodes that we recognize, like VQDMULH and MULH, we
15396// can end up with shuffle(binop(shuffle, shuffle)), that can be simplified to
15397// binop as the shuffles cancel out.
15398static SDValue FlattenVectorShuffle(ShuffleVectorSDNode *N, SelectionDAG &DAG) {
15399 EVT VT = N->getValueType(0);
15400 if (!N->getOperand(1).isUndef() || N->getOperand(0).getValueType() != VT)
15401 return SDValue();
15402 SDValue Op = N->getOperand(0);
15403
15404 // Looking for binary operators that will have been folded from
15405 // truncates/extends.
15406 switch (Op.getOpcode()) {
15407 case ARMISD::VQDMULH:
15408 case ISD::MULHS:
15409 case ISD::MULHU:
15410 case ISD::ABDS:
15411 case ISD::ABDU:
15412 case ISD::AVGFLOORS:
15413 case ISD::AVGFLOORU:
15414 case ISD::AVGCEILS:
15415 case ISD::AVGCEILU:
15416 break;
15417 default:
15418 return SDValue();
15419 }
15420
15421 ShuffleVectorSDNode *Op0 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(0));
15422 ShuffleVectorSDNode *Op1 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(1));
15423 if (!Op0 || !Op1 || !Op0->getOperand(1).isUndef() ||
15424 !Op1->getOperand(1).isUndef() || Op0->getMask() != Op1->getMask() ||
15425 Op0->getOperand(0).getValueType() != VT)
15426 return SDValue();
15427
15428 // Check the mask turns into an identity shuffle.
15429 ArrayRef<int> NMask = N->getMask();
15430 ArrayRef<int> OpMask = Op0->getMask();
15431 for (int i = 0, e = NMask.size(); i != e; i++) {
15432 if (NMask[i] > 0 && OpMask[NMask[i]] > 0 && OpMask[NMask[i]] != i)
15433 return SDValue();
15434 }
15435
15436 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
15437 Op0->getOperand(0), Op1->getOperand(0));
15438}
15439
15440static SDValue
15441PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15442 SDValue Vec = N->getOperand(0);
15443 SDValue SubVec = N->getOperand(1);
15444 uint64_t IdxVal = N->getConstantOperandVal(2);
15445 EVT VecVT = Vec.getValueType();
15446 EVT SubVT = SubVec.getValueType();
15447
15448 // Only do this for legal fixed vector types.
15449 if (!VecVT.isFixedLengthVector() ||
15450 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15451 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
15452 return SDValue();
15453
15454 // Ignore widening patterns.
15455 if (IdxVal == 0 && Vec.isUndef())
15456 return SDValue();
15457
15458 // Subvector must be half the width and an "aligned" insertion.
15459 unsigned NumSubElts = SubVT.getVectorNumElements();
15460 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15461 (IdxVal != 0 && IdxVal != NumSubElts))
15462 return SDValue();
15463
15464 // Fold insert_subvector -> concat_vectors
15465 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15466 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15467 SDLoc DL(N);
15468 SDValue Lo, Hi;
15469 if (IdxVal == 0) {
15470 Lo = SubVec;
15471 Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15472 DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15473 } else {
15474 Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15475 DCI.DAG.getVectorIdxConstant(0, DL));
15476 Hi = SubVec;
15477 }
15478 return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15479}
15480
15481// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15482static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N,
15483 SelectionDAG &DAG) {
15484 SDValue Trunc = N->getOperand(0);
15485 EVT VT = Trunc.getValueType();
15486 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15487 return SDValue();
15488
15489 SDLoc DL(Trunc);
15490 if (isVMOVNTruncMask(N->getMask(), VT, false))
15491 return DAG.getNode(
15492 ARMISD::VMOVN, DL, VT,
15493 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15494 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15495 DAG.getConstant(1, DL, MVT::i32));
15496 else if (isVMOVNTruncMask(N->getMask(), VT, true))
15497 return DAG.getNode(
15498 ARMISD::VMOVN, DL, VT,
15499 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15500 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15501 DAG.getConstant(1, DL, MVT::i32));
15502 return SDValue();
15503}
15504
15505/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15506/// ISD::VECTOR_SHUFFLE.
15507static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
15508 if (SDValue R = FlattenVectorShuffle(cast<ShuffleVectorSDNode>(N), DAG))
15509 return R;
15510 if (SDValue R = PerformShuffleVMOVNCombine(cast<ShuffleVectorSDNode>(N), DAG))
15511 return R;
15512
15513 // The LLVM shufflevector instruction does not require the shuffle mask
15514 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15515 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15516 // operands do not match the mask length, they are extended by concatenating
15517 // them with undef vectors. That is probably the right thing for other
15518 // targets, but for NEON it is better to concatenate two double-register
15519 // size vector operands into a single quad-register size vector. Do that
15520 // transformation here:
15521 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15522 // shuffle(concat(v1, v2), undef)
15523 SDValue Op0 = N->getOperand(0);
15524 SDValue Op1 = N->getOperand(1);
15525 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15526 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15527 Op0.getNumOperands() != 2 ||
15528 Op1.getNumOperands() != 2)
15529 return SDValue();
15530 SDValue Concat0Op1 = Op0.getOperand(1);
15531 SDValue Concat1Op1 = Op1.getOperand(1);
15532 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15533 return SDValue();
15534 // Skip the transformation if any of the types are illegal.
15535 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15536 EVT VT = N->getValueType(0);
15537 if (!TLI.isTypeLegal(VT) ||
15538 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
15539 !TLI.isTypeLegal(Concat1Op1.getValueType()))
15540 return SDValue();
15541
15542 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
15543 Op0.getOperand(0), Op1.getOperand(0));
15544 // Translate the shuffle mask.
15545 SmallVector<int, 16> NewMask;
15546 unsigned NumElts = VT.getVectorNumElements();
15547 unsigned HalfElts = NumElts/2;
15548 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15549 for (unsigned n = 0; n < NumElts; ++n) {
15550 int MaskElt = SVN->getMaskElt(n);
15551 int NewElt = -1;
15552 if (MaskElt < (int)HalfElts)
15553 NewElt = MaskElt;
15554 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15555 NewElt = HalfElts + MaskElt - NumElts;
15556 NewMask.push_back(NewElt);
15557 }
15558 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
15559 DAG.getUNDEF(VT), NewMask);
15560}
15561
15562/// Load/store instruction that can be merged with a base address
15563/// update
15564struct BaseUpdateTarget {
15565 SDNode *N;
15566 bool isIntrinsic;
15567 bool isStore;
15568 unsigned AddrOpIdx;
15569};
15570
15571struct BaseUpdateUser {
15572 /// Instruction that updates a pointer
15573 SDNode *N;
15574 /// Pointer increment operand
15575 SDValue Inc;
15576 /// Pointer increment value if it is a constant, or 0 otherwise
15577 unsigned ConstInc;
15578};
15579
15580static bool TryCombineBaseUpdate(struct BaseUpdateTarget &Target,
15581 struct BaseUpdateUser &User,
15582 bool SimpleConstIncOnly,
15583 TargetLowering::DAGCombinerInfo &DCI) {
15584 SelectionDAG &DAG = DCI.DAG;
15585 SDNode *N = Target.N;
15586 MemSDNode *MemN = cast<MemSDNode>(N);
15587 SDLoc dl(N);
15588
15589 // Find the new opcode for the updating load/store.
15590 bool isLoadOp = true;
15591 bool isLaneOp = false;
15592 // Workaround for vst1x and vld1x intrinsics which do not have alignment
15593 // as an operand.
15594 bool hasAlignment = true;
15595 unsigned NewOpc = 0;
15596 unsigned NumVecs = 0;
15597 if (Target.isIntrinsic) {
15598 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15599 switch (IntNo) {
15600 default:
15601 llvm_unreachable("unexpected intrinsic for Neon base update")::llvm::llvm_unreachable_internal("unexpected intrinsic for Neon base update"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 15601)
;
15602 case Intrinsic::arm_neon_vld1:
15603 NewOpc = ARMISD::VLD1_UPD;
15604 NumVecs = 1;
15605 break;
15606 case Intrinsic::arm_neon_vld2:
15607 NewOpc = ARMISD::VLD2_UPD;
15608 NumVecs = 2;
15609 break;
15610 case Intrinsic::arm_neon_vld3:
15611 NewOpc = ARMISD::VLD3_UPD;
15612 NumVecs = 3;
15613 break;
15614 case Intrinsic::arm_neon_vld4:
15615 NewOpc = ARMISD::VLD4_UPD;
15616 NumVecs = 4;
15617 break;
15618 case Intrinsic::arm_neon_vld1x2:
15619 NewOpc = ARMISD::VLD1x2_UPD;
15620 NumVecs = 2;
15621 hasAlignment = false;
15622 break;
15623 case Intrinsic::arm_neon_vld1x3:
15624 NewOpc = ARMISD::VLD1x3_UPD;
15625 NumVecs = 3;
15626 hasAlignment = false;
15627 break;
15628 case Intrinsic::arm_neon_vld1x4:
15629 NewOpc = ARMISD::VLD1x4_UPD;
15630 NumVecs = 4;
15631 hasAlignment = false;
15632 break;
15633 case Intrinsic::arm_neon_vld2dup:
15634 NewOpc = ARMISD::VLD2DUP_UPD;
15635 NumVecs = 2;
15636 break;
15637 case Intrinsic::arm_neon_vld3dup:
15638 NewOpc = ARMISD::VLD3DUP_UPD;
15639 NumVecs = 3;
15640 break;
15641 case Intrinsic::arm_neon_vld4dup:
15642 NewOpc = ARMISD::VLD4DUP_UPD;
15643 NumVecs = 4;
15644 break;
15645 case Intrinsic::arm_neon_vld2lane:
15646 NewOpc = ARMISD::VLD2LN_UPD;
15647 NumVecs = 2;
15648 isLaneOp = true;
15649 break;
15650 case Intrinsic::arm_neon_vld3lane:
15651 NewOpc = ARMISD::VLD3LN_UPD;
15652 NumVecs = 3;
15653 isLaneOp = true;
15654 break;
15655 case Intrinsic::arm_neon_vld4lane:
15656 NewOpc = ARMISD::VLD4LN_UPD;
15657 NumVecs = 4;
15658 isLaneOp = true;
15659 break;
15660 case Intrinsic::arm_neon_vst1:
15661 NewOpc = ARMISD::VST1_UPD;
15662 NumVecs = 1;
15663 isLoadOp = false;
15664 break;
15665 case Intrinsic::arm_neon_vst2:
15666 NewOpc = ARMISD::VST2_UPD;
15667 NumVecs = 2;
15668 isLoadOp = false;
15669 break;
15670 case Intrinsic::arm_neon_vst3:
15671 NewOpc = ARMISD::VST3_UPD;
15672 NumVecs = 3;
15673 isLoadOp = false;
15674 break;
15675 case Intrinsic::arm_neon_vst4:
15676 NewOpc = ARMISD::VST4_UPD;
15677 NumVecs = 4;
15678 isLoadOp = false;
15679 break;
15680 case Intrinsic::arm_neon_vst2lane:
15681 NewOpc = ARMISD::VST2LN_UPD;
15682 NumVecs = 2;
15683 isLoadOp = false;
15684 isLaneOp = true;
15685 break;
15686 case Intrinsic::arm_neon_vst3lane:
15687 NewOpc = ARMISD::VST3LN_UPD;
15688 NumVecs = 3;
15689 isLoadOp = false;
15690 isLaneOp = true;
15691 break;
15692 case Intrinsic::arm_neon_vst4lane:
15693 NewOpc = ARMISD::VST4LN_UPD;
15694 NumVecs = 4;
15695 isLoadOp = false;
15696 isLaneOp = true;
15697 break;
15698 case Intrinsic::arm_neon_vst1x2:
15699 NewOpc = ARMISD::VST1x2_UPD;
15700 NumVecs = 2;
15701 isLoadOp = false;
15702 hasAlignment = false;
15703 break;
15704 case Intrinsic::arm_neon_vst1x3:
15705 NewOpc = ARMISD::VST1x3_UPD;
15706 NumVecs = 3;
15707 isLoadOp = false;
15708 hasAlignment = false;
15709 break;
15710 case Intrinsic::arm_neon_vst1x4:
15711 NewOpc = ARMISD::VST1x4_UPD;
15712 NumVecs = 4;
15713 isLoadOp = false;
15714 hasAlignment = false;
15715 break;
15716 }
15717 } else {
15718 isLaneOp = true;
15719 switch (N->getOpcode()) {
15720 default:
15721 llvm_unreachable("unexpected opcode for Neon base update")::llvm::llvm_unreachable_internal("unexpected opcode for Neon base update"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 15721)
;
15722 case ARMISD::VLD1DUP:
15723 NewOpc = ARMISD::VLD1DUP_UPD;
15724 NumVecs = 1;
15725 break;
15726 case ARMISD::VLD2DUP:
15727 NewOpc = ARMISD::VLD2DUP_UPD;
15728 NumVecs = 2;
15729 break;
15730 case ARMISD::VLD3DUP:
15731 NewOpc = ARMISD::VLD3DUP_UPD;
15732 NumVecs = 3;
15733 break;
15734 case ARMISD::VLD4DUP:
15735 NewOpc = ARMISD::VLD4DUP_UPD;
15736 NumVecs = 4;
15737 break;
15738 case ISD::LOAD:
15739 NewOpc = ARMISD::VLD1_UPD;
15740 NumVecs = 1;
15741 isLaneOp = false;
15742 break;
15743 case ISD::STORE:
15744 NewOpc = ARMISD::VST1_UPD;
15745 NumVecs = 1;
15746 isLaneOp = false;
15747 isLoadOp = false;
15748 break;
15749 }
15750 }
15751
15752 // Find the size of memory referenced by the load/store.
15753 EVT VecTy;
15754 if (isLoadOp) {
15755 VecTy = N->getValueType(0);
15756 } else if (Target.isIntrinsic) {
15757 VecTy = N->getOperand(Target.AddrOpIdx + 1).getValueType();
15758 } else {
15759 assert(Target.isStore &&(static_cast <bool> (Target.isStore && "Node has to be a load, a store, or an intrinsic!"
) ? void (0) : __assert_fail ("Target.isStore && \"Node has to be a load, a store, or an intrinsic!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 15760, __extension__
__PRETTY_FUNCTION__))
15760 "Node has to be a load, a store, or an intrinsic!")(static_cast <bool> (Target.isStore && "Node has to be a load, a store, or an intrinsic!"
) ? void (0) : __assert_fail ("Target.isStore && \"Node has to be a load, a store, or an intrinsic!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 15760, __extension__
__PRETTY_FUNCTION__))
;
15761 VecTy = N->getOperand(1).getValueType();
15762 }
15763
15764 bool isVLDDUPOp =
15765 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
15766 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
15767
15768 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15769 if (isLaneOp || isVLDDUPOp)
15770 NumBytes /= VecTy.getVectorNumElements();
15771
15772 if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
15773 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
15774 // separate instructions that make it harder to use a non-constant update.
15775 return false;
15776 }
15777
15778 if (SimpleConstIncOnly && User.ConstInc != NumBytes)
15779 return false;
15780
15781 // OK, we found an ADD we can fold into the base update.
15782 // Now, create a _UPD node, taking care of not breaking alignment.
15783
15784 EVT AlignedVecTy = VecTy;
15785 Align Alignment = MemN->getAlign();
15786
15787 // If this is a less-than-standard-aligned load/store, change the type to
15788 // match the standard alignment.
15789 // The alignment is overlooked when selecting _UPD variants; and it's
15790 // easier to introduce bitcasts here than fix that.
15791 // There are 3 ways to get to this base-update combine:
15792 // - intrinsics: they are assumed to be properly aligned (to the standard
15793 // alignment of the memory type), so we don't need to do anything.
15794 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
15795 // intrinsics, so, likewise, there's nothing to do.
15796 // - generic load/store instructions: the alignment is specified as an
15797 // explicit operand, rather than implicitly as the standard alignment
15798 // of the memory type (like the intrisics). We need to change the
15799 // memory type to match the explicit alignment. That way, we don't
15800 // generate non-standard-aligned ARMISD::VLDx nodes.
15801 if (isa<LSBaseSDNode>(N)) {
15802 if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
15803 MVT EltTy = MVT::getIntegerVT(Alignment.value() * 8);
15804 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.")(static_cast <bool> (NumVecs == 1 && "Unexpected multi-element generic load/store."
) ? void (0) : __assert_fail ("NumVecs == 1 && \"Unexpected multi-element generic load/store.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 15804, __extension__
__PRETTY_FUNCTION__))
;
15805 assert(!isLaneOp && "Unexpected generic load/store lane.")(static_cast <bool> (!isLaneOp && "Unexpected generic load/store lane."
) ? void (0) : __assert_fail ("!isLaneOp && \"Unexpected generic load/store lane.\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 15805, __extension__
__PRETTY_FUNCTION__))
;
15806 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
15807 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
15808 }
15809 // Don't set an explicit alignment on regular load/stores that we want
15810 // to transform to VLD/VST 1_UPD nodes.
15811 // This matches the behavior of regular load/stores, which only get an
15812 // explicit alignment if the MMO alignment is larger than the standard
15813 // alignment of the memory type.
15814 // Intrinsics, however, always get an explicit alignment, set to the
15815 // alignment of the MMO.
15816 Alignment = Align(1);
15817 }
15818
15819 // Create the new updating load/store node.
15820 // First, create an SDVTList for the new updating node's results.
15821 EVT Tys[6];
15822 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
15823 unsigned n;
15824 for (n = 0; n < NumResultVecs; ++n)
15825 Tys[n] = AlignedVecTy;
15826 Tys[n++] = MVT::i32;
15827 Tys[n] = MVT::Other;
15828 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
15829
15830 // Then, gather the new node's operands.
15831 SmallVector<SDValue, 8> Ops;
15832 Ops.push_back(N->getOperand(0)); // incoming chain
15833 Ops.push_back(N->getOperand(Target.AddrOpIdx));
15834 Ops.push_back(User.Inc);
15835
15836 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
15837 // Try to match the intrinsic's signature
15838 Ops.push_back(StN->getValue());
15839 } else {
15840 // Loads (and of course intrinsics) match the intrinsics' signature,
15841 // so just add all but the alignment operand.
15842 unsigned LastOperand =
15843 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
15844 for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
15845 Ops.push_back(N->getOperand(i));
15846 }
15847
15848 // For all node types, the alignment operand is always the last one.
15849 Ops.push_back(DAG.getConstant(Alignment.value(), dl, MVT::i32));
15850
15851 // If this is a non-standard-aligned STORE, the penultimate operand is the
15852 // stored value. Bitcast it to the aligned type.
15853 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
15854 SDValue &StVal = Ops[Ops.size() - 2];
15855 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
15856 }
15857
15858 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
15859 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
15860 MemN->getMemOperand());
15861
15862 // Update the uses.
15863 SmallVector<SDValue, 5> NewResults;
15864 for (unsigned i = 0; i < NumResultVecs; ++i)
15865 NewResults.push_back(SDValue(UpdN.getNode(), i));
15866
15867 // If this is an non-standard-aligned LOAD, the first result is the loaded
15868 // value. Bitcast it to the expected result type.
15869 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
15870 SDValue &LdVal = NewResults[0];
15871 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
15872 }
15873
15874 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
15875 DCI.CombineTo(N, NewResults);
15876 DCI.CombineTo(User.N, SDValue(UpdN.getNode(), NumResultVecs));
15877
15878 return true;
15879}
15880
15881// If (opcode ptr inc) is and ADD-like instruction, return the
15882// increment value. Otherwise return 0.
15883static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
15884 SDValue Inc, const SelectionDAG &DAG) {
15885 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
15886 if (!CInc)
15887 return 0;
15888
15889 switch (Opcode) {
15890 case ARMISD::VLD1_UPD:
15891 case ISD::ADD:
15892 return CInc->getZExtValue();
15893 case ISD::OR: {
15894 if (DAG.haveNoCommonBitsSet(Ptr, Inc)) {
15895 // (OR ptr inc) is the same as (ADD ptr inc)
15896 return CInc->getZExtValue();
15897 }
15898 return 0;
15899 }
15900 default:
15901 return 0;
15902 }
15903}
15904
15905static bool findPointerConstIncrement(SDNode *N, SDValue *Ptr, SDValue *CInc) {
15906 switch (N->getOpcode()) {
15907 case ISD::ADD:
15908 case ISD::OR: {
15909 if (isa<ConstantSDNode>(N->getOperand(1))) {
15910 *Ptr = N->getOperand(0);
15911 *CInc = N->getOperand(1);
15912 return true;
15913 }
15914 return false;
15915 }
15916 case ARMISD::VLD1_UPD: {
15917 if (isa<ConstantSDNode>(N->getOperand(2))) {
15918 *Ptr = N->getOperand(1);
15919 *CInc = N->getOperand(2);
15920 return true;
15921 }
15922 return false;
15923 }
15924 default:
15925 return false;
15926 }
15927}
15928
15929static bool isValidBaseUpdate(SDNode *N, SDNode *User) {
15930 // Check that the add is independent of the load/store.
15931 // Otherwise, folding it would create a cycle. Search through Addr
15932 // as well, since the User may not be a direct user of Addr and
15933 // only share a base pointer.
15934 SmallPtrSet<const SDNode *, 32> Visited;
15935 SmallVector<const SDNode *, 16> Worklist;
15936 Worklist.push_back(N);
15937 Worklist.push_back(User);
15938 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
15939 SDNode::hasPredecessorHelper(User, Visited, Worklist))
15940 return false;
15941 return true;
15942}
15943
15944/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
15945/// NEON load/store intrinsics, and generic vector load/stores, to merge
15946/// base address updates.
15947/// For generic load/stores, the memory type is assumed to be a vector.
15948/// The caller is assumed to have checked legality.
15949static SDValue CombineBaseUpdate(SDNode *N,
15950 TargetLowering::DAGCombinerInfo &DCI) {
15951 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
15952 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
15953 const bool isStore = N->getOpcode() == ISD::STORE;
15954 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
15955 BaseUpdateTarget Target = {N, isIntrinsic, isStore, AddrOpIdx};
15956
15957 SDValue Addr = N->getOperand(AddrOpIdx);
15958
15959 SmallVector<BaseUpdateUser, 8> BaseUpdates;
15960
15961 // Search for a use of the address operand that is an increment.
15962 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
15963 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
15964 SDNode *User = *UI;
15965 if (UI.getUse().getResNo() != Addr.getResNo() ||
15966 User->getNumOperands() != 2)
15967 continue;
15968
15969 SDValue Inc = User->getOperand(UI.getOperandNo() == 1 ? 0 : 1);
15970 unsigned ConstInc =
15971 getPointerConstIncrement(User->getOpcode(), Addr, Inc, DCI.DAG);
15972
15973 if (ConstInc || User->getOpcode() == ISD::ADD)
15974 BaseUpdates.push_back({User, Inc, ConstInc});
15975 }
15976
15977 // If the address is a constant pointer increment itself, find
15978 // another constant increment that has the same base operand
15979 SDValue Base;
15980 SDValue CInc;
15981 if (findPointerConstIncrement(Addr.getNode(), &Base, &CInc)) {
15982 unsigned Offset =
15983 getPointerConstIncrement(Addr->getOpcode(), Base, CInc, DCI.DAG);
15984 for (SDNode::use_iterator UI = Base->use_begin(), UE = Base->use_end();
15985 UI != UE; ++UI) {
15986
15987 SDNode *User = *UI;
15988 if (UI.getUse().getResNo() != Base.getResNo() || User == Addr.getNode() ||
15989 User->getNumOperands() != 2)
15990 continue;
15991
15992 SDValue UserInc = User->getOperand(UI.getOperandNo() == 0 ? 1 : 0);
15993 unsigned UserOffset =
15994 getPointerConstIncrement(User->getOpcode(), Base, UserInc, DCI.DAG);
15995
15996 if (!UserOffset || UserOffset <= Offset)
15997 continue;
15998
15999 unsigned NewConstInc = UserOffset - Offset;
16000 SDValue NewInc = DCI.DAG.getConstant(NewConstInc, SDLoc(N), MVT::i32);
16001 BaseUpdates.push_back({User, NewInc, NewConstInc});
16002 }
16003 }
16004
16005 // Try to fold the load/store with an update that matches memory
16006 // access size. This should work well for sequential loads.
16007 //
16008 // Filter out invalid updates as well.
16009 unsigned NumValidUpd = BaseUpdates.size();
16010 for (unsigned I = 0; I < NumValidUpd;) {
16011 BaseUpdateUser &User = BaseUpdates[I];
16012 if (!isValidBaseUpdate(N, User.N)) {
16013 --NumValidUpd;
16014 std::swap(BaseUpdates[I], BaseUpdates[NumValidUpd]);
16015 continue;
16016 }
16017
16018 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16019 return SDValue();
16020 ++I;
16021 }
16022 BaseUpdates.resize(NumValidUpd);
16023
16024 // Try to fold with other users. Non-constant updates are considered
16025 // first, and constant updates are sorted to not break a sequence of
16026 // strided accesses (if there is any).
16027 std::stable_sort(BaseUpdates.begin(), BaseUpdates.end(),
16028 [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16029 return LHS.ConstInc < RHS.ConstInc;
16030 });
16031 for (BaseUpdateUser &User : BaseUpdates) {
16032 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16033 return SDValue();
16034 }
16035 return SDValue();
16036}
16037
16038static SDValue PerformVLDCombine(SDNode *N,
16039 TargetLowering::DAGCombinerInfo &DCI) {
16040 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16041 return SDValue();
16042
16043 return CombineBaseUpdate(N, DCI);
16044}
16045
16046static SDValue PerformMVEVLDCombine(SDNode *N,
16047 TargetLowering::DAGCombinerInfo &DCI) {
16048 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16049 return SDValue();
16050
16051 SelectionDAG &DAG = DCI.DAG;
16052 SDValue Addr = N->getOperand(2);
16053 MemSDNode *MemN = cast<MemSDNode>(N);
16054 SDLoc dl(N);
16055
16056 // For the stores, where there are multiple intrinsics we only actually want
16057 // to post-inc the last of the them.
16058 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16059 if (IntNo == Intrinsic::arm_mve_vst2q &&
16060 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
16061 return SDValue();
16062 if (IntNo == Intrinsic::arm_mve_vst4q &&
16063 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
16064 return SDValue();
16065
16066 // Search for a use of the address operand that is an increment.
16067 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
16068 UE = Addr.getNode()->use_end();
16069 UI != UE; ++UI) {
16070 SDNode *User = *UI;
16071 if (User->getOpcode() != ISD::ADD ||
16072 UI.getUse().getResNo() != Addr.getResNo())
16073 continue;
16074
16075 // Check that the add is independent of the load/store. Otherwise, folding
16076 // it would create a cycle. We can avoid searching through Addr as it's a
16077 // predecessor to both.
16078 SmallPtrSet<const SDNode *, 32> Visited;
16079 SmallVector<const SDNode *, 16> Worklist;
16080 Visited.insert(Addr.getNode());
16081 Worklist.push_back(N);
16082 Worklist.push_back(User);
16083 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
16084 SDNode::hasPredecessorHelper(User, Visited, Worklist))
16085 continue;
16086
16087 // Find the new opcode for the updating load/store.
16088 bool isLoadOp = true;
16089 unsigned NewOpc = 0;
16090 unsigned NumVecs = 0;
16091 switch (IntNo) {
16092 default:
16093 llvm_unreachable("unexpected intrinsic for MVE VLDn combine")::llvm::llvm_unreachable_internal("unexpected intrinsic for MVE VLDn combine"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16093)
;
16094 case Intrinsic::arm_mve_vld2q:
16095 NewOpc = ARMISD::VLD2_UPD;
16096 NumVecs = 2;
16097 break;
16098 case Intrinsic::arm_mve_vld4q:
16099 NewOpc = ARMISD::VLD4_UPD;
16100 NumVecs = 4;
16101 break;
16102 case Intrinsic::arm_mve_vst2q:
16103 NewOpc = ARMISD::VST2_UPD;
16104 NumVecs = 2;
16105 isLoadOp = false;
16106 break;
16107 case Intrinsic::arm_mve_vst4q:
16108 NewOpc = ARMISD::VST4_UPD;
16109 NumVecs = 4;
16110 isLoadOp = false;
16111 break;
16112 }
16113
16114 // Find the size of memory referenced by the load/store.
16115 EVT VecTy;
16116 if (isLoadOp) {
16117 VecTy = N->getValueType(0);
16118 } else {
16119 VecTy = N->getOperand(3).getValueType();
16120 }
16121
16122 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16123
16124 // If the increment is a constant, it must match the memory ref size.
16125 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16126 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
16127 if (!CInc || CInc->getZExtValue() != NumBytes)
16128 continue;
16129
16130 // Create the new updating load/store node.
16131 // First, create an SDVTList for the new updating node's results.
16132 EVT Tys[6];
16133 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16134 unsigned n;
16135 for (n = 0; n < NumResultVecs; ++n)
16136 Tys[n] = VecTy;
16137 Tys[n++] = MVT::i32;
16138 Tys[n] = MVT::Other;
16139 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
16140
16141 // Then, gather the new node's operands.
16142 SmallVector<SDValue, 8> Ops;
16143 Ops.push_back(N->getOperand(0)); // incoming chain
16144 Ops.push_back(N->getOperand(2)); // ptr
16145 Ops.push_back(Inc);
16146
16147 for (unsigned i = 3; i < N->getNumOperands(); ++i)
16148 Ops.push_back(N->getOperand(i));
16149
16150 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
16151 MemN->getMemOperand());
16152
16153 // Update the uses.
16154 SmallVector<SDValue, 5> NewResults;
16155 for (unsigned i = 0; i < NumResultVecs; ++i)
16156 NewResults.push_back(SDValue(UpdN.getNode(), i));
16157
16158 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16159 DCI.CombineTo(N, NewResults);
16160 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
16161
16162 break;
16163 }
16164
16165 return SDValue();
16166}
16167
16168/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16169/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16170/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
16171/// return true.
16172static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
16173 SelectionDAG &DAG = DCI.DAG;
16174 EVT VT = N->getValueType(0);
16175 // vldN-dup instructions only support 64-bit vectors for N > 1.
16176 if (!VT.is64BitVector())
16177 return false;
16178
16179 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16180 SDNode *VLD = N->getOperand(0).getNode();
16181 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16182 return false;
16183 unsigned NumVecs = 0;
16184 unsigned NewOpc = 0;
16185 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
16186 if (IntNo == Intrinsic::arm_neon_vld2lane) {
16187 NumVecs = 2;
16188 NewOpc = ARMISD::VLD2DUP;
16189 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16190 NumVecs = 3;
16191 NewOpc = ARMISD::VLD3DUP;
16192 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16193 NumVecs = 4;
16194 NewOpc = ARMISD::VLD4DUP;
16195 } else {
16196 return false;
16197 }
16198
16199 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16200 // numbers match the load.
16201 unsigned VLDLaneNo =
16202 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
16203 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
16204 UI != UE; ++UI) {
16205 // Ignore uses of the chain result.
16206 if (UI.getUse().getResNo() == NumVecs)
16207 continue;
16208 SDNode *User = *UI;
16209 if (User->getOpcode() != ARMISD::VDUPLANE ||
16210 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
16211 return false;
16212 }
16213
16214 // Create the vldN-dup node.
16215 EVT Tys[5];
16216 unsigned n;
16217 for (n = 0; n < NumVecs; ++n)
16218 Tys[n] = VT;
16219 Tys[n] = MVT::Other;
16220 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
16221 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
16222 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
16223 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
16224 Ops, VLDMemInt->getMemoryVT(),
16225 VLDMemInt->getMemOperand());
16226
16227 // Update the uses.
16228 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
16229 UI != UE; ++UI) {
16230 unsigned ResNo = UI.getUse().getResNo();
16231 // Ignore uses of the chain result.
16232 if (ResNo == NumVecs)
16233 continue;
16234 SDNode *User = *UI;
16235 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
16236 }
16237
16238 // Now the vldN-lane intrinsic is dead except for its chain result.
16239 // Update uses of the chain.
16240 std::vector<SDValue> VLDDupResults;
16241 for (unsigned n = 0; n < NumVecs; ++n)
16242 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
16243 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
16244 DCI.CombineTo(VLD, VLDDupResults);
16245
16246 return true;
16247}
16248
16249/// PerformVDUPLANECombine - Target-specific dag combine xforms for
16250/// ARMISD::VDUPLANE.
16251static SDValue PerformVDUPLANECombine(SDNode *N,
16252 TargetLowering::DAGCombinerInfo &DCI,
16253 const ARMSubtarget *Subtarget) {
16254 SDValue Op = N->getOperand(0);
16255 EVT VT = N->getValueType(0);
16256
16257 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16258 if (Subtarget->hasMVEIntegerOps()) {
16259 EVT ExtractVT = VT.getVectorElementType();
16260 // We need to ensure we are creating a legal type.
16261 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
16262 ExtractVT = MVT::i32;
16263 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
16264 N->getOperand(0), N->getOperand(1));
16265 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
16266 }
16267
16268 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16269 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16270 if (CombineVLDDUP(N, DCI))
16271 return SDValue(N, 0);
16272
16273 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16274 // redundant. Ignore bit_converts for now; element sizes are checked below.
16275 while (Op.getOpcode() == ISD::BITCAST)
16276 Op = Op.getOperand(0);
16277 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16278 return SDValue();
16279
16280 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16281 unsigned EltSize = Op.getScalarValueSizeInBits();
16282 // The canonical VMOV for a zero vector uses a 32-bit element size.
16283 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16284 unsigned EltBits;
16285 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
16286 EltSize = 8;
16287 if (EltSize > VT.getScalarSizeInBits())
16288 return SDValue();
16289
16290 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
16291}
16292
16293/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
16294static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG,
16295 const ARMSubtarget *Subtarget) {
16296 SDValue Op = N->getOperand(0);
16297 SDLoc dl(N);
16298
16299 if (Subtarget->hasMVEIntegerOps()) {
16300 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16301 // need to come from a GPR.
16302 if (Op.getValueType() == MVT::f32)
16303 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16304 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
16305 else if (Op.getValueType() == MVT::f16)
16306 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16307 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
16308 }
16309
16310 if (!Subtarget->hasNEON())
16311 return SDValue();
16312
16313 // Match VDUP(LOAD) -> VLD1DUP.
16314 // We match this pattern here rather than waiting for isel because the
16315 // transform is only legal for unindexed loads.
16316 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
16317 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16318 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
16319 SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
16320 DAG.getConstant(LD->getAlign().value(), SDLoc(N), MVT::i32)};
16321 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
16322 SDValue VLDDup =
16323 DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, Ops,
16324 LD->getMemoryVT(), LD->getMemOperand());
16325 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
16326 return VLDDup;
16327 }
16328
16329 return SDValue();
16330}
16331
16332static SDValue PerformLOADCombine(SDNode *N,
16333 TargetLowering::DAGCombinerInfo &DCI,
16334 const ARMSubtarget *Subtarget) {
16335 EVT VT = N->getValueType(0);
16336
16337 // If this is a legal vector load, try to combine it into a VLD1_UPD.
16338 if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16339 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16340 return CombineBaseUpdate(N, DCI);
16341
16342 return SDValue();
16343}
16344
16345// Optimize trunc store (of multiple scalars) to shuffle and store. First,
16346// pack all of the elements in one place. Next, store to memory in fewer
16347// chunks.
16348static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
16349 SelectionDAG &DAG) {
16350 SDValue StVal = St->getValue();
16351 EVT VT = StVal.getValueType();
16352 if (!St->isTruncatingStore() || !VT.isVector())
16353 return SDValue();
16354 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16355 EVT StVT = St->getMemoryVT();
16356 unsigned NumElems = VT.getVectorNumElements();
16357 assert(StVT != VT && "Cannot truncate to the same type")(static_cast <bool> (StVT != VT && "Cannot truncate to the same type"
) ? void (0) : __assert_fail ("StVT != VT && \"Cannot truncate to the same type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16357, __extension__
__PRETTY_FUNCTION__))
;
16358 unsigned FromEltSz = VT.getScalarSizeInBits();
16359 unsigned ToEltSz = StVT.getScalarSizeInBits();
16360
16361 // From, To sizes and ElemCount must be pow of two
16362 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
16363 return SDValue();
16364
16365 // We are going to use the original vector elt for storing.
16366 // Accumulated smaller vector elements must be a multiple of the store size.
16367 if (0 != (NumElems * FromEltSz) % ToEltSz)
16368 return SDValue();
16369
16370 unsigned SizeRatio = FromEltSz / ToEltSz;
16371 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits())(static_cast <bool> (SizeRatio * NumElems * ToEltSz == VT
.getSizeInBits()) ? void (0) : __assert_fail ("SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16371, __extension__
__PRETTY_FUNCTION__))
;
16372
16373 // Create a type on which we perform the shuffle.
16374 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
16375 NumElems * SizeRatio);
16376 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits())(static_cast <bool> (WideVecVT.getSizeInBits() == VT.getSizeInBits
()) ? void (0) : __assert_fail ("WideVecVT.getSizeInBits() == VT.getSizeInBits()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16376, __extension__
__PRETTY_FUNCTION__))
;
16377
16378 SDLoc DL(St);
16379 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
16380 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16381 for (unsigned i = 0; i < NumElems; ++i)
16382 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16383 : i * SizeRatio;
16384
16385 // Can't shuffle using an illegal type.
16386 if (!TLI.isTypeLegal(WideVecVT))
16387 return SDValue();
16388
16389 SDValue Shuff = DAG.getVectorShuffle(
16390 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
16391 // At this point all of the data is stored at the bottom of the
16392 // register. We now need to save it to mem.
16393
16394 // Find the largest store unit
16395 MVT StoreType = MVT::i8;
16396 for (MVT Tp : MVT::integer_valuetypes()) {
16397 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16398 StoreType = Tp;
16399 }
16400 // Didn't find a legal store type.
16401 if (!TLI.isTypeLegal(StoreType))
16402 return SDValue();
16403
16404 // Bitcast the original vector into a vector of store-size units
16405 EVT StoreVecVT =
16406 EVT::getVectorVT(*DAG.getContext(), StoreType,
16407 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16408 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits())(static_cast <bool> (StoreVecVT.getSizeInBits() == VT.getSizeInBits
()) ? void (0) : __assert_fail ("StoreVecVT.getSizeInBits() == VT.getSizeInBits()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16408, __extension__
__PRETTY_FUNCTION__))
;
16409 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
16410 SmallVector<SDValue, 8> Chains;
16411 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
16412 TLI.getPointerTy(DAG.getDataLayout()));
16413 SDValue BasePtr = St->getBasePtr();
16414
16415 // Perform one or more big stores into memory.
16416 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16417 for (unsigned I = 0; I < E; I++) {
16418 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
16419 ShuffWide, DAG.getIntPtrConstant(I, DL));
16420 SDValue Ch =
16421 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
16422 St->getAlign(), St->getMemOperand()->getFlags());
16423 BasePtr =
16424 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
16425 Chains.push_back(Ch);
16426 }
16427 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16428}
16429
16430// Try taking a single vector store from an fpround (which would otherwise turn
16431// into an expensive buildvector) and splitting it into a series of narrowing
16432// stores.
16433static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
16434 SelectionDAG &DAG) {
16435 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16436 return SDValue();
16437 SDValue Trunc = St->getValue();
16438 if (Trunc->getOpcode() != ISD::FP_ROUND)
16439 return SDValue();
16440 EVT FromVT = Trunc->getOperand(0).getValueType();
16441 EVT ToVT = Trunc.getValueType();
16442 if (!ToVT.isVector())
16443 return SDValue();
16444 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements())(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements()) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16444, __extension__
__PRETTY_FUNCTION__))
;
16445 EVT ToEltVT = ToVT.getVectorElementType();
16446 EVT FromEltVT = FromVT.getVectorElementType();
16447
16448 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16449 return SDValue();
16450
16451 unsigned NumElements = 4;
16452 if (FromVT.getVectorNumElements() % NumElements != 0)
16453 return SDValue();
16454
16455 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
16456 // use the VMOVN over splitting the store. We are looking for patterns of:
16457 // !rev: 0 N 1 N+1 2 N+2 ...
16458 // rev: N 0 N+1 1 N+2 2 ...
16459 // The shuffle may either be a single source (in which case N = NumElts/2) or
16460 // two inputs extended with concat to the same size (in which case N =
16461 // NumElts).
16462 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16463 ArrayRef<int> M = SVN->getMask();
16464 unsigned NumElts = ToVT.getVectorNumElements();
16465 if (SVN->getOperand(1).isUndef())
16466 NumElts /= 2;
16467
16468 unsigned Off0 = Rev ? NumElts : 0;
16469 unsigned Off1 = Rev ? 0 : NumElts;
16470
16471 for (unsigned I = 0; I < NumElts; I += 2) {
16472 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16473 return false;
16474 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16475 return false;
16476 }
16477
16478 return true;
16479 };
16480
16481 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
16482 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16483 return SDValue();
16484
16485 LLVMContext &C = *DAG.getContext();
16486 SDLoc DL(St);
16487 // Details about the old store
16488 SDValue Ch = St->getChain();
16489 SDValue BasePtr = St->getBasePtr();
16490 Align Alignment = St->getOriginalAlign();
16491 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16492 AAMDNodes AAInfo = St->getAAInfo();
16493
16494 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16495 // and then stored as truncating integer stores.
16496 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
16497 EVT NewToVT = EVT::getVectorVT(
16498 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
16499
16500 SmallVector<SDValue, 4> Stores;
16501 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16502 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16503 SDValue NewPtr =
16504 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
16505
16506 SDValue Extract =
16507 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
16508 DAG.getConstant(i * NumElements, DL, MVT::i32));
16509
16510 SDValue FPTrunc =
16511 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
16512 Extract, DAG.getConstant(0, DL, MVT::i32));
16513 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
16514
16515 SDValue Store = DAG.getTruncStore(
16516 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16517 NewToVT, Alignment.value(), MMOFlags, AAInfo);
16518 Stores.push_back(Store);
16519 }
16520 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16521}
16522
16523// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16524// into an expensive buildvector) and splitting it into a series of narrowing
16525// stores.
16526static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St,
16527 SelectionDAG &DAG) {
16528 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16529 return SDValue();
16530 SDValue Trunc = St->getValue();
16531 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16532 return SDValue();
16533 EVT FromVT = Trunc->getOperand(0).getValueType();
16534 EVT ToVT = Trunc.getValueType();
16535
16536 LLVMContext &C = *DAG.getContext();
16537 SDLoc DL(St);
16538 // Details about the old store
16539 SDValue Ch = St->getChain();
16540 SDValue BasePtr = St->getBasePtr();
16541 Align Alignment = St->getOriginalAlign();
16542 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16543 AAMDNodes AAInfo = St->getAAInfo();
16544
16545 EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
16546 FromVT.getVectorNumElements());
16547
16548 SmallVector<SDValue, 4> Stores;
16549 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16550 unsigned NewOffset =
16551 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16552 SDValue NewPtr =
16553 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
16554
16555 SDValue Extract = Trunc.getOperand(i);
16556 SDValue Store = DAG.getTruncStore(
16557 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16558 NewToVT, Alignment.value(), MMOFlags, AAInfo);
16559 Stores.push_back(Store);
16560 }
16561 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16562}
16563
16564// Given a floating point store from an extracted vector, with an integer
16565// VGETLANE that already exists, store the existing VGETLANEu directly. This can
16566// help reduce fp register pressure, doesn't require the fp extract and allows
16567// use of more integer post-inc stores not available with vstr.
16568static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) {
16569 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16570 return SDValue();
16571 SDValue Extract = St->getValue();
16572 EVT VT = Extract.getValueType();
16573 // For now only uses f16. This may be useful for f32 too, but that will
16574 // be bitcast(extract), not the VGETLANEu we currently check here.
16575 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16576 return SDValue();
16577
16578 SDNode *GetLane =
16579 DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
16580 {Extract.getOperand(0), Extract.getOperand(1)});
16581 if (!GetLane)
16582 return SDValue();
16583
16584 LLVMContext &C = *DAG.getContext();
16585 SDLoc DL(St);
16586 // Create a new integer store to replace the existing floating point version.
16587 SDValue Ch = St->getChain();
16588 SDValue BasePtr = St->getBasePtr();
16589 Align Alignment = St->getOriginalAlign();
16590 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16591 AAMDNodes AAInfo = St->getAAInfo();
16592 EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
16593 SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
16594 St->getPointerInfo(), NewToVT,
16595 Alignment.value(), MMOFlags, AAInfo);
16596
16597 return Store;
16598}
16599
16600/// PerformSTORECombine - Target-specific dag combine xforms for
16601/// ISD::STORE.
16602static SDValue PerformSTORECombine(SDNode *N,
16603 TargetLowering::DAGCombinerInfo &DCI,
16604 const ARMSubtarget *Subtarget) {
16605 StoreSDNode *St = cast<StoreSDNode>(N);
16606 if (St->isVolatile())
16607 return SDValue();
16608 SDValue StVal = St->getValue();
16609 EVT VT = StVal.getValueType();
16610
16611 if (Subtarget->hasNEON())
16612 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
16613 return Store;
16614
16615 if (Subtarget->hasMVEIntegerOps()) {
16616 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
16617 return NewToken;
16618 if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
16619 return NewChain;
16620 if (SDValue NewToken =
16621 PerformSplittingMVETruncToNarrowingStores(St, DCI.DAG))
16622 return NewToken;
16623 }
16624
16625 if (!ISD::isNormalStore(St))
16626 return SDValue();
16627
16628 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16629 // ARM stores of arguments in the same cache line.
16630 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16631 StVal.getNode()->hasOneUse()) {
16632 SelectionDAG &DAG = DCI.DAG;
16633 bool isBigEndian = DAG.getDataLayout().isBigEndian();
16634 SDLoc DL(St);
16635 SDValue BasePtr = St->getBasePtr();
16636 SDValue NewST1 = DAG.getStore(
16637 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
16638 BasePtr, St->getPointerInfo(), St->getOriginalAlign(),
16639 St->getMemOperand()->getFlags());
16640
16641 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
16642 DAG.getConstant(4, DL, MVT::i32));
16643 return DAG.getStore(NewST1.getValue(0), DL,
16644 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
16645 OffsetPtr, St->getPointerInfo().getWithOffset(4),
16646 St->getOriginalAlign(),
16647 St->getMemOperand()->getFlags());
16648 }
16649
16650 if (StVal.getValueType() == MVT::i64 &&
16651 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16652
16653 // Bitcast an i64 store extracted from a vector to f64.
16654 // Otherwise, the i64 value will be legalized to a pair of i32 values.
16655 SelectionDAG &DAG = DCI.DAG;
16656 SDLoc dl(StVal);
16657 SDValue IntVec = StVal.getOperand(0);
16658 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
16659 IntVec.getValueType().getVectorNumElements());
16660 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
16661 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
16662 Vec, StVal.getOperand(1));
16663 dl = SDLoc(N);
16664 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
16665 // Make the DAGCombiner fold the bitcasts.
16666 DCI.AddToWorklist(Vec.getNode());
16667 DCI.AddToWorklist(ExtElt.getNode());
16668 DCI.AddToWorklist(V.getNode());
16669 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
16670 St->getPointerInfo(), St->getAlign(),
16671 St->getMemOperand()->getFlags(), St->getAAInfo());
16672 }
16673
16674 // If this is a legal vector store, try to combine it into a VST1_UPD.
16675 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16676 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16677 return CombineBaseUpdate(N, DCI);
16678
16679 return SDValue();
16680}
16681
16682/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16683/// can replace combinations of VMUL and VCVT (floating-point to integer)
16684/// when the VMUL has a constant operand that is a power of 2.
16685///
16686/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16687/// vmul.f32 d16, d17, d16
16688/// vcvt.s32.f32 d16, d16
16689/// becomes:
16690/// vcvt.s32.f32 d16, d16, #3
16691static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
16692 const ARMSubtarget *Subtarget) {
16693 if (!Subtarget->hasNEON())
16694 return SDValue();
16695
16696 SDValue Op = N->getOperand(0);
16697 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16698 Op.getOpcode() != ISD::FMUL)
16699 return SDValue();
16700
16701 SDValue ConstVec = Op->getOperand(1);
16702 if (!isa<BuildVectorSDNode>(ConstVec))
16703 return SDValue();
16704
16705 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16706 uint32_t FloatBits = FloatTy.getSizeInBits();
16707 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
16708 uint32_t IntBits = IntTy.getSizeInBits();
16709 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16710 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16711 // These instructions only exist converting from f32 to i32. We can handle
16712 // smaller integers by generating an extra truncate, but larger ones would
16713 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16714 // these intructions only support v2i32/v4i32 types.
16715 return SDValue();
16716 }
16717
16718 BitVector UndefElements;
16719 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16720 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16721 if (C == -1 || C == 0 || C > 32)
16722 return SDValue();
16723
16724 SDLoc dl(N);
16725 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
16726 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
16727 Intrinsic::arm_neon_vcvtfp2fxu;
16728 SDValue FixConv = DAG.getNode(
16729 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16730 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
16731 DAG.getConstant(C, dl, MVT::i32));
16732
16733 if (IntBits < FloatBits)
16734 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
16735
16736 return FixConv;
16737}
16738
16739static SDValue PerformFAddVSelectCombine(SDNode *N, SelectionDAG &DAG,
16740 const ARMSubtarget *Subtarget) {
16741 if (!Subtarget->hasMVEFloatOps())
16742 return SDValue();
16743
16744 // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
16745 // The second form can be more easily turned into a predicated vadd, and
16746 // possibly combined into a fma to become a predicated vfma.
16747 SDValue Op0 = N->getOperand(0);
16748 SDValue Op1 = N->getOperand(1);
16749 EVT VT = N->getValueType(0);
16750 SDLoc DL(N);
16751
16752 // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
16753 // which these VMOV's represent.
16754 auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
16755 if (Op.getOpcode() != ISD::BITCAST ||
16756 Op.getOperand(0).getOpcode() != ARMISD::VMOVIMM)
16757 return false;
16758 uint64_t ImmVal = Op.getOperand(0).getConstantOperandVal(0);
16759 if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
16760 return true;
16761 if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
16762 return true;
16763 return false;
16764 };
16765
16766 if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
16767 std::swap(Op0, Op1);
16768
16769 if (Op1.getOpcode() != ISD::VSELECT)
16770 return SDValue();
16771
16772 SDNodeFlags FaddFlags = N->getFlags();
16773 bool NSZ = FaddFlags.hasNoSignedZeros();
16774 if (!isIdentitySplat(Op1.getOperand(2), NSZ))
16775 return SDValue();
16776
16777 SDValue FAdd =
16778 DAG.getNode(ISD::FADD, DL, VT, Op0, Op1.getOperand(1), FaddFlags);
16779 return DAG.getNode(ISD::VSELECT, DL, VT, Op1.getOperand(0), FAdd, Op0, FaddFlags);
16780}
16781
16782/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
16783/// can replace combinations of VCVT (integer to floating-point) and VDIV
16784/// when the VDIV has a constant operand that is a power of 2.
16785///
16786/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16787/// vcvt.f32.s32 d16, d16
16788/// vdiv.f32 d16, d17, d16
16789/// becomes:
16790/// vcvt.f32.s32 d16, d16, #3
16791static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
16792 const ARMSubtarget *Subtarget) {
16793 if (!Subtarget->hasNEON())
16794 return SDValue();
16795
16796 SDValue Op = N->getOperand(0);
16797 unsigned OpOpcode = Op.getNode()->getOpcode();
16798 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
16799 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
16800 return SDValue();
16801
16802 SDValue ConstVec = N->getOperand(1);
16803 if (!isa<BuildVectorSDNode>(ConstVec))
16804 return SDValue();
16805
16806 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
16807 uint32_t FloatBits = FloatTy.getSizeInBits();
16808 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
16809 uint32_t IntBits = IntTy.getSizeInBits();
16810 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16811 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16812 // These instructions only exist converting from i32 to f32. We can handle
16813 // smaller integers by generating an extra extend, but larger ones would
16814 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16815 // these intructions only support v2i32/v4i32 types.
16816 return SDValue();
16817 }
16818
16819 BitVector UndefElements;
16820 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16821 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16822 if (C == -1 || C == 0 || C > 32)
16823 return SDValue();
16824
16825 SDLoc dl(N);
16826 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
16827 SDValue ConvInput = Op.getOperand(0);
16828 if (IntBits < FloatBits)
16829 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
16830 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16831 ConvInput);
16832
16833 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
16834 Intrinsic::arm_neon_vcvtfxu2fp;
16835 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
16836 Op.getValueType(),
16837 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
16838 ConvInput, DAG.getConstant(C, dl, MVT::i32));
16839}
16840
16841static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
16842 const ARMSubtarget *ST) {
16843 if (!ST->hasMVEIntegerOps())
16844 return SDValue();
16845
16846 assert(N->getOpcode() == ISD::VECREDUCE_ADD)(static_cast <bool> (N->getOpcode() == ISD::VECREDUCE_ADD
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::VECREDUCE_ADD"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16846, __extension__
__PRETTY_FUNCTION__))
;
16847 EVT ResVT = N->getValueType(0);
16848 SDValue N0 = N->getOperand(0);
16849 SDLoc dl(N);
16850
16851 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
16852 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
16853 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
16854 N0.getValueType() == MVT::v16i8)) {
16855 SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
16856 SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
16857 return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
16858 }
16859
16860 // We are looking for something that will have illegal types if left alone,
16861 // but that we can convert to a single instruction under MVE. For example
16862 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
16863 // or
16864 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
16865
16866 // The legal cases are:
16867 // VADDV u/s 8/16/32
16868 // VMLAV u/s 8/16/32
16869 // VADDLV u/s 32
16870 // VMLALV u/s 16/32
16871
16872 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
16873 // extend it and use v4i32 instead.
16874 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
16875 EVT AVT = A.getValueType();
16876 return any_of(ExtTypes, [&](MVT Ty) {
16877 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
16878 AVT.bitsLE(Ty);
16879 });
16880 };
16881 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
16882 EVT AVT = A.getValueType();
16883 if (!AVT.is128BitVector())
16884 A = DAG.getNode(ExtendCode, dl,
16885 AVT.changeVectorElementType(MVT::getIntegerVT(
16886 128 / AVT.getVectorMinNumElements())),
16887 A);
16888 return A;
16889 };
16890 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
16891 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
16892 return SDValue();
16893 SDValue A = N0->getOperand(0);
16894 if (ExtTypeMatches(A, ExtTypes))
16895 return ExtendIfNeeded(A, ExtendCode);
16896 return SDValue();
16897 };
16898 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
16899 ArrayRef<MVT> ExtTypes, SDValue &Mask) {
16900 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
16901 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
16902 return SDValue();
16903 Mask = N0->getOperand(0);
16904 SDValue Ext = N0->getOperand(1);
16905 if (Ext->getOpcode() != ExtendCode)
16906 return SDValue();
16907 SDValue A = Ext->getOperand(0);
16908 if (ExtTypeMatches(A, ExtTypes))
16909 return ExtendIfNeeded(A, ExtendCode);
16910 return SDValue();
16911 };
16912 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
16913 SDValue &A, SDValue &B) {
16914 // For a vmla we are trying to match a larger pattern:
16915 // ExtA = sext/zext A
16916 // ExtB = sext/zext B
16917 // Mul = mul ExtA, ExtB
16918 // vecreduce.add Mul
16919 // There might also be en extra extend between the mul and the addreduce, so
16920 // long as the bitwidth is high enough to make them equivalent (for example
16921 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
16922 if (ResVT != RetTy)
16923 return false;
16924 SDValue Mul = N0;
16925 if (Mul->getOpcode() == ExtendCode &&
16926 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
16927 ResVT.getScalarSizeInBits())
16928 Mul = Mul->getOperand(0);
16929 if (Mul->getOpcode() != ISD::MUL)
16930 return false;
16931 SDValue ExtA = Mul->getOperand(0);
16932 SDValue ExtB = Mul->getOperand(1);
16933 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
16934 return false;
16935 A = ExtA->getOperand(0);
16936 B = ExtB->getOperand(0);
16937 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
16938 A = ExtendIfNeeded(A, ExtendCode);
16939 B = ExtendIfNeeded(B, ExtendCode);
16940 return true;
16941 }
16942 return false;
16943 };
16944 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
16945 SDValue &A, SDValue &B, SDValue &Mask) {
16946 // Same as the pattern above with a select for the zero predicated lanes
16947 // ExtA = sext/zext A
16948 // ExtB = sext/zext B
16949 // Mul = mul ExtA, ExtB
16950 // N0 = select Mask, Mul, 0
16951 // vecreduce.add N0
16952 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
16953 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
16954 return false;
16955 Mask = N0->getOperand(0);
16956 SDValue Mul = N0->getOperand(1);
16957 if (Mul->getOpcode() == ExtendCode &&
16958 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
16959 ResVT.getScalarSizeInBits())
16960 Mul = Mul->getOperand(0);
16961 if (Mul->getOpcode() != ISD::MUL)
16962 return false;
16963 SDValue ExtA = Mul->getOperand(0);
16964 SDValue ExtB = Mul->getOperand(1);
16965 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
16966 return false;
16967 A = ExtA->getOperand(0);
16968 B = ExtB->getOperand(0);
16969 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
16970 A = ExtendIfNeeded(A, ExtendCode);
16971 B = ExtendIfNeeded(B, ExtendCode);
16972 return true;
16973 }
16974 return false;
16975 };
16976 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
16977 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
16978 // reductions. The operands are extended with MVEEXT, but as they are
16979 // reductions the lane orders do not matter. MVEEXT may be combined with
16980 // loads to produce two extending loads, or else they will be expanded to
16981 // VREV/VMOVL.
16982 EVT VT = Ops[0].getValueType();
16983 if (VT == MVT::v16i8) {
16984 assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&(static_cast <bool> ((Opcode == ARMISD::VMLALVs || Opcode
== ARMISD::VMLALVu) && "Unexpected illegal long reduction opcode"
) ? void (0) : __assert_fail ("(Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) && \"Unexpected illegal long reduction opcode\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16985, __extension__
__PRETTY_FUNCTION__))
16985 "Unexpected illegal long reduction opcode")(static_cast <bool> ((Opcode == ARMISD::VMLALVs || Opcode
== ARMISD::VMLALVu) && "Unexpected illegal long reduction opcode"
) ? void (0) : __assert_fail ("(Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) && \"Unexpected illegal long reduction opcode\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 16985, __extension__
__PRETTY_FUNCTION__))
;
16986 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
16987
16988 SDValue Ext0 =
16989 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
16990 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
16991 SDValue Ext1 =
16992 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
16993 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
16994
16995 SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
16996 Ext0, Ext1);
16997 SDValue MLA1 =
16998 DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
16999 DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
17000 Ext0.getValue(1), Ext1.getValue(1));
17001 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
17002 }
17003 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
17004 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
17005 SDValue(Node.getNode(), 1));
17006 };
17007
17008 SDValue A, B;
17009 SDValue Mask;
17010 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17011 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
17012 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17013 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
17014 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17015 A, B))
17016 return Create64bitNode(ARMISD::VMLALVs, {A, B});
17017 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17018 A, B))
17019 return Create64bitNode(ARMISD::VMLALVu, {A, B});
17020 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17021 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17022 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
17023 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17024 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17025 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
17026
17027 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17028 Mask))
17029 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
17030 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17031 Mask))
17032 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
17033 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17034 Mask))
17035 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17036 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17037 Mask))
17038 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17039 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17040 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17041 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
17042 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17043 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17044 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
17045
17046 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17047 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
17048 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17049 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
17050 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17051 return Create64bitNode(ARMISD::VADDLVs, {A});
17052 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17053 return Create64bitNode(ARMISD::VADDLVu, {A});
17054 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17055 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17056 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
17057 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17058 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17059 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
17060
17061 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17062 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
17063 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17064 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
17065 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17066 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17067 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17068 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17069 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17070 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17071 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
17072 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17073 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17074 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
17075
17076 // Some complications. We can get a case where the two inputs of the mul are
17077 // the same, then the output sext will have been helpfully converted to a
17078 // zext. Turn it back.
17079 SDValue Op = N0;
17080 if (Op->getOpcode() == ISD::VSELECT)
17081 Op = Op->getOperand(1);
17082 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17083 Op->getOperand(0)->getOpcode() == ISD::MUL) {
17084 SDValue Mul = Op->getOperand(0);
17085 if (Mul->getOperand(0) == Mul->getOperand(1) &&
17086 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
17087 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
17088 if (Op != N0)
17089 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
17090 N0->getOperand(0), Ext, N0->getOperand(2));
17091 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
17092 }
17093 }
17094
17095 return SDValue();
17096}
17097
17098static SDValue PerformVMOVNCombine(SDNode *N,
17099 TargetLowering::DAGCombinerInfo &DCI) {
17100 SDValue Op0 = N->getOperand(0);
17101 SDValue Op1 = N->getOperand(1);
17102 unsigned IsTop = N->getConstantOperandVal(2);
17103
17104 // VMOVNT a undef -> a
17105 // VMOVNB a undef -> a
17106 // VMOVNB undef a -> a
17107 if (Op1->isUndef())
17108 return Op0;
17109 if (Op0->isUndef() && !IsTop)
17110 return Op1;
17111
17112 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17113 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17114 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17115 Op1->getOpcode() == ARMISD::VQMOVNu) &&
17116 Op1->getConstantOperandVal(2) == 0)
17117 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
17118 Op0, Op1->getOperand(1), N->getOperand(2));
17119
17120 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17121 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17122 // into the top or bottom lanes.
17123 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17124 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
17125 APInt Op0DemandedElts =
17126 IsTop ? Op1DemandedElts
17127 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
17128
17129 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17130 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17131 return SDValue(N, 0);
17132 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, DCI))
17133 return SDValue(N, 0);
17134
17135 return SDValue();
17136}
17137
17138static SDValue PerformVQMOVNCombine(SDNode *N,
17139 TargetLowering::DAGCombinerInfo &DCI) {
17140 SDValue Op0 = N->getOperand(0);
17141 unsigned IsTop = N->getConstantOperandVal(2);
17142
17143 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17144 APInt Op0DemandedElts =
17145 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
17146 : APInt::getHighBitsSet(2, 1));
17147
17148 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17149 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17150 return SDValue(N, 0);
17151 return SDValue();
17152}
17153
17154static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
17155 SDLoc DL(N);
17156 SDValue Op0 = N->getOperand(0);
17157 SDValue Op1 = N->getOperand(1);
17158
17159 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17160 // uses of the intrinsics.
17161 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
17162 int ShiftAmt = C->getSExtValue();
17163 if (ShiftAmt == 0) {
17164 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
17165 DAG.ReplaceAllUsesWith(N, Merge.getNode());
17166 return SDValue();
17167 }
17168
17169 if (ShiftAmt >= -32 && ShiftAmt < 0) {
17170 unsigned NewOpcode =
17171 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17172 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
17173 DAG.getConstant(-ShiftAmt, DL, MVT::i32));
17174 DAG.ReplaceAllUsesWith(N, NewShift.getNode());
17175 return NewShift;
17176 }
17177 }
17178
17179 return SDValue();
17180}
17181
17182/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
17183SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
17184 DAGCombinerInfo &DCI) const {
17185 SelectionDAG &DAG = DCI.DAG;
17186 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
17187 switch (IntNo) {
17188 default:
17189 // Don't do anything for most intrinsics.
17190 break;
17191
17192 // Vector shifts: check for immediate versions and lower them.
17193 // Note: This is done during DAG combining instead of DAG legalizing because
17194 // the build_vectors for 64-bit vector element shift counts are generally
17195 // not legal, and it is hard to see their values after they get legalized to
17196 // loads from a constant pool.
17197 case Intrinsic::arm_neon_vshifts:
17198 case Intrinsic::arm_neon_vshiftu:
17199 case Intrinsic::arm_neon_vrshifts:
17200 case Intrinsic::arm_neon_vrshiftu:
17201 case Intrinsic::arm_neon_vrshiftn:
17202 case Intrinsic::arm_neon_vqshifts:
17203 case Intrinsic::arm_neon_vqshiftu:
17204 case Intrinsic::arm_neon_vqshiftsu:
17205 case Intrinsic::arm_neon_vqshiftns:
17206 case Intrinsic::arm_neon_vqshiftnu:
17207 case Intrinsic::arm_neon_vqshiftnsu:
17208 case Intrinsic::arm_neon_vqrshiftns:
17209 case Intrinsic::arm_neon_vqrshiftnu:
17210 case Intrinsic::arm_neon_vqrshiftnsu: {
17211 EVT VT = N->getOperand(1).getValueType();
17212 int64_t Cnt;
17213 unsigned VShiftOpc = 0;
17214
17215 switch (IntNo) {
17216 case Intrinsic::arm_neon_vshifts:
17217 case Intrinsic::arm_neon_vshiftu:
17218 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
17219 VShiftOpc = ARMISD::VSHLIMM;
17220 break;
17221 }
17222 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
17223 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
17224 : ARMISD::VSHRuIMM);
17225 break;
17226 }
17227 return SDValue();
17228
17229 case Intrinsic::arm_neon_vrshifts:
17230 case Intrinsic::arm_neon_vrshiftu:
17231 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
17232 break;
17233 return SDValue();
17234
17235 case Intrinsic::arm_neon_vqshifts:
17236 case Intrinsic::arm_neon_vqshiftu:
17237 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17238 break;
17239 return SDValue();
17240
17241 case Intrinsic::arm_neon_vqshiftsu:
17242 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17243 break;
17244 llvm_unreachable("invalid shift count for vqshlu intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for vqshlu intrinsic"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17244)
;
17245
17246 case Intrinsic::arm_neon_vrshiftn:
17247 case Intrinsic::arm_neon_vqshiftns:
17248 case Intrinsic::arm_neon_vqshiftnu:
17249 case Intrinsic::arm_neon_vqshiftnsu:
17250 case Intrinsic::arm_neon_vqrshiftns:
17251 case Intrinsic::arm_neon_vqrshiftnu:
17252 case Intrinsic::arm_neon_vqrshiftnsu:
17253 // Narrowing shifts require an immediate right shift.
17254 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
17255 break;
17256 llvm_unreachable("invalid shift count for narrowing vector shift "::llvm::llvm_unreachable_internal("invalid shift count for narrowing vector shift "
"intrinsic", "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17257
)
17257 "intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for narrowing vector shift "
"intrinsic", "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17257
)
;
17258
17259 default:
17260 llvm_unreachable("unhandled vector shift")::llvm::llvm_unreachable_internal("unhandled vector shift", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17260)
;
17261 }
17262
17263 switch (IntNo) {
17264 case Intrinsic::arm_neon_vshifts:
17265 case Intrinsic::arm_neon_vshiftu:
17266 // Opcode already set above.
17267 break;
17268 case Intrinsic::arm_neon_vrshifts:
17269 VShiftOpc = ARMISD::VRSHRsIMM;
17270 break;
17271 case Intrinsic::arm_neon_vrshiftu:
17272 VShiftOpc = ARMISD::VRSHRuIMM;
17273 break;
17274 case Intrinsic::arm_neon_vrshiftn:
17275 VShiftOpc = ARMISD::VRSHRNIMM;
17276 break;
17277 case Intrinsic::arm_neon_vqshifts:
17278 VShiftOpc = ARMISD::VQSHLsIMM;
17279 break;
17280 case Intrinsic::arm_neon_vqshiftu:
17281 VShiftOpc = ARMISD::VQSHLuIMM;
17282 break;
17283 case Intrinsic::arm_neon_vqshiftsu:
17284 VShiftOpc = ARMISD::VQSHLsuIMM;
17285 break;
17286 case Intrinsic::arm_neon_vqshiftns:
17287 VShiftOpc = ARMISD::VQSHRNsIMM;
17288 break;
17289 case Intrinsic::arm_neon_vqshiftnu:
17290 VShiftOpc = ARMISD::VQSHRNuIMM;
17291 break;
17292 case Intrinsic::arm_neon_vqshiftnsu:
17293 VShiftOpc = ARMISD::VQSHRNsuIMM;
17294 break;
17295 case Intrinsic::arm_neon_vqrshiftns:
17296 VShiftOpc = ARMISD::VQRSHRNsIMM;
17297 break;
17298 case Intrinsic::arm_neon_vqrshiftnu:
17299 VShiftOpc = ARMISD::VQRSHRNuIMM;
17300 break;
17301 case Intrinsic::arm_neon_vqrshiftnsu:
17302 VShiftOpc = ARMISD::VQRSHRNsuIMM;
17303 break;
17304 }
17305
17306 SDLoc dl(N);
17307 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17308 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
17309 }
17310
17311 case Intrinsic::arm_neon_vshiftins: {
17312 EVT VT = N->getOperand(1).getValueType();
17313 int64_t Cnt;
17314 unsigned VShiftOpc = 0;
17315
17316 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
17317 VShiftOpc = ARMISD::VSLIIMM;
17318 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
17319 VShiftOpc = ARMISD::VSRIIMM;
17320 else {
17321 llvm_unreachable("invalid shift count for vsli/vsri intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for vsli/vsri intrinsic"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17321)
;
17322 }
17323
17324 SDLoc dl(N);
17325 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17326 N->getOperand(1), N->getOperand(2),
17327 DAG.getConstant(Cnt, dl, MVT::i32));
17328 }
17329
17330 case Intrinsic::arm_neon_vqrshifts:
17331 case Intrinsic::arm_neon_vqrshiftu:
17332 // No immediate versions of these to check for.
17333 break;
17334
17335 case Intrinsic::arm_mve_vqdmlah:
17336 case Intrinsic::arm_mve_vqdmlash:
17337 case Intrinsic::arm_mve_vqrdmlah:
17338 case Intrinsic::arm_mve_vqrdmlash:
17339 case Intrinsic::arm_mve_vmla_n_predicated:
17340 case Intrinsic::arm_mve_vmlas_n_predicated:
17341 case Intrinsic::arm_mve_vqdmlah_predicated:
17342 case Intrinsic::arm_mve_vqdmlash_predicated:
17343 case Intrinsic::arm_mve_vqrdmlah_predicated:
17344 case Intrinsic::arm_mve_vqrdmlash_predicated: {
17345 // These intrinsics all take an i32 scalar operand which is narrowed to the
17346 // size of a single lane of the vector type they return. So we don't need
17347 // any bits of that operand above that point, which allows us to eliminate
17348 // uxth/sxth.
17349 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
17350 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17351 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
17352 return SDValue();
17353 break;
17354 }
17355
17356 case Intrinsic::arm_mve_minv:
17357 case Intrinsic::arm_mve_maxv:
17358 case Intrinsic::arm_mve_minav:
17359 case Intrinsic::arm_mve_maxav:
17360 case Intrinsic::arm_mve_minv_predicated:
17361 case Intrinsic::arm_mve_maxv_predicated:
17362 case Intrinsic::arm_mve_minav_predicated:
17363 case Intrinsic::arm_mve_maxav_predicated: {
17364 // These intrinsics all take an i32 scalar operand which is narrowed to the
17365 // size of a single lane of the vector type they take as the other input.
17366 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
17367 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17368 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
17369 return SDValue();
17370 break;
17371 }
17372
17373 case Intrinsic::arm_mve_addv: {
17374 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
17375 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
17376 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
17377 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
17378 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
17379 }
17380
17381 case Intrinsic::arm_mve_addlv:
17382 case Intrinsic::arm_mve_addlv_predicated: {
17383 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
17384 // which recombines the two outputs into an i64
17385 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
17386 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
17387 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
17388 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
17389
17390 SmallVector<SDValue, 4> Ops;
17391 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
17392 if (i != 2) // skip the unsigned flag
17393 Ops.push_back(N->getOperand(i));
17394
17395 SDLoc dl(N);
17396 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
17397 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
17398 val.getValue(1));
17399 }
17400 }
17401
17402 return SDValue();
17403}
17404
17405/// PerformShiftCombine - Checks for immediate versions of vector shifts and
17406/// lowers them. As with the vector shift intrinsics, this is done during DAG
17407/// combining instead of DAG legalizing because the build_vectors for 64-bit
17408/// vector element shift counts are generally not legal, and it is hard to see
17409/// their values after they get legalized to loads from a constant pool.
17410static SDValue PerformShiftCombine(SDNode *N,
17411 TargetLowering::DAGCombinerInfo &DCI,
17412 const ARMSubtarget *ST) {
17413 SelectionDAG &DAG = DCI.DAG;
17414 EVT VT = N->getValueType(0);
17415
17416 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
17417 N->getOperand(0)->getOpcode() == ISD::AND &&
17418 N->getOperand(0)->hasOneUse()) {
17419 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17420 return SDValue();
17421 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
17422 // usually show up because instcombine prefers to canonicalize it to
17423 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
17424 // out of GEP lowering in some cases.
17425 SDValue N0 = N->getOperand(0);
17426 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
17427 if (!ShiftAmtNode)
17428 return SDValue();
17429 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
17430 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17431 if (!AndMaskNode)
17432 return SDValue();
17433 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
17434 // Don't transform uxtb/uxth.
17435 if (AndMask == 255 || AndMask == 65535)
17436 return SDValue();
17437 if (isMask_32(AndMask)) {
17438 uint32_t MaskedBits = countLeadingZeros(AndMask);
17439 if (MaskedBits > ShiftAmt) {
17440 SDLoc DL(N);
17441 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
17442 DAG.getConstant(MaskedBits, DL, MVT::i32));
17443 return DAG.getNode(
17444 ISD::SRL, DL, MVT::i32, SHL,
17445 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
17446 }
17447 }
17448 }
17449
17450 // Nothing to be done for scalar shifts.
17451 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17452 if (!VT.isVector() || !TLI.isTypeLegal(VT))
17453 return SDValue();
17454 if (ST->hasMVEIntegerOps())
17455 return SDValue();
17456
17457 int64_t Cnt;
17458
17459 switch (N->getOpcode()) {
17460 default: llvm_unreachable("unexpected shift opcode")::llvm::llvm_unreachable_internal("unexpected shift opcode", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17460)
;
17461
17462 case ISD::SHL:
17463 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
17464 SDLoc dl(N);
17465 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
17466 DAG.getConstant(Cnt, dl, MVT::i32));
17467 }
17468 break;
17469
17470 case ISD::SRA:
17471 case ISD::SRL:
17472 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
17473 unsigned VShiftOpc =
17474 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
17475 SDLoc dl(N);
17476 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
17477 DAG.getConstant(Cnt, dl, MVT::i32));
17478 }
17479 }
17480 return SDValue();
17481}
17482
17483// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
17484// split into multiple extending loads, which are simpler to deal with than an
17485// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
17486// to convert the type to an f32.
17487static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
17488 SDValue N0 = N->getOperand(0);
17489 if (N0.getOpcode() != ISD::LOAD)
17490 return SDValue();
17491 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
17492 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
17493 LD->getExtensionType() != ISD::NON_EXTLOAD)
17494 return SDValue();
17495 EVT FromVT = LD->getValueType(0);
17496 EVT ToVT = N->getValueType(0);
17497 if (!ToVT.isVector())
17498 return SDValue();
17499 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements())(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements()) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17499, __extension__
__PRETTY_FUNCTION__))
;
17500 EVT ToEltVT = ToVT.getVectorElementType();
17501 EVT FromEltVT = FromVT.getVectorElementType();
17502
17503 unsigned NumElements = 0;
17504 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
17505 NumElements = 4;
17506 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
17507 NumElements = 4;
17508 if (NumElements == 0 ||
17509 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
17510 FromVT.getVectorNumElements() % NumElements != 0 ||
17511 !isPowerOf2_32(NumElements))
17512 return SDValue();
17513
17514 LLVMContext &C = *DAG.getContext();
17515 SDLoc DL(LD);
17516 // Details about the old load
17517 SDValue Ch = LD->getChain();
17518 SDValue BasePtr = LD->getBasePtr();
17519 Align Alignment = LD->getOriginalAlign();
17520 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17521 AAMDNodes AAInfo = LD->getAAInfo();
17522
17523 ISD::LoadExtType NewExtType =
17524 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17525 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
17526 EVT NewFromVT = EVT::getVectorVT(
17527 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
17528 EVT NewToVT = EVT::getVectorVT(
17529 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
17530
17531 SmallVector<SDValue, 4> Loads;
17532 SmallVector<SDValue, 4> Chains;
17533 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17534 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17535 SDValue NewPtr =
17536 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
17537
17538 SDValue NewLoad =
17539 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
17540 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
17541 Alignment, MMOFlags, AAInfo);
17542 Loads.push_back(NewLoad);
17543 Chains.push_back(SDValue(NewLoad.getNode(), 1));
17544 }
17545
17546 // Float truncs need to extended with VCVTB's into their floating point types.
17547 if (FromEltVT == MVT::f16) {
17548 SmallVector<SDValue, 4> Extends;
17549
17550 for (unsigned i = 0; i < Loads.size(); i++) {
17551 SDValue LoadBC =
17552 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
17553 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
17554 DAG.getConstant(0, DL, MVT::i32));
17555 Extends.push_back(FPExt);
17556 }
17557
17558 Loads = Extends;
17559 }
17560
17561 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17562 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
17563 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
17564}
17565
17566/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
17567/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
17568static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
17569 const ARMSubtarget *ST) {
17570 SDValue N0 = N->getOperand(0);
17571
17572 // Check for sign- and zero-extensions of vector extract operations of 8- and
17573 // 16-bit vector elements. NEON and MVE support these directly. They are
17574 // handled during DAG combining because type legalization will promote them
17575 // to 32-bit types and it is messy to recognize the operations after that.
17576 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
17577 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17578 SDValue Vec = N0.getOperand(0);
17579 SDValue Lane = N0.getOperand(1);
17580 EVT VT = N->getValueType(0);
17581 EVT EltVT = N0.getValueType();
17582 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17583
17584 if (VT == MVT::i32 &&
17585 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
17586 TLI.isTypeLegal(Vec.getValueType()) &&
17587 isa<ConstantSDNode>(Lane)) {
17588
17589 unsigned Opc = 0;
17590 switch (N->getOpcode()) {
17591 default: llvm_unreachable("unexpected opcode")::llvm::llvm_unreachable_internal("unexpected opcode", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17591)
;
17592 case ISD::SIGN_EXTEND:
17593 Opc = ARMISD::VGETLANEs;
17594 break;
17595 case ISD::ZERO_EXTEND:
17596 case ISD::ANY_EXTEND:
17597 Opc = ARMISD::VGETLANEu;
17598 break;
17599 }
17600 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
17601 }
17602 }
17603
17604 if (ST->hasMVEIntegerOps())
17605 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17606 return NewLoad;
17607
17608 return SDValue();
17609}
17610
17611static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
17612 const ARMSubtarget *ST) {
17613 if (ST->hasMVEFloatOps())
17614 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17615 return NewLoad;
17616
17617 return SDValue();
17618}
17619
17620// Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
17621// constant bounds.
17622static SDValue PerformMinMaxToSatCombine(SDValue Op, SelectionDAG &DAG,
17623 const ARMSubtarget *Subtarget) {
17624 if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
17625 !Subtarget->isThumb2())
17626 return SDValue();
17627
17628 EVT VT = Op.getValueType();
17629 SDValue Op0 = Op.getOperand(0);
17630
17631 if (VT != MVT::i32 ||
17632 (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
17633 !isa<ConstantSDNode>(Op.getOperand(1)) ||
17634 !isa<ConstantSDNode>(Op0.getOperand(1)))
17635 return SDValue();
17636
17637 SDValue Min = Op;
17638 SDValue Max = Op0;
17639 SDValue Input = Op0.getOperand(0);
17640 if (Min.getOpcode() == ISD::SMAX)
17641 std::swap(Min, Max);
17642
17643 APInt MinC = Min.getConstantOperandAPInt(1);
17644 APInt MaxC = Max.getConstantOperandAPInt(1);
17645
17646 if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX ||
17647 !(MinC + 1).isPowerOf2())
17648 return SDValue();
17649
17650 SDLoc DL(Op);
17651 if (MinC == ~MaxC)
17652 return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
17653 DAG.getConstant(MinC.countTrailingOnes(), DL, VT));
17654 if (MaxC == 0)
17655 return DAG.getNode(ARMISD::USAT, DL, VT, Input,
17656 DAG.getConstant(MinC.countTrailingOnes(), DL, VT));
17657
17658 return SDValue();
17659}
17660
17661/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
17662/// saturates.
17663static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
17664 const ARMSubtarget *ST) {
17665 EVT VT = N->getValueType(0);
17666 SDValue N0 = N->getOperand(0);
17667
17668 if (VT == MVT::i32)
17669 return PerformMinMaxToSatCombine(SDValue(N, 0), DAG, ST);
17670
17671 if (!ST->hasMVEIntegerOps())
17672 return SDValue();
17673
17674 if (SDValue V = PerformVQDMULHCombine(N, DAG))
17675 return V;
17676
17677 if (VT != MVT::v4i32 && VT != MVT::v8i16)
17678 return SDValue();
17679
17680 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
17681 // Check one is a smin and the other is a smax
17682 if (Min->getOpcode() != ISD::SMIN)
17683 std::swap(Min, Max);
17684 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
17685 return false;
17686
17687 APInt SaturateC;
17688 if (VT == MVT::v4i32)
17689 SaturateC = APInt(32, (1 << 15) - 1, true);
17690 else //if (VT == MVT::v8i16)
17691 SaturateC = APInt(16, (1 << 7) - 1, true);
17692
17693 APInt MinC, MaxC;
17694 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
17695 MinC != SaturateC)
17696 return false;
17697 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
17698 MaxC != ~SaturateC)
17699 return false;
17700 return true;
17701 };
17702
17703 if (IsSignedSaturate(N, N0.getNode())) {
17704 SDLoc DL(N);
17705 MVT ExtVT, HalfVT;
17706 if (VT == MVT::v4i32) {
17707 HalfVT = MVT::v8i16;
17708 ExtVT = MVT::v4i16;
17709 } else { // if (VT == MVT::v8i16)
17710 HalfVT = MVT::v16i8;
17711 ExtVT = MVT::v8i8;
17712 }
17713
17714 // Create a VQMOVNB with undef top lanes, then signed extended into the top
17715 // half. That extend will hopefully be removed if only the bottom bits are
17716 // demanded (though a truncating store, for example).
17717 SDValue VQMOVN =
17718 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
17719 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
17720 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
17721 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
17722 DAG.getValueType(ExtVT));
17723 }
17724
17725 auto IsUnsignedSaturate = [&](SDNode *Min) {
17726 // For unsigned, we just need to check for <= 0xffff
17727 if (Min->getOpcode() != ISD::UMIN)
17728 return false;
17729
17730 APInt SaturateC;
17731 if (VT == MVT::v4i32)
17732 SaturateC = APInt(32, (1 << 16) - 1, true);
17733 else //if (VT == MVT::v8i16)
17734 SaturateC = APInt(16, (1 << 8) - 1, true);
17735
17736 APInt MinC;
17737 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
17738 MinC != SaturateC)
17739 return false;
17740 return true;
17741 };
17742
17743 if (IsUnsignedSaturate(N)) {
17744 SDLoc DL(N);
17745 MVT HalfVT;
17746 unsigned ExtConst;
17747 if (VT == MVT::v4i32) {
17748 HalfVT = MVT::v8i16;
17749 ExtConst = 0x0000FFFF;
17750 } else { //if (VT == MVT::v8i16)
17751 HalfVT = MVT::v16i8;
17752 ExtConst = 0x00FF;
17753 }
17754
17755 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
17756 // an AND. That extend will hopefully be removed if only the bottom bits are
17757 // demanded (though a truncating store, for example).
17758 SDValue VQMOVN =
17759 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
17760 DAG.getConstant(0, DL, MVT::i32));
17761 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
17762 return DAG.getNode(ISD::AND, DL, VT, Bitcast,
17763 DAG.getConstant(ExtConst, DL, VT));
17764 }
17765
17766 return SDValue();
17767}
17768
17769static const APInt *isPowerOf2Constant(SDValue V) {
17770 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
17771 if (!C)
17772 return nullptr;
17773 const APInt *CV = &C->getAPIntValue();
17774 return CV->isPowerOf2() ? CV : nullptr;
17775}
17776
17777SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
17778 // If we have a CMOV, OR and AND combination such as:
17779 // if (x & CN)
17780 // y |= CM;
17781 //
17782 // And:
17783 // * CN is a single bit;
17784 // * All bits covered by CM are known zero in y
17785 //
17786 // Then we can convert this into a sequence of BFI instructions. This will
17787 // always be a win if CM is a single bit, will always be no worse than the
17788 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
17789 // three bits (due to the extra IT instruction).
17790
17791 SDValue Op0 = CMOV->getOperand(0);
17792 SDValue Op1 = CMOV->getOperand(1);
17793 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
17794 auto CC = CCNode->getAPIntValue().getLimitedValue();
17795 SDValue CmpZ = CMOV->getOperand(4);
17796
17797 // The compare must be against zero.
17798 if (!isNullConstant(CmpZ->getOperand(1)))
17799 return SDValue();
17800
17801 assert(CmpZ->getOpcode() == ARMISD::CMPZ)(static_cast <bool> (CmpZ->getOpcode() == ARMISD::CMPZ
) ? void (0) : __assert_fail ("CmpZ->getOpcode() == ARMISD::CMPZ"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17801, __extension__
__PRETTY_FUNCTION__))
;
17802 SDValue And = CmpZ->getOperand(0);
17803 if (And->getOpcode() != ISD::AND)
17804 return SDValue();
17805 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
17806 if (!AndC)
17807 return SDValue();
17808 SDValue X = And->getOperand(0);
17809
17810 if (CC == ARMCC::EQ) {
17811 // We're performing an "equal to zero" compare. Swap the operands so we
17812 // canonicalize on a "not equal to zero" compare.
17813 std::swap(Op0, Op1);
17814 } else {
17815 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?")(static_cast <bool> (CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"
) ? void (0) : __assert_fail ("CC == ARMCC::NE && \"How can a CMPZ node not be EQ or NE?\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17815, __extension__
__PRETTY_FUNCTION__))
;
17816 }
17817
17818 if (Op1->getOpcode() != ISD::OR)
17819 return SDValue();
17820
17821 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
17822 if (!OrC)
17823 return SDValue();
17824 SDValue Y = Op1->getOperand(0);
17825
17826 if (Op0 != Y)
17827 return SDValue();
17828
17829 // Now, is it profitable to continue?
17830 APInt OrCI = OrC->getAPIntValue();
17831 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
17832 if (OrCI.countPopulation() > Heuristic)
17833 return SDValue();
17834
17835 // Lastly, can we determine that the bits defined by OrCI
17836 // are zero in Y?
17837 KnownBits Known = DAG.computeKnownBits(Y);
17838 if ((OrCI & Known.Zero) != OrCI)
17839 return SDValue();
17840
17841 // OK, we can do the combine.
17842 SDValue V = Y;
17843 SDLoc dl(X);
17844 EVT VT = X.getValueType();
17845 unsigned BitInX = AndC->logBase2();
17846
17847 if (BitInX != 0) {
17848 // We must shift X first.
17849 X = DAG.getNode(ISD::SRL, dl, VT, X,
17850 DAG.getConstant(BitInX, dl, VT));
17851 }
17852
17853 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
17854 BitInY < NumActiveBits; ++BitInY) {
17855 if (OrCI[BitInY] == 0)
17856 continue;
17857 APInt Mask(VT.getSizeInBits(), 0);
17858 Mask.setBit(BitInY);
17859 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
17860 // Confusingly, the operand is an *inverted* mask.
17861 DAG.getConstant(~Mask, dl, VT));
17862 }
17863
17864 return V;
17865}
17866
17867// Given N, the value controlling the conditional branch, search for the loop
17868// intrinsic, returning it, along with how the value is used. We need to handle
17869// patterns such as the following:
17870// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
17871// (brcond (setcc (loop.decrement), 0, eq), exit)
17872// (brcond (setcc (loop.decrement), 0, ne), header)
17873static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
17874 bool &Negate) {
17875 switch (N->getOpcode()) {
17876 default:
17877 break;
17878 case ISD::XOR: {
17879 if (!isa<ConstantSDNode>(N.getOperand(1)))
17880 return SDValue();
17881 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
17882 return SDValue();
17883 Negate = !Negate;
17884 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
17885 }
17886 case ISD::SETCC: {
17887 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
17888 if (!Const)
17889 return SDValue();
17890 if (Const->isZero())
17891 Imm = 0;
17892 else if (Const->isOne())
17893 Imm = 1;
17894 else
17895 return SDValue();
17896 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
17897 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
17898 }
17899 case ISD::INTRINSIC_W_CHAIN: {
17900 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
17901 if (IntOp != Intrinsic::test_start_loop_iterations &&
17902 IntOp != Intrinsic::loop_decrement_reg)
17903 return SDValue();
17904 return N;
17905 }
17906 }
17907 return SDValue();
17908}
17909
17910static SDValue PerformHWLoopCombine(SDNode *N,
17911 TargetLowering::DAGCombinerInfo &DCI,
17912 const ARMSubtarget *ST) {
17913
17914 // The hwloop intrinsics that we're interested are used for control-flow,
17915 // either for entering or exiting the loop:
17916 // - test.start.loop.iterations will test whether its operand is zero. If it
17917 // is zero, the proceeding branch should not enter the loop.
17918 // - loop.decrement.reg also tests whether its operand is zero. If it is
17919 // zero, the proceeding branch should not branch back to the beginning of
17920 // the loop.
17921 // So here, we need to check that how the brcond is using the result of each
17922 // of the intrinsics to ensure that we're branching to the right place at the
17923 // right time.
17924
17925 ISD::CondCode CC;
17926 SDValue Cond;
17927 int Imm = 1;
17928 bool Negate = false;
17929 SDValue Chain = N->getOperand(0);
17930 SDValue Dest;
17931
17932 if (N->getOpcode() == ISD::BRCOND) {
17933 CC = ISD::SETEQ;
17934 Cond = N->getOperand(1);
17935 Dest = N->getOperand(2);
17936 } else {
17937 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!")(static_cast <bool> (N->getOpcode() == ISD::BR_CC &&
"Expected BRCOND or BR_CC!") ? void (0) : __assert_fail ("N->getOpcode() == ISD::BR_CC && \"Expected BRCOND or BR_CC!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17937, __extension__
__PRETTY_FUNCTION__))
;
17938 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
17939 Cond = N->getOperand(2);
17940 Dest = N->getOperand(4);
17941 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
17942 if (!Const->isOne() && !Const->isZero())
17943 return SDValue();
17944 Imm = Const->getZExtValue();
17945 } else
17946 return SDValue();
17947 }
17948
17949 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
17950 if (!Int)
17951 return SDValue();
17952
17953 if (Negate)
17954 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
17955
17956 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
17957 return (CC == ISD::SETEQ && Imm == 0) ||
17958 (CC == ISD::SETNE && Imm == 1) ||
17959 (CC == ISD::SETLT && Imm == 1) ||
17960 (CC == ISD::SETULT && Imm == 1);
17961 };
17962
17963 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
17964 return (CC == ISD::SETEQ && Imm == 1) ||
17965 (CC == ISD::SETNE && Imm == 0) ||
17966 (CC == ISD::SETGT && Imm == 0) ||
17967 (CC == ISD::SETUGT && Imm == 0) ||
17968 (CC == ISD::SETGE && Imm == 1) ||
17969 (CC == ISD::SETUGE && Imm == 1);
17970 };
17971
17972 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&(static_cast <bool> ((IsTrueIfZero(CC, Imm) || IsFalseIfZero
(CC, Imm)) && "unsupported condition") ? void (0) : __assert_fail
("(IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && \"unsupported condition\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17973, __extension__
__PRETTY_FUNCTION__))
17973 "unsupported condition")(static_cast <bool> ((IsTrueIfZero(CC, Imm) || IsFalseIfZero
(CC, Imm)) && "unsupported condition") ? void (0) : __assert_fail
("(IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && \"unsupported condition\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17973, __extension__
__PRETTY_FUNCTION__))
;
17974
17975 SDLoc dl(Int);
17976 SelectionDAG &DAG = DCI.DAG;
17977 SDValue Elements = Int.getOperand(2);
17978 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
17979 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)(static_cast <bool> ((N->hasOneUse() && N->
use_begin()->getOpcode() == ISD::BR) && "expected single br user"
) ? void (0) : __assert_fail ("(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) && \"expected single br user\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17980, __extension__
__PRETTY_FUNCTION__))
17980 && "expected single br user")(static_cast <bool> ((N->hasOneUse() && N->
use_begin()->getOpcode() == ISD::BR) && "expected single br user"
) ? void (0) : __assert_fail ("(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) && \"expected single br user\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 17980, __extension__
__PRETTY_FUNCTION__))
;
17981 SDNode *Br = *N->use_begin();
17982 SDValue OtherTarget = Br->getOperand(1);
17983
17984 // Update the unconditional branch to branch to the given Dest.
17985 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
17986 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
17987 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
17988 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
17989 };
17990
17991 if (IntOp == Intrinsic::test_start_loop_iterations) {
17992 SDValue Res;
17993 SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
17994 // We expect this 'instruction' to branch when the counter is zero.
17995 if (IsTrueIfZero(CC, Imm)) {
17996 SDValue Ops[] = {Chain, Setup, Dest};
17997 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
17998 } else {
17999 // The logic is the reverse of what we need for WLS, so find the other
18000 // basic block target: the target of the proceeding br.
18001 UpdateUncondBr(Br, Dest, DAG);
18002
18003 SDValue Ops[] = {Chain, Setup, OtherTarget};
18004 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18005 }
18006 // Update LR count to the new value
18007 DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
18008 // Update chain
18009 DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
18010 return Res;
18011 } else {
18012 SDValue Size = DAG.getTargetConstant(
18013 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
18014 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
18015 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
18016 DAG.getVTList(MVT::i32, MVT::Other), Args);
18017 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
18018
18019 // We expect this instruction to branch when the count is not zero.
18020 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18021
18022 // Update the unconditional branch to target the loop preheader if we've
18023 // found the condition has been reversed.
18024 if (Target == OtherTarget)
18025 UpdateUncondBr(Br, Dest, DAG);
18026
18027 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18028 SDValue(LoopDec.getNode(), 1), Chain);
18029
18030 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18031 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
18032 }
18033 return SDValue();
18034}
18035
18036/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18037SDValue
18038ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
18039 SDValue Cmp = N->getOperand(4);
18040 if (Cmp.getOpcode() != ARMISD::CMPZ)
18041 // Only looking at NE cases.
18042 return SDValue();
18043
18044 EVT VT = N->getValueType(0);
18045 SDLoc dl(N);
18046 SDValue LHS = Cmp.getOperand(0);
18047 SDValue RHS = Cmp.getOperand(1);
18048 SDValue Chain = N->getOperand(0);
18049 SDValue BB = N->getOperand(1);
18050 SDValue ARMcc = N->getOperand(2);
18051 ARMCC::CondCodes CC =
18052 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
18053
18054 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
18055 // -> (brcond Chain BB CC CPSR Cmp)
18056 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18057 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
18058 LHS->getOperand(0)->hasOneUse()) {
18059 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
18060 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
18061 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
18062 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
18063 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
18064 (LHS01C && LHS01C->getZExtValue() == 1) &&
18065 (LHS1C && LHS1C->getZExtValue() == 1) &&
18066 (RHSC && RHSC->getZExtValue() == 0)) {
18067 return DAG.getNode(
18068 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
18069 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
18070 }
18071 }
18072
18073 return SDValue();
18074}
18075
18076/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18077SDValue
18078ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
18079 SDValue Cmp = N->getOperand(4);
18080 if (Cmp.getOpcode() != ARMISD::CMPZ)
18081 // Only looking at EQ and NE cases.
18082 return SDValue();
18083
18084 EVT VT = N->getValueType(0);
18085 SDLoc dl(N);
18086 SDValue LHS = Cmp.getOperand(0);
18087 SDValue RHS = Cmp.getOperand(1);
18088 SDValue FalseVal = N->getOperand(0);
18089 SDValue TrueVal = N->getOperand(1);
18090 SDValue ARMcc = N->getOperand(2);
18091 ARMCC::CondCodes CC =
18092 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
18093
18094 // BFI is only available on V6T2+.
18095 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18096 SDValue R = PerformCMOVToBFICombine(N, DAG);
18097 if (R)
18098 return R;
18099 }
18100
18101 // Simplify
18102 // mov r1, r0
18103 // cmp r1, x
18104 // mov r0, y
18105 // moveq r0, x
18106 // to
18107 // cmp r0, x
18108 // movne r0, y
18109 //
18110 // mov r1, r0
18111 // cmp r1, x
18112 // mov r0, x
18113 // movne r0, y
18114 // to
18115 // cmp r0, x
18116 // movne r0, y
18117 /// FIXME: Turn this into a target neutral optimization?
18118 SDValue Res;
18119 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
18120 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
18121 N->getOperand(3), Cmp);
18122 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
18123 SDValue ARMcc;
18124 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
18125 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
18126 N->getOperand(3), NewCmp);
18127 }
18128
18129 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
18130 // -> (cmov F T CC CPSR Cmp)
18131 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
18132 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
18133 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
18134 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
18135 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
18136 (LHS1C && LHS1C->getZExtValue() == 1) &&
18137 (RHSC && RHSC->getZExtValue() == 0)) {
18138 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
18139 LHS->getOperand(2), LHS->getOperand(3),
18140 LHS->getOperand(4));
18141 }
18142 }
18143
18144 if (!VT.isInteger())
18145 return SDValue();
18146
18147 // Fold away an unneccessary CMPZ/CMOV
18148 // CMOV A, B, C1, $cpsr, (CMPZ (CMOV 1, 0, C2, D), 0) ->
18149 // if C1==EQ -> CMOV A, B, C2, $cpsr, D
18150 // if C1==NE -> CMOV A, B, NOT(C2), $cpsr, D
18151 if (N->getConstantOperandVal(2) == ARMCC::EQ ||
18152 N->getConstantOperandVal(2) == ARMCC::NE) {
18153 ARMCC::CondCodes Cond;
18154 if (SDValue C = IsCMPZCSINC(N->getOperand(4).getNode(), Cond)) {
18155 if (N->getConstantOperandVal(2) == ARMCC::NE)
18156 Cond = ARMCC::getOppositeCondition(Cond);
18157 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
18158 N->getOperand(1),
18159 DAG.getTargetConstant(Cond, SDLoc(N), MVT::i32),
18160 N->getOperand(3), C);
18161 }
18162 }
18163
18164 // Materialize a boolean comparison for integers so we can avoid branching.
18165 if (isNullConstant(FalseVal)) {
18166 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
18167 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
18168 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
18169 // right 5 bits will make that 32 be 1, otherwise it will be 0.
18170 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
18171 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18172 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
18173 DAG.getConstant(5, dl, MVT::i32));
18174 } else {
18175 // CMOV 0, 1, ==, (CMPZ x, y) ->
18176 // (ADDCARRY (SUB x, y), t:0, t:1)
18177 // where t = (SUBCARRY 0, (SUB x, y), 0)
18178 //
18179 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
18180 // x != y. In other words, a carry C == 1 when x == y, C == 0
18181 // otherwise.
18182 // The final ADDCARRY computes
18183 // x - y + (0 - (x - y)) + C == C
18184 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18185 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18186 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
18187 // ISD::SUBCARRY returns a borrow but we want the carry here
18188 // actually.
18189 SDValue Carry =
18190 DAG.getNode(ISD::SUB, dl, MVT::i32,
18191 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
18192 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
18193 }
18194 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
18195 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
18196 // This seems pointless but will allow us to combine it further below.
18197 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
18198 SDValue Sub =
18199 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18200 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
18201 Sub.getValue(1), SDValue());
18202 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
18203 N->getOperand(3), CPSRGlue.getValue(1));
18204 FalseVal = Sub;
18205 }
18206 } else if (isNullConstant(TrueVal)) {
18207 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
18208 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
18209 // This seems pointless but will allow us to combine it further below
18210 // Note that we change == for != as this is the dual for the case above.
18211 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
18212 SDValue Sub =
18213 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18214 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
18215 Sub.getValue(1), SDValue());
18216 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
18217 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
18218 N->getOperand(3), CPSRGlue.getValue(1));
18219 FalseVal = Sub;
18220 }
18221 }
18222
18223 // On Thumb1, the DAG above may be further combined if z is a power of 2
18224 // (z == 2 ^ K).
18225 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
18226 // t1 = (USUBO (SUB x, y), 1)
18227 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
18228 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18229 //
18230 // This also handles the special case of comparing against zero; it's
18231 // essentially, the same pattern, except there's no SUBS:
18232 // CMOV x, z, !=, (CMPZ x, 0) ->
18233 // t1 = (USUBO x, 1)
18234 // t2 = (SUBCARRY x, t1:0, t1:1)
18235 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18236 const APInt *TrueConst;
18237 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
18238 ((FalseVal.getOpcode() == ARMISD::SUBS &&
18239 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
18240 (FalseVal == LHS && isNullConstant(RHS))) &&
18241 (TrueConst = isPowerOf2Constant(TrueVal))) {
18242 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18243 unsigned ShiftAmount = TrueConst->logBase2();
18244 if (ShiftAmount)
18245 TrueVal = DAG.getConstant(1, dl, VT);
18246 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
18247 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
18248
18249 if (ShiftAmount)
18250 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
18251 DAG.getConstant(ShiftAmount, dl, MVT::i32));
18252 }
18253
18254 if (Res.getNode()) {
18255 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
18256 // Capture demanded bits information that would be otherwise lost.
18257 if (Known.Zero == 0xfffffffe)
18258 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18259 DAG.getValueType(MVT::i1));
18260 else if (Known.Zero == 0xffffff00)
18261 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18262 DAG.getValueType(MVT::i8));
18263 else if (Known.Zero == 0xffff0000)
18264 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18265 DAG.getValueType(MVT::i16));
18266 }
18267
18268 return Res;
18269}
18270
18271static SDValue PerformBITCASTCombine(SDNode *N,
18272 TargetLowering::DAGCombinerInfo &DCI,
18273 const ARMSubtarget *ST) {
18274 SelectionDAG &DAG = DCI.DAG;
18275 SDValue Src = N->getOperand(0);
18276 EVT DstVT = N->getValueType(0);
18277
18278 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
18279 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
18280 EVT SrcVT = Src.getValueType();
18281 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
18282 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
18283 }
18284
18285 // We may have a bitcast of something that has already had this bitcast
18286 // combine performed on it, so skip past any VECTOR_REG_CASTs.
18287 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
18288 Src = Src.getOperand(0);
18289
18290 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
18291 // would be generated is at least the width of the element type.
18292 EVT SrcVT = Src.getValueType();
18293 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
18294 Src.getOpcode() == ARMISD::VMVNIMM ||
18295 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
18296 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
18297 DAG.getDataLayout().isBigEndian())
18298 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
18299
18300 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
18301 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
18302 return R;
18303
18304 return SDValue();
18305}
18306
18307// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
18308// node into stack operations after legalizeOps.
18309SDValue ARMTargetLowering::PerformMVETruncCombine(
18310 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18311 SelectionDAG &DAG = DCI.DAG;
18312 EVT VT = N->getValueType(0);
18313 SDLoc DL(N);
18314
18315 // MVETrunc(Undef, Undef) -> Undef
18316 if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
18317 return DAG.getUNDEF(VT);
18318
18319 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
18320 if (N->getNumOperands() == 2 &&
18321 N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
18322 N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
18323 return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
18324 N->getOperand(0).getOperand(1),
18325 N->getOperand(1).getOperand(0),
18326 N->getOperand(1).getOperand(1));
18327
18328 // MVETrunc(shuffle, shuffle) -> VMOVN
18329 if (N->getNumOperands() == 2 &&
18330 N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
18331 N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
18332 auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
18333 auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
18334
18335 if (S0->getOperand(0) == S1->getOperand(0) &&
18336 S0->getOperand(1) == S1->getOperand(1)) {
18337 // Construct complete shuffle mask
18338 SmallVector<int, 8> Mask(S0->getMask());
18339 Mask.append(S1->getMask().begin(), S1->getMask().end());
18340
18341 if (isVMOVNTruncMask(Mask, VT, false))
18342 return DAG.getNode(
18343 ARMISD::VMOVN, DL, VT,
18344 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18345 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18346 DAG.getConstant(1, DL, MVT::i32));
18347 if (isVMOVNTruncMask(Mask, VT, true))
18348 return DAG.getNode(
18349 ARMISD::VMOVN, DL, VT,
18350 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18351 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18352 DAG.getConstant(1, DL, MVT::i32));
18353 }
18354 }
18355
18356 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
18357 // truncate to a buildvector to allow the generic optimisations to kick in.
18358 if (all_of(N->ops(), [](SDValue Op) {
18359 return Op.getOpcode() == ISD::BUILD_VECTOR ||
18360 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
18361 (Op.getOpcode() == ISD::BITCAST &&
18362 Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
18363 })) {
18364 SmallVector<SDValue, 8> Extracts;
18365 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
18366 SDValue O = N->getOperand(Op);
18367 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
18368 SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
18369 DAG.getConstant(i, DL, MVT::i32));
18370 Extracts.push_back(Ext);
18371 }
18372 }
18373 return DAG.getBuildVector(VT, DL, Extracts);
18374 }
18375
18376 // If we are late in the legalization process and nothing has optimised
18377 // the trunc to anything better, lower it to a stack store and reload,
18378 // performing the truncation whilst keeping the lanes in the correct order:
18379 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
18380 if (!DCI.isAfterLegalizeDAG())
18381 return SDValue();
18382
18383 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::Fixed(16), Align(4));
18384 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18385 int NumIns = N->getNumOperands();
18386 assert((NumIns == 2 || NumIns == 4) &&(static_cast <bool> ((NumIns == 2 || NumIns == 4) &&
"Expected 2 or 4 inputs to an MVETrunc") ? void (0) : __assert_fail
("(NumIns == 2 || NumIns == 4) && \"Expected 2 or 4 inputs to an MVETrunc\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18387, __extension__
__PRETTY_FUNCTION__))
18387 "Expected 2 or 4 inputs to an MVETrunc")(static_cast <bool> ((NumIns == 2 || NumIns == 4) &&
"Expected 2 or 4 inputs to an MVETrunc") ? void (0) : __assert_fail
("(NumIns == 2 || NumIns == 4) && \"Expected 2 or 4 inputs to an MVETrunc\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18387, __extension__
__PRETTY_FUNCTION__))
;
18388 EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
18389 if (N->getNumOperands() == 4)
18390 StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
18391
18392 SmallVector<SDValue> Chains;
18393 for (int I = 0; I < NumIns; I++) {
18394 SDValue Ptr = DAG.getNode(
18395 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18396 DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
18397 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18398 DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
18399 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
18400 Ptr, MPI, StoreVT, Align(4));
18401 Chains.push_back(Ch);
18402 }
18403
18404 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18405 MachinePointerInfo MPI =
18406 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
18407 return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
18408}
18409
18410// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
18411static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N,
18412 SelectionDAG &DAG) {
18413 SDValue N0 = N->getOperand(0);
18414 LoadSDNode *LD = dyn_cast<LoadSDNode>(N0.getNode());
18415 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
18416 return SDValue();
18417
18418 EVT FromVT = LD->getMemoryVT();
18419 EVT ToVT = N->getValueType(0);
18420 if (!ToVT.isVector())
18421 return SDValue();
18422 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2)(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements() * 2) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18422, __extension__
__PRETTY_FUNCTION__))
;
18423 EVT ToEltVT = ToVT.getVectorElementType();
18424 EVT FromEltVT = FromVT.getVectorElementType();
18425
18426 unsigned NumElements = 0;
18427 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
18428 NumElements = 4;
18429 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
18430 NumElements = 8;
18431 assert(NumElements != 0)(static_cast <bool> (NumElements != 0) ? void (0) : __assert_fail
("NumElements != 0", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18431, __extension__ __PRETTY_FUNCTION__))
;
18432
18433 ISD::LoadExtType NewExtType =
18434 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18435 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
18436 LD->getExtensionType() != ISD::EXTLOAD &&
18437 LD->getExtensionType() != NewExtType)
18438 return SDValue();
18439
18440 LLVMContext &C = *DAG.getContext();
18441 SDLoc DL(LD);
18442 // Details about the old load
18443 SDValue Ch = LD->getChain();
18444 SDValue BasePtr = LD->getBasePtr();
18445 Align Alignment = LD->getOriginalAlign();
18446 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18447 AAMDNodes AAInfo = LD->getAAInfo();
18448
18449 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
18450 EVT NewFromVT = EVT::getVectorVT(
18451 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
18452 EVT NewToVT = EVT::getVectorVT(
18453 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
18454
18455 SmallVector<SDValue, 4> Loads;
18456 SmallVector<SDValue, 4> Chains;
18457 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18458 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18459 SDValue NewPtr =
18460 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
18461
18462 SDValue NewLoad =
18463 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
18464 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
18465 Alignment, MMOFlags, AAInfo);
18466 Loads.push_back(NewLoad);
18467 Chains.push_back(SDValue(NewLoad.getNode(), 1));
18468 }
18469
18470 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18471 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
18472 return DAG.getMergeValues(Loads, DL);
18473}
18474
18475// Perform combines for MVEEXT. If it has not be optimized to anything better
18476// before lowering, it gets converted to stack store and extloads performing the
18477// extend whilst still keeping the same lane ordering.
18478SDValue ARMTargetLowering::PerformMVEExtCombine(
18479 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18480 SelectionDAG &DAG = DCI.DAG;
18481 EVT VT = N->getValueType(0);
18482 SDLoc DL(N);
18483 assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements")(static_cast <bool> (N->getNumValues() == 2 &&
"Expected MVEEXT with 2 elements") ? void (0) : __assert_fail
("N->getNumValues() == 2 && \"Expected MVEEXT with 2 elements\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18483, __extension__
__PRETTY_FUNCTION__))
;
18484 assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type")(static_cast <bool> ((VT == MVT::v4i32 || VT == MVT::v8i16
) && "Unexpected MVEEXT type") ? void (0) : __assert_fail
("(VT == MVT::v4i32 || VT == MVT::v8i16) && \"Unexpected MVEEXT type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18484, __extension__
__PRETTY_FUNCTION__))
;
18485
18486 EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18487 *DAG.getContext());
18488 auto Extend = [&](SDValue V) {
18489 SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
18490 return N->getOpcode() == ARMISD::MVESEXT
18491 ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
18492 DAG.getValueType(ExtVT))
18493 : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
18494 };
18495
18496 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
18497 if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
18498 SDValue Ext = Extend(N->getOperand(0));
18499 return DAG.getMergeValues({Ext, Ext}, DL);
18500 }
18501
18502 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
18503 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
18504 ArrayRef<int> Mask = SVN->getMask();
18505 assert(Mask.size() == 2 * VT.getVectorNumElements())(static_cast <bool> (Mask.size() == 2 * VT.getVectorNumElements
()) ? void (0) : __assert_fail ("Mask.size() == 2 * VT.getVectorNumElements()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18505, __extension__
__PRETTY_FUNCTION__))
;
18506 assert(Mask.size() == SVN->getValueType(0).getVectorNumElements())(static_cast <bool> (Mask.size() == SVN->getValueType
(0).getVectorNumElements()) ? void (0) : __assert_fail ("Mask.size() == SVN->getValueType(0).getVectorNumElements()"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18506, __extension__
__PRETTY_FUNCTION__))
;
18507 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
18508 SDValue Op0 = SVN->getOperand(0);
18509 SDValue Op1 = SVN->getOperand(1);
18510
18511 auto CheckInregMask = [&](int Start, int Offset) {
18512 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
18513 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
18514 return false;
18515 return true;
18516 };
18517 SDValue V0 = SDValue(N, 0);
18518 SDValue V1 = SDValue(N, 1);
18519 if (CheckInregMask(0, 0))
18520 V0 = Extend(Op0);
18521 else if (CheckInregMask(0, 1))
18522 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18523 else if (CheckInregMask(0, Mask.size()))
18524 V0 = Extend(Op1);
18525 else if (CheckInregMask(0, Mask.size() + 1))
18526 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18527
18528 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
18529 V1 = Extend(Op1);
18530 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
18531 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18532 else if (CheckInregMask(VT.getVectorNumElements(), 0))
18533 V1 = Extend(Op0);
18534 else if (CheckInregMask(VT.getVectorNumElements(), 1))
18535 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18536
18537 if (V0.getNode() != N || V1.getNode() != N)
18538 return DAG.getMergeValues({V0, V1}, DL);
18539 }
18540
18541 // MVEEXT(load) -> extload, extload
18542 if (N->getOperand(0)->getOpcode() == ISD::LOAD)
18543 if (SDValue L = PerformSplittingMVEEXTToWideningLoad(N, DAG))
18544 return L;
18545
18546 if (!DCI.isAfterLegalizeDAG())
18547 return SDValue();
18548
18549 // Lower to a stack store and reload:
18550 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
18551 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::Fixed(16), Align(4));
18552 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18553 int NumOuts = N->getNumValues();
18554 assert((NumOuts == 2 || NumOuts == 4) &&(static_cast <bool> ((NumOuts == 2 || NumOuts == 4) &&
"Expected 2 or 4 outputs to an MVEEXT") ? void (0) : __assert_fail
("(NumOuts == 2 || NumOuts == 4) && \"Expected 2 or 4 outputs to an MVEEXT\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18555, __extension__
__PRETTY_FUNCTION__))
18555 "Expected 2 or 4 outputs to an MVEEXT")(static_cast <bool> ((NumOuts == 2 || NumOuts == 4) &&
"Expected 2 or 4 outputs to an MVEEXT") ? void (0) : __assert_fail
("(NumOuts == 2 || NumOuts == 4) && \"Expected 2 or 4 outputs to an MVEEXT\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 18555, __extension__
__PRETTY_FUNCTION__))
;
18556 EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18557 *DAG.getContext());
18558 if (N->getNumOperands() == 4)
18559 LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
18560
18561 MachinePointerInfo MPI =
18562 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
18563 SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
18564 StackPtr, MPI, Align(4));
18565
18566 SmallVector<SDValue> Loads;
18567 for (int I = 0; I < NumOuts; I++) {
18568 SDValue Ptr = DAG.getNode(
18569 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18570 DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
18571 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18572 DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
18573 SDValue Load = DAG.getExtLoad(
18574 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
18575 VT, Chain, Ptr, MPI, LoadVT, Align(4));
18576 Loads.push_back(Load);
18577 }
18578
18579 return DAG.getMergeValues(Loads, DL);
18580}
18581
18582SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
18583 DAGCombinerInfo &DCI) const {
18584 switch (N->getOpcode()) {
18585 default: break;
18586 case ISD::SELECT_CC:
18587 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
18588 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
18589 case ISD::SETCC: return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
18590 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
18591 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
18592 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
18593 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
18594 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
18595 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
18596 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
18597 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
18598 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
18599 case ISD::BRCOND:
18600 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
18601 case ARMISD::ADDC:
18602 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
18603 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
18604 case ARMISD::BFI: return PerformBFICombine(N, DCI.DAG);
18605 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
18606 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
18607 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
18608 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI.DAG);
18609 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
18610 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
18611 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
18612 case ISD::EXTRACT_VECTOR_ELT:
18613 return PerformExtractEltCombine(N, DCI, Subtarget);
18614 case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DCI.DAG);
18615 case ISD::INSERT_SUBVECTOR: return PerformInsertSubvectorCombine(N, DCI);
18616 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
18617 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
18618 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
18619 case ISD::FP_TO_SINT:
18620 case ISD::FP_TO_UINT:
18621 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
18622 case ISD::FADD:
18623 return PerformFAddVSelectCombine(N, DCI.DAG, Subtarget);
18624 case ISD::FDIV:
18625 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
18626 case ISD::INTRINSIC_WO_CHAIN:
18627 return PerformIntrinsicCombine(N, DCI);
18628 case ISD::SHL:
18629 case ISD::SRA:
18630 case ISD::SRL:
18631 return PerformShiftCombine(N, DCI, Subtarget);
18632 case ISD::SIGN_EXTEND:
18633 case ISD::ZERO_EXTEND:
18634 case ISD::ANY_EXTEND:
18635 return PerformExtendCombine(N, DCI.DAG, Subtarget);
18636 case ISD::FP_EXTEND:
18637 return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
18638 case ISD::SMIN:
18639 case ISD::UMIN:
18640 case ISD::SMAX:
18641 case ISD::UMAX:
18642 return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
18643 case ARMISD::CMOV:
18644 return PerformCMOVCombine(N, DCI.DAG);
18645 case ARMISD::BRCOND:
18646 return PerformBRCONDCombine(N, DCI.DAG);
18647 case ARMISD::CMPZ:
18648 return PerformCMPZCombine(N, DCI.DAG);
18649 case ARMISD::CSINC:
18650 case ARMISD::CSINV:
18651 case ARMISD::CSNEG:
18652 return PerformCSETCombine(N, DCI.DAG);
18653 case ISD::LOAD:
18654 return PerformLOADCombine(N, DCI, Subtarget);
18655 case ARMISD::VLD1DUP:
18656 case ARMISD::VLD2DUP:
18657 case ARMISD::VLD3DUP:
18658 case ARMISD::VLD4DUP:
18659 return PerformVLDCombine(N, DCI);
18660 case ARMISD::BUILD_VECTOR:
18661 return PerformARMBUILD_VECTORCombine(N, DCI);
18662 case ISD::BITCAST:
18663 return PerformBITCASTCombine(N, DCI, Subtarget);
18664 case ARMISD::PREDICATE_CAST:
18665 return PerformPREDICATE_CASTCombine(N, DCI);
18666 case ARMISD::VECTOR_REG_CAST:
18667 return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
18668 case ARMISD::MVETRUNC:
18669 return PerformMVETruncCombine(N, DCI);
18670 case ARMISD::MVESEXT:
18671 case ARMISD::MVEZEXT:
18672 return PerformMVEExtCombine(N, DCI);
18673 case ARMISD::VCMP:
18674 return PerformVCMPCombine(N, DCI.DAG, Subtarget);
18675 case ISD::VECREDUCE_ADD:
18676 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
18677 case ARMISD::VMOVN:
18678 return PerformVMOVNCombine(N, DCI);
18679 case ARMISD::VQMOVNs:
18680 case ARMISD::VQMOVNu:
18681 return PerformVQMOVNCombine(N, DCI);
18682 case ARMISD::ASRL:
18683 case ARMISD::LSRL:
18684 case ARMISD::LSLL:
18685 return PerformLongShiftCombine(N, DCI.DAG);
18686 case ARMISD::SMULWB: {
18687 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18688 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
18689 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18690 return SDValue();
18691 break;
18692 }
18693 case ARMISD::SMULWT: {
18694 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18695 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
18696 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18697 return SDValue();
18698 break;
18699 }
18700 case ARMISD::SMLALBB:
18701 case ARMISD::QADD16b:
18702 case ARMISD::QSUB16b:
18703 case ARMISD::UQADD16b:
18704 case ARMISD::UQSUB16b: {
18705 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18706 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
18707 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18708 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18709 return SDValue();
18710 break;
18711 }
18712 case ARMISD::SMLALBT: {
18713 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
18714 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
18715 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
18716 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
18717 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
18718 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
18719 return SDValue();
18720 break;
18721 }
18722 case ARMISD::SMLALTB: {
18723 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
18724 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
18725 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
18726 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
18727 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
18728 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
18729 return SDValue();
18730 break;
18731 }
18732 case ARMISD::SMLALTT: {
18733 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18734 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
18735 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18736 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18737 return SDValue();
18738 break;
18739 }
18740 case ARMISD::QADD8b:
18741 case ARMISD::QSUB8b:
18742 case ARMISD::UQADD8b:
18743 case ARMISD::UQSUB8b: {
18744 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18745 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
18746 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18747 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18748 return SDValue();
18749 break;
18750 }
18751 case ISD::INTRINSIC_VOID:
18752 case ISD::INTRINSIC_W_CHAIN:
18753 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
18754 case Intrinsic::arm_neon_vld1:
18755 case Intrinsic::arm_neon_vld1x2:
18756 case Intrinsic::arm_neon_vld1x3:
18757 case Intrinsic::arm_neon_vld1x4:
18758 case Intrinsic::arm_neon_vld2:
18759 case Intrinsic::arm_neon_vld3:
18760 case Intrinsic::arm_neon_vld4:
18761 case Intrinsic::arm_neon_vld2lane:
18762 case Intrinsic::arm_neon_vld3lane:
18763 case Intrinsic::arm_neon_vld4lane:
18764 case Intrinsic::arm_neon_vld2dup:
18765 case Intrinsic::arm_neon_vld3dup:
18766 case Intrinsic::arm_neon_vld4dup:
18767 case Intrinsic::arm_neon_vst1:
18768 case Intrinsic::arm_neon_vst1x2:
18769 case Intrinsic::arm_neon_vst1x3:
18770 case Intrinsic::arm_neon_vst1x4:
18771 case Intrinsic::arm_neon_vst2:
18772 case Intrinsic::arm_neon_vst3:
18773 case Intrinsic::arm_neon_vst4:
18774 case Intrinsic::arm_neon_vst2lane:
18775 case Intrinsic::arm_neon_vst3lane:
18776 case Intrinsic::arm_neon_vst4lane:
18777 return PerformVLDCombine(N, DCI);
18778 case Intrinsic::arm_mve_vld2q:
18779 case Intrinsic::arm_mve_vld4q:
18780 case Intrinsic::arm_mve_vst2q:
18781 case Intrinsic::arm_mve_vst4q:
18782 return PerformMVEVLDCombine(N, DCI);
18783 default: break;
18784 }
18785 break;
18786 }
18787 return SDValue();
18788}
18789
18790bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
18791 EVT VT) const {
18792 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
18793}
18794
18795bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
18796 Align Alignment,
18797 MachineMemOperand::Flags,
18798 bool *Fast) const {
18799 // Depends what it gets converted into if the type is weird.
18800 if (!VT.isSimple())
18801 return false;
18802
18803 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
18804 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
18805 auto Ty = VT.getSimpleVT().SimpleTy;
18806
18807 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
18808 // Unaligned access can use (for example) LRDB, LRDH, LDR
18809 if (AllowsUnaligned) {
18810 if (Fast)
18811 *Fast = Subtarget->hasV7Ops();
18812 return true;
18813 }
18814 }
18815
18816 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
18817 // For any little-endian targets with neon, we can support unaligned ld/st
18818 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
18819 // A big-endian target may also explicitly support unaligned accesses
18820 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
18821 if (Fast)
18822 *Fast = true;
18823 return true;
18824 }
18825 }
18826
18827 if (!Subtarget->hasMVEIntegerOps())
18828 return false;
18829
18830 // These are for predicates
18831 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
18832 Ty == MVT::v2i1)) {
18833 if (Fast)
18834 *Fast = true;
18835 return true;
18836 }
18837
18838 // These are for truncated stores/narrowing loads. They are fine so long as
18839 // the alignment is at least the size of the item being loaded
18840 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
18841 Alignment >= VT.getScalarSizeInBits() / 8) {
18842 if (Fast)
18843 *Fast = true;
18844 return true;
18845 }
18846
18847 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
18848 // VSTRW.U32 all store the vector register in exactly the same format, and
18849 // differ only in the range of their immediate offset field and the required
18850 // alignment. So there is always a store that can be used, regardless of
18851 // actual type.
18852 //
18853 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
18854 // VREV64.8) pair and get the same effect. This will likely be better than
18855 // aligning the vector through the stack.
18856 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
18857 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
18858 Ty == MVT::v2f64) {
18859 if (Fast)
18860 *Fast = true;
18861 return true;
18862 }
18863
18864 return false;
18865}
18866
18867
18868EVT ARMTargetLowering::getOptimalMemOpType(
18869 const MemOp &Op, const AttributeList &FuncAttributes) const {
18870 // See if we can use NEON instructions for this...
18871 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
18872 !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
18873 bool Fast;
18874 if (Op.size() >= 16 &&
18875 (Op.isAligned(Align(16)) ||
18876 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
18877 MachineMemOperand::MONone, &Fast) &&
18878 Fast))) {
18879 return MVT::v2f64;
18880 } else if (Op.size() >= 8 &&
18881 (Op.isAligned(Align(8)) ||
18882 (allowsMisalignedMemoryAccesses(
18883 MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
18884 Fast))) {
18885 return MVT::f64;
18886 }
18887 }
18888
18889 // Let the target-independent logic figure it out.
18890 return MVT::Other;
18891}
18892
18893// 64-bit integers are split into their high and low parts and held in two
18894// different registers, so the trunc is free since the low register can just
18895// be used.
18896bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
18897 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
18898 return false;
18899 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
18900 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
18901 return (SrcBits == 64 && DestBits == 32);
18902}
18903
18904bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
18905 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
18906 !DstVT.isInteger())
18907 return false;
18908 unsigned SrcBits = SrcVT.getSizeInBits();
18909 unsigned DestBits = DstVT.getSizeInBits();
18910 return (SrcBits == 64 && DestBits == 32);
18911}
18912
18913bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18914 if (Val.getOpcode() != ISD::LOAD)
18915 return false;
18916
18917 EVT VT1 = Val.getValueType();
18918 if (!VT1.isSimple() || !VT1.isInteger() ||
18919 !VT2.isSimple() || !VT2.isInteger())
18920 return false;
18921
18922 switch (VT1.getSimpleVT().SimpleTy) {
18923 default: break;
18924 case MVT::i1:
18925 case MVT::i8:
18926 case MVT::i16:
18927 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
18928 return true;
18929 }
18930
18931 return false;
18932}
18933
18934bool ARMTargetLowering::isFNegFree(EVT VT) const {
18935 if (!VT.isSimple())
18936 return false;
18937
18938 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
18939 // negate values directly (fneg is free). So, we don't want to let the DAG
18940 // combiner rewrite fneg into xors and some other instructions. For f16 and
18941 // FullFP16 argument passing, some bitcast nodes may be introduced,
18942 // triggering this DAG combine rewrite, so we are avoiding that with this.
18943 switch (VT.getSimpleVT().SimpleTy) {
18944 default: break;
18945 case MVT::f16:
18946 return Subtarget->hasFullFP16();
18947 }
18948
18949 return false;
18950}
18951
18952/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
18953/// of the vector elements.
18954static bool areExtractExts(Value *Ext1, Value *Ext2) {
18955 auto areExtDoubled = [](Instruction *Ext) {
18956 return Ext->getType()->getScalarSizeInBits() ==
18957 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
18958 };
18959
18960 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
18961 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
18962 !areExtDoubled(cast<Instruction>(Ext1)) ||
18963 !areExtDoubled(cast<Instruction>(Ext2)))
18964 return false;
18965
18966 return true;
18967}
18968
18969/// Check if sinking \p I's operands to I's basic block is profitable, because
18970/// the operands can be folded into a target instruction, e.g.
18971/// sext/zext can be folded into vsubl.
18972bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
18973 SmallVectorImpl<Use *> &Ops) const {
18974 if (!I->getType()->isVectorTy())
18975 return false;
18976
18977 if (Subtarget->hasNEON()) {
18978 switch (I->getOpcode()) {
18979 case Instruction::Sub:
18980 case Instruction::Add: {
18981 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
18982 return false;
18983 Ops.push_back(&I->getOperandUse(0));
18984 Ops.push_back(&I->getOperandUse(1));
18985 return true;
18986 }
18987 default:
18988 return false;
18989 }
18990 }
18991
18992 if (!Subtarget->hasMVEIntegerOps())
18993 return false;
18994
18995 auto IsFMSMul = [&](Instruction *I) {
18996 if (!I->hasOneUse())
18997 return false;
18998 auto *Sub = cast<Instruction>(*I->users().begin());
18999 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
19000 };
19001 auto IsFMS = [&](Instruction *I) {
19002 if (match(I->getOperand(0), m_FNeg(m_Value())) ||
19003 match(I->getOperand(1), m_FNeg(m_Value())))
19004 return true;
19005 return false;
19006 };
19007
19008 auto IsSinker = [&](Instruction *I, int Operand) {
19009 switch (I->getOpcode()) {
19010 case Instruction::Add:
19011 case Instruction::Mul:
19012 case Instruction::FAdd:
19013 case Instruction::ICmp:
19014 case Instruction::FCmp:
19015 return true;
19016 case Instruction::FMul:
19017 return !IsFMSMul(I);
19018 case Instruction::Sub:
19019 case Instruction::FSub:
19020 case Instruction::Shl:
19021 case Instruction::LShr:
19022 case Instruction::AShr:
19023 return Operand == 1;
19024 case Instruction::Call:
19025 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
19026 switch (II->getIntrinsicID()) {
19027 case Intrinsic::fma:
19028 return !IsFMS(I);
19029 case Intrinsic::sadd_sat:
19030 case Intrinsic::uadd_sat:
19031 case Intrinsic::arm_mve_add_predicated:
19032 case Intrinsic::arm_mve_mul_predicated:
19033 case Intrinsic::arm_mve_qadd_predicated:
19034 case Intrinsic::arm_mve_vhadd:
19035 case Intrinsic::arm_mve_hadd_predicated:
19036 case Intrinsic::arm_mve_vqdmull:
19037 case Intrinsic::arm_mve_vqdmull_predicated:
19038 case Intrinsic::arm_mve_vqdmulh:
19039 case Intrinsic::arm_mve_qdmulh_predicated:
19040 case Intrinsic::arm_mve_vqrdmulh:
19041 case Intrinsic::arm_mve_qrdmulh_predicated:
19042 case Intrinsic::arm_mve_fma_predicated:
19043 return true;
19044 case Intrinsic::ssub_sat:
19045 case Intrinsic::usub_sat:
19046 case Intrinsic::arm_mve_sub_predicated:
19047 case Intrinsic::arm_mve_qsub_predicated:
19048 case Intrinsic::arm_mve_hsub_predicated:
19049 case Intrinsic::arm_mve_vhsub:
19050 return Operand == 1;
19051 default:
19052 return false;
19053 }
19054 }
19055 return false;
19056 default:
19057 return false;
19058 }
19059 };
19060
19061 for (auto OpIdx : enumerate(I->operands())) {
19062 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
19063 // Make sure we are not already sinking this operand
19064 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
19065 continue;
19066
19067 Instruction *Shuffle = Op;
19068 if (Shuffle->getOpcode() == Instruction::BitCast)
19069 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
19070 // We are looking for a splat that can be sunk.
19071 if (!Shuffle ||
19072 !match(Shuffle, m_Shuffle(
19073 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
19074 m_Undef(), m_ZeroMask())))
19075 continue;
19076 if (!IsSinker(I, OpIdx.index()))
19077 continue;
19078
19079 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
19080 // and vector registers
19081 for (Use &U : Op->uses()) {
19082 Instruction *Insn = cast<Instruction>(U.getUser());
19083 if (!IsSinker(Insn, U.getOperandNo()))
19084 return false;
19085 }
19086
19087 Ops.push_back(&Shuffle->getOperandUse(0));
19088 if (Shuffle != Op)
19089 Ops.push_back(&Op->getOperandUse(0));
19090 Ops.push_back(&OpIdx.value());
19091 }
19092 return true;
19093}
19094
19095Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
19096 if (!Subtarget->hasMVEIntegerOps())
19097 return nullptr;
19098 Type *SVIType = SVI->getType();
19099 Type *ScalarType = SVIType->getScalarType();
19100
19101 if (ScalarType->isFloatTy())
19102 return Type::getInt32Ty(SVIType->getContext());
19103 if (ScalarType->isHalfTy())
19104 return Type::getInt16Ty(SVIType->getContext());
19105 return nullptr;
19106}
19107
19108bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
19109 EVT VT = ExtVal.getValueType();
19110
19111 if (!isTypeLegal(VT))
19112 return false;
19113
19114 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
19115 if (Ld->isExpandingLoad())
19116 return false;
19117 }
19118
19119 if (Subtarget->hasMVEIntegerOps())
19120 return true;
19121
19122 // Don't create a loadext if we can fold the extension into a wide/long
19123 // instruction.
19124 // If there's more than one user instruction, the loadext is desirable no
19125 // matter what. There can be two uses by the same instruction.
19126 if (ExtVal->use_empty() ||
19127 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
19128 return true;
19129
19130 SDNode *U = *ExtVal->use_begin();
19131 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19132 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19133 return false;
19134
19135 return true;
19136}
19137
19138bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19139 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19140 return false;
19141
19142 if (!isTypeLegal(EVT::getEVT(Ty1)))
19143 return false;
19144
19145 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop")(static_cast <bool> (Ty1->getPrimitiveSizeInBits() <=
64 && "i128 is probably not a noop") ? void (0) : __assert_fail
("Ty1->getPrimitiveSizeInBits() <= 64 && \"i128 is probably not a noop\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 19145, __extension__
__PRETTY_FUNCTION__))
;
19146
19147 // Assuming the caller doesn't have a zeroext or signext return parameter,
19148 // truncation all the way down to i1 is valid.
19149 return true;
19150}
19151
19152/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19153/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19154/// expanded to FMAs when this method returns true, otherwise fmuladd is
19155/// expanded to fmul + fadd.
19156///
19157/// ARM supports both fused and unfused multiply-add operations; we already
19158/// lower a pair of fmul and fadd to the latter so it's not clear that there
19159/// would be a gain or that the gain would be worthwhile enough to risk
19160/// correctness bugs.
19161///
19162/// For MVE, we set this to true as it helps simplify the need for some
19163/// patterns (and we don't have the non-fused floating point instruction).
19164bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19165 EVT VT) const {
19166 if (!VT.isSimple())
19167 return false;
19168
19169 switch (VT.getSimpleVT().SimpleTy) {
19170 case MVT::v4f32:
19171 case MVT::v8f16:
19172 return Subtarget->hasMVEFloatOps();
19173 case MVT::f16:
19174 return Subtarget->useFPVFMx16();
19175 case MVT::f32:
19176 return Subtarget->useFPVFMx();
19177 case MVT::f64:
19178 return Subtarget->useFPVFMx64();
19179 default:
19180 break;
19181 }
19182
19183 return false;
19184}
19185
19186static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19187 if (V < 0)
19188 return false;
19189
19190 unsigned Scale = 1;
19191 switch (VT.getSimpleVT().SimpleTy) {
19192 case MVT::i1:
19193 case MVT::i8:
19194 // Scale == 1;
19195 break;
19196 case MVT::i16:
19197 // Scale == 2;
19198 Scale = 2;
19199 break;
19200 default:
19201 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19202 // Scale == 4;
19203 Scale = 4;
19204 break;
19205 }
19206
19207 if ((V & (Scale - 1)) != 0)
19208 return false;
19209 return isUInt<5>(V / Scale);
19210}
19211
19212static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19213 const ARMSubtarget *Subtarget) {
19214 if (!VT.isInteger() && !VT.isFloatingPoint())
19215 return false;
19216 if (VT.isVector() && Subtarget->hasNEON())
19217 return false;
19218 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19219 !Subtarget->hasMVEFloatOps())
19220 return false;
19221
19222 bool IsNeg = false;
19223 if (V < 0) {
19224 IsNeg = true;
19225 V = -V;
19226 }
19227
19228 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
19229
19230 // MVE: size * imm7
19231 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
19232 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
19233 case MVT::i32:
19234 case MVT::f32:
19235 return isShiftedUInt<7,2>(V);
19236 case MVT::i16:
19237 case MVT::f16:
19238 return isShiftedUInt<7,1>(V);
19239 case MVT::i8:
19240 return isUInt<7>(V);
19241 default:
19242 return false;
19243 }
19244 }
19245
19246 // half VLDR: 2 * imm8
19247 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
19248 return isShiftedUInt<8, 1>(V);
19249 // VLDR and LDRD: 4 * imm8
19250 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
19251 return isShiftedUInt<8, 2>(V);
19252
19253 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
19254 // + imm12 or - imm8
19255 if (IsNeg)
19256 return isUInt<8>(V);
19257 return isUInt<12>(V);
19258 }
19259
19260 return false;
19261}
19262
19263/// isLegalAddressImmediate - Return true if the integer value can be used
19264/// as the offset of the target addressing mode for load / store of the
19265/// given type.
19266static bool isLegalAddressImmediate(int64_t V, EVT VT,
19267 const ARMSubtarget *Subtarget) {
19268 if (V == 0)
19269 return true;
19270
19271 if (!VT.isSimple())
19272 return false;
19273
19274 if (Subtarget->isThumb1Only())
19275 return isLegalT1AddressImmediate(V, VT);
19276 else if (Subtarget->isThumb2())
19277 return isLegalT2AddressImmediate(V, VT, Subtarget);
19278
19279 // ARM mode.
19280 if (V < 0)
19281 V = - V;
19282 switch (VT.getSimpleVT().SimpleTy) {
19283 default: return false;
19284 case MVT::i1:
19285 case MVT::i8:
19286 case MVT::i32:
19287 // +- imm12
19288 return isUInt<12>(V);
19289 case MVT::i16:
19290 // +- imm8
19291 return isUInt<8>(V);
19292 case MVT::f32:
19293 case MVT::f64:
19294 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
19295 return false;
19296 return isShiftedUInt<8, 2>(V);
19297 }
19298}
19299
19300bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
19301 EVT VT) const {
19302 int Scale = AM.Scale;
19303 if (Scale < 0)
19304 return false;
19305
19306 switch (VT.getSimpleVT().SimpleTy) {
19307 default: return false;
19308 case MVT::i1:
19309 case MVT::i8:
19310 case MVT::i16:
19311 case MVT::i32:
19312 if (Scale == 1)
19313 return true;
19314 // r + r << imm
19315 Scale = Scale & ~1;
19316 return Scale == 2 || Scale == 4 || Scale == 8;
19317 case MVT::i64:
19318 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
19319 // version in Thumb mode.
19320 // r + r
19321 if (Scale == 1)
19322 return true;
19323 // r * 2 (this can be lowered to r + r).
19324 if (!AM.HasBaseReg && Scale == 2)
19325 return true;
19326 return false;
19327 case MVT::isVoid:
19328 // Note, we allow "void" uses (basically, uses that aren't loads or
19329 // stores), because arm allows folding a scale into many arithmetic
19330 // operations. This should be made more precise and revisited later.
19331
19332 // Allow r << imm, but the imm has to be a multiple of two.
19333 if (Scale & 1) return false;
19334 return isPowerOf2_32(Scale);
19335 }
19336}
19337
19338bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
19339 EVT VT) const {
19340 const int Scale = AM.Scale;
19341
19342 // Negative scales are not supported in Thumb1.
19343 if (Scale < 0)
19344 return false;
19345
19346 // Thumb1 addressing modes do not support register scaling excepting the
19347 // following cases:
19348 // 1. Scale == 1 means no scaling.
19349 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
19350 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
19351}
19352
19353/// isLegalAddressingMode - Return true if the addressing mode represented
19354/// by AM is legal for this target, for a load/store of the specified type.
19355bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
19356 const AddrMode &AM, Type *Ty,
19357 unsigned AS, Instruction *I) const {
19358 EVT VT = getValueType(DL, Ty, true);
19359 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
19360 return false;
19361
19362 // Can never fold addr of global into load/store.
19363 if (AM.BaseGV)
19364 return false;
19365
19366 switch (AM.Scale) {
19367 case 0: // no scale reg, must be "r+i" or "r", or "i".
19368 break;
19369 default:
19370 // ARM doesn't support any R+R*scale+imm addr modes.
19371 if (AM.BaseOffs)
19372 return false;
19373
19374 if (!VT.isSimple())
19375 return false;
19376
19377 if (Subtarget->isThumb1Only())
19378 return isLegalT1ScaledAddressingMode(AM, VT);
19379
19380 if (Subtarget->isThumb2())
19381 return isLegalT2ScaledAddressingMode(AM, VT);
19382
19383 int Scale = AM.Scale;
19384 switch (VT.getSimpleVT().SimpleTy) {
19385 default: return false;
19386 case MVT::i1:
19387 case MVT::i8:
19388 case MVT::i32:
19389 if (Scale < 0) Scale = -Scale;
19390 if (Scale == 1)
19391 return true;
19392 // r + r << imm
19393 return isPowerOf2_32(Scale & ~1);
19394 case MVT::i16:
19395 case MVT::i64:
19396 // r +/- r
19397 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
19398 return true;
19399 // r * 2 (this can be lowered to r + r).
19400 if (!AM.HasBaseReg && Scale == 2)
19401 return true;
19402 return false;
19403
19404 case MVT::isVoid:
19405 // Note, we allow "void" uses (basically, uses that aren't loads or
19406 // stores), because arm allows folding a scale into many arithmetic
19407 // operations. This should be made more precise and revisited later.
19408
19409 // Allow r << imm, but the imm has to be a multiple of two.
19410 if (Scale & 1) return false;
19411 return isPowerOf2_32(Scale);
19412 }
19413 }
19414 return true;
19415}
19416
19417/// isLegalICmpImmediate - Return true if the specified immediate is legal
19418/// icmp immediate, that is the target has icmp instructions which can compare
19419/// a register against the immediate without having to materialize the
19420/// immediate into a register.
19421bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19422 // Thumb2 and ARM modes can use cmn for negative immediates.
19423 if (!Subtarget->isThumb())
19424 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
19425 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
19426 if (Subtarget->isThumb2())
19427 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
19428 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
19429 // Thumb1 doesn't have cmn, and only 8-bit immediates.
19430 return Imm >= 0 && Imm <= 255;
19431}
19432
19433/// isLegalAddImmediate - Return true if the specified immediate is a legal add
19434/// *or sub* immediate, that is the target has add or sub instructions which can
19435/// add a register with the immediate without having to materialize the
19436/// immediate into a register.
19437bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
19438 // Same encoding for add/sub, just flip the sign.
19439 int64_t AbsImm = std::abs(Imm);
19440 if (!Subtarget->isThumb())
19441 return ARM_AM::getSOImmVal(AbsImm) != -1;
19442 if (Subtarget->isThumb2())
19443 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
19444 // Thumb1 only has 8-bit unsigned immediate.
19445 return AbsImm >= 0 && AbsImm <= 255;
19446}
19447
19448// Return false to prevent folding
19449// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
19450// if the folding leads to worse code.
19451bool ARMTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
19452 SDValue ConstNode) const {
19453 // Let the DAGCombiner decide for vector types and large types.
19454 const EVT VT = AddNode.getValueType();
19455 if (VT.isVector() || VT.getScalarSizeInBits() > 32)
19456 return true;
19457
19458 // It is worse if c0 is legal add immediate, while c1*c0 is not
19459 // and has to be composed by at least two instructions.
19460 const ConstantSDNode *C0Node = cast<ConstantSDNode>(AddNode.getOperand(1));
19461 const ConstantSDNode *C1Node = cast<ConstantSDNode>(ConstNode);
19462 const int64_t C0 = C0Node->getSExtValue();
19463 APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
19464 if (!isLegalAddImmediate(C0) || isLegalAddImmediate(CA.getSExtValue()))
19465 return true;
19466 if (ConstantMaterializationCost((unsigned)CA.getZExtValue(), Subtarget) > 1)
19467 return false;
19468
19469 // Default to true and let the DAGCombiner decide.
19470 return true;
19471}
19472
19473static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
19474 bool isSEXTLoad, SDValue &Base,
19475 SDValue &Offset, bool &isInc,
19476 SelectionDAG &DAG) {
19477 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19478 return false;
19479
19480 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
19481 // AddressingMode 3
19482 Base = Ptr->getOperand(0);
19483 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19484 int RHSC = (int)RHS->getZExtValue();
19485 if (RHSC < 0 && RHSC > -256) {
19486 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"llvm/lib/Target/ARM/ARMISelLowering.cpp", 19486, __extension__
__PRETTY_FUNCTION__))
;
19487 isInc = false;
19488 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19489 return true;
19490 }
19491 }
19492 isInc = (Ptr->getOpcode() == ISD::ADD);
19493 Offset = Ptr->getOperand(1);
19494 return true;
19495 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
19496 // AddressingMode 2
19497 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19498 int RHSC = (int)RHS->getZExtValue();
19499 if (RHSC < 0 && RHSC > -0x1000) {
19500 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"llvm/lib/Target/ARM/ARMISelLowering.cpp", 19500, __extension__
__PRETTY_FUNCTION__))
;
19501 isInc = false;
19502 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19503 Base = Ptr->getOperand(0);
19504 return true;
19505 }
19506 }
19507
19508 if (Ptr->getOpcode() == ISD::ADD) {
19509 isInc = true;
19510 ARM_AM::ShiftOpc ShOpcVal=
19511 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
19512 if (ShOpcVal != ARM_AM::no_shift) {
19513 Base = Ptr->getOperand(1);
19514 Offset = Ptr->getOperand(0);
19515 } else {
19516 Base = Ptr->getOperand(0);
19517 Offset = Ptr->getOperand(1);
19518 }
19519 return true;
19520 }
19521
19522 isInc = (Ptr->getOpcode() == ISD::ADD);
19523 Base = Ptr->getOperand(0);
19524 Offset = Ptr->getOperand(1);
19525 return true;
19526 }
19527
19528 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
19529 return false;
19530}
19531
19532static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
19533 bool isSEXTLoad, SDValue &Base,
19534 SDValue &Offset, bool &isInc,
19535 SelectionDAG &DAG) {
19536 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19537 return false;
19538
19539 Base = Ptr->getOperand(0);
19540 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19541 int RHSC = (int)RHS->getZExtValue();
19542 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
19543 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"llvm/lib/Target/ARM/ARMISelLowering.cpp", 19543, __extension__
__PRETTY_FUNCTION__))
;
19544 isInc = false;
19545 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19546 return true;
19547 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
19548 isInc = Ptr->getOpcode() == ISD::ADD;
19549 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19550 return true;
19551 }
19552 }
19553
19554 return false;
19555}
19556
19557static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
19558 bool isSEXTLoad, bool IsMasked, bool isLE,
19559 SDValue &Base, SDValue &Offset,
19560 bool &isInc, SelectionDAG &DAG) {
19561 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19562 return false;
19563 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
19564 return false;
19565
19566 // We allow LE non-masked loads to change the type (for example use a vldrb.8
19567 // as opposed to a vldrw.32). This can allow extra addressing modes or
19568 // alignments for what is otherwise an equivalent instruction.
19569 bool CanChangeType = isLE && !IsMasked;
19570
19571 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
19572 int RHSC = (int)RHS->getZExtValue();
19573
19574 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
19575 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
19576 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"llvm/lib/Target/ARM/ARMISelLowering.cpp", 19576, __extension__
__PRETTY_FUNCTION__))
;
19577 isInc = false;
19578 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19579 return true;
19580 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
19581 isInc = Ptr->getOpcode() == ISD::ADD;
19582 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19583 return true;
19584 }
19585 return false;
19586 };
19587
19588 // Try to find a matching instruction based on s/zext, Alignment, Offset and
19589 // (in BE/masked) type.
19590 Base = Ptr->getOperand(0);
19591 if (VT == MVT::v4i16) {
19592 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
19593 return true;
19594 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
19595 if (IsInRange(RHSC, 0x80, 1))
19596 return true;
19597 } else if (Alignment >= 4 &&
19598 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
19599 IsInRange(RHSC, 0x80, 4))
19600 return true;
19601 else if (Alignment >= 2 &&
19602 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
19603 IsInRange(RHSC, 0x80, 2))
19604 return true;
19605 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
19606 return true;
19607 return false;
19608}
19609
19610/// getPreIndexedAddressParts - returns true by value, base pointer and
19611/// offset pointer and addressing mode by reference if the node's address
19612/// can be legally represented as pre-indexed load / store address.
19613bool
19614ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
19615 SDValue &Offset,
19616 ISD::MemIndexedMode &AM,
19617 SelectionDAG &DAG) const {
19618 if (Subtarget->isThumb1Only())
19619 return false;
19620
19621 EVT VT;
19622 SDValue Ptr;
19623 Align Alignment;
19624 bool isSEXTLoad = false;
19625 bool IsMasked = false;
19626 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19627 Ptr = LD->getBasePtr();
19628 VT = LD->getMemoryVT();
19629 Alignment = LD->getAlign();
19630 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19631 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19632 Ptr = ST->getBasePtr();
19633 VT = ST->getMemoryVT();
19634 Alignment = ST->getAlign();
19635 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19636 Ptr = LD->getBasePtr();
19637 VT = LD->getMemoryVT();
19638 Alignment = LD->getAlign();
19639 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19640 IsMasked = true;
19641 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19642 Ptr = ST->getBasePtr();
19643 VT = ST->getMemoryVT();
19644 Alignment = ST->getAlign();
19645 IsMasked = true;
19646 } else
19647 return false;
19648
19649 bool isInc;
19650 bool isLegal = false;
19651 if (VT.isVector())
19652 isLegal = Subtarget->hasMVEIntegerOps() &&
19653 getMVEIndexedAddressParts(
19654 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
19655 Subtarget->isLittle(), Base, Offset, isInc, DAG);
19656 else {
19657 if (Subtarget->isThumb2())
19658 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19659 Offset, isInc, DAG);
19660 else
19661 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19662 Offset, isInc, DAG);
19663 }
19664 if (!isLegal)
19665 return false;
19666
19667 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
19668 return true;
19669}
19670
19671/// getPostIndexedAddressParts - returns true by value, base pointer and
19672/// offset pointer and addressing mode by reference if this node can be
19673/// combined with a load / store to form a post-indexed load / store.
19674bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
19675 SDValue &Base,
19676 SDValue &Offset,
19677 ISD::MemIndexedMode &AM,
19678 SelectionDAG &DAG) const {
19679 EVT VT;
19680 SDValue Ptr;
19681 Align Alignment;
19682 bool isSEXTLoad = false, isNonExt;
19683 bool IsMasked = false;
19684 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19685 VT = LD->getMemoryVT();
19686 Ptr = LD->getBasePtr();
19687 Alignment = LD->getAlign();
19688 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19689 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19690 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19691 VT = ST->getMemoryVT();
19692 Ptr = ST->getBasePtr();
19693 Alignment = ST->getAlign();
19694 isNonExt = !ST->isTruncatingStore();
19695 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19696 VT = LD->getMemoryVT();
19697 Ptr = LD->getBasePtr();
19698 Alignment = LD->getAlign();
19699 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19700 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19701 IsMasked = true;
19702 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19703 VT = ST->getMemoryVT();
19704 Ptr = ST->getBasePtr();
19705 Alignment = ST->getAlign();
19706 isNonExt = !ST->isTruncatingStore();
19707 IsMasked = true;
19708 } else
19709 return false;
19710
19711 if (Subtarget->isThumb1Only()) {
19712 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
19713 // must be non-extending/truncating, i32, with an offset of 4.
19714 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!")(static_cast <bool> (Op->getValueType(0) == MVT::i32
&& "Non-i32 post-inc op?!") ? void (0) : __assert_fail
("Op->getValueType(0) == MVT::i32 && \"Non-i32 post-inc op?!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 19714, __extension__
__PRETTY_FUNCTION__))
;
19715 if (Op->getOpcode() != ISD::ADD || !isNonExt)
19716 return false;
19717 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
19718 if (!RHS || RHS->getZExtValue() != 4)
19719 return false;
19720 if (Alignment < Align(4))
19721 return false;
19722
19723 Offset = Op->getOperand(1);
19724 Base = Op->getOperand(0);
19725 AM = ISD::POST_INC;
19726 return true;
19727 }
19728
19729 bool isInc;
19730 bool isLegal = false;
19731 if (VT.isVector())
19732 isLegal = Subtarget->hasMVEIntegerOps() &&
19733 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
19734 Subtarget->isLittle(), Base, Offset,
19735 isInc, DAG);
19736 else {
19737 if (Subtarget->isThumb2())
19738 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19739 isInc, DAG);
19740 else
19741 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19742 isInc, DAG);
19743 }
19744 if (!isLegal)
19745 return false;
19746
19747 if (Ptr != Base) {
19748 // Swap base ptr and offset to catch more post-index load / store when
19749 // it's legal. In Thumb2 mode, offset must be an immediate.
19750 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
19751 !Subtarget->isThumb2())
19752 std::swap(Base, Offset);
19753
19754 // Post-indexed load / store update the base pointer.
19755 if (Ptr != Base)
19756 return false;
19757 }
19758
19759 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
19760 return true;
19761}
19762
19763void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19764 KnownBits &Known,
19765 const APInt &DemandedElts,
19766 const SelectionDAG &DAG,
19767 unsigned Depth) const {
19768 unsigned BitWidth = Known.getBitWidth();
19769 Known.resetAll();
19770 switch (Op.getOpcode()) {
19771 default: break;
19772 case ARMISD::ADDC:
19773 case ARMISD::ADDE:
19774 case ARMISD::SUBC:
19775 case ARMISD::SUBE:
19776 // Special cases when we convert a carry to a boolean.
19777 if (Op.getResNo() == 0) {
19778 SDValue LHS = Op.getOperand(0);
19779 SDValue RHS = Op.getOperand(1);
19780 // (ADDE 0, 0, C) will give us a single bit.
19781 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
19782 isNullConstant(RHS)) {
19783 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19784 return;
19785 }
19786 }
19787 break;
19788 case ARMISD::CMOV: {
19789 // Bits are known zero/one if known on the LHS and RHS.
19790 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
19791 if (Known.isUnknown())
19792 return;
19793
19794 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
19795 Known = KnownBits::commonBits(Known, KnownRHS);
19796 return;
19797 }
19798 case ISD::INTRINSIC_W_CHAIN: {
19799 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
19800 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
19801 switch (IntID) {
19802 default: return;
19803 case Intrinsic::arm_ldaex:
19804 case Intrinsic::arm_ldrex: {
19805 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
19806 unsigned MemBits = VT.getScalarSizeInBits();
19807 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
19808 return;
19809 }
19810 }
19811 }
19812 case ARMISD::BFI: {
19813 // Conservatively, we can recurse down the first operand
19814 // and just mask out all affected bits.
19815 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
19816
19817 // The operand to BFI is already a mask suitable for removing the bits it
19818 // sets.
19819 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
19820 const APInt &Mask = CI->getAPIntValue();
19821 Known.Zero &= Mask;
19822 Known.One &= Mask;
19823 return;
19824 }
19825 case ARMISD::VGETLANEs:
19826 case ARMISD::VGETLANEu: {
19827 const SDValue &SrcSV = Op.getOperand(0);
19828 EVT VecVT = SrcSV.getValueType();
19829 assert(VecVT.isVector() && "VGETLANE expected a vector type")(static_cast <bool> (VecVT.isVector() && "VGETLANE expected a vector type"
) ? void (0) : __assert_fail ("VecVT.isVector() && \"VGETLANE expected a vector type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 19829, __extension__
__PRETTY_FUNCTION__))
;
19830 const unsigned NumSrcElts = VecVT.getVectorNumElements();
19831 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
19832 assert(Pos->getAPIntValue().ult(NumSrcElts) &&(static_cast <bool> (Pos->getAPIntValue().ult(NumSrcElts
) && "VGETLANE index out of bounds") ? void (0) : __assert_fail
("Pos->getAPIntValue().ult(NumSrcElts) && \"VGETLANE index out of bounds\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 19833, __extension__
__PRETTY_FUNCTION__))
19833 "VGETLANE index out of bounds")(static_cast <bool> (Pos->getAPIntValue().ult(NumSrcElts
) && "VGETLANE index out of bounds") ? void (0) : __assert_fail
("Pos->getAPIntValue().ult(NumSrcElts) && \"VGETLANE index out of bounds\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 19833, __extension__
__PRETTY_FUNCTION__))
;
19834 unsigned Idx = Pos->getZExtValue();
19835 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
19836 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
19837
19838 EVT VT = Op.getValueType();
19839 const unsigned DstSz = VT.getScalarSizeInBits();
19840 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
19841 (void)SrcSz;
19842 assert(SrcSz == Known.getBitWidth())(static_cast <bool> (SrcSz == Known.getBitWidth()) ? void
(0) : __assert_fail ("SrcSz == Known.getBitWidth()", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19842, __extension__ __PRETTY_FUNCTION__))
;
19843 assert(DstSz > SrcSz)(static_cast <bool> (DstSz > SrcSz) ? void (0) : __assert_fail
("DstSz > SrcSz", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19843, __extension__ __PRETTY_FUNCTION__))
;
19844 if (Op.getOpcode() == ARMISD::VGETLANEs)
19845 Known = Known.sext(DstSz);
19846 else {
19847 Known = Known.zext(DstSz);
19848 }
19849 assert(DstSz == Known.getBitWidth())(static_cast <bool> (DstSz == Known.getBitWidth()) ? void
(0) : __assert_fail ("DstSz == Known.getBitWidth()", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19849, __extension__ __PRETTY_FUNCTION__))
;
19850 break;
19851 }
19852 case ARMISD::VMOVrh: {
19853 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
19854 assert(KnownOp.getBitWidth() == 16)(static_cast <bool> (KnownOp.getBitWidth() == 16) ? void
(0) : __assert_fail ("KnownOp.getBitWidth() == 16", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19854, __extension__ __PRETTY_FUNCTION__))
;
19855 Known = KnownOp.zext(32);
19856 break;
19857 }
19858 case ARMISD::CSINC:
19859 case ARMISD::CSINV:
19860 case ARMISD::CSNEG: {
19861 KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
19862 KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
19863
19864 // The result is either:
19865 // CSINC: KnownOp0 or KnownOp1 + 1
19866 // CSINV: KnownOp0 or ~KnownOp1
19867 // CSNEG: KnownOp0 or KnownOp1 * -1
19868 if (Op.getOpcode() == ARMISD::CSINC)
19869 KnownOp1 = KnownBits::computeForAddSub(
19870 true, false, KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
19871 else if (Op.getOpcode() == ARMISD::CSINV)
19872 std::swap(KnownOp1.Zero, KnownOp1.One);
19873 else if (Op.getOpcode() == ARMISD::CSNEG)
19874 KnownOp1 = KnownBits::mul(
19875 KnownOp1, KnownBits::makeConstant(APInt(32, -1)));
19876
19877 Known = KnownBits::commonBits(KnownOp0, KnownOp1);
19878 break;
19879 }
19880 }
19881}
19882
19883bool ARMTargetLowering::targetShrinkDemandedConstant(
19884 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
19885 TargetLoweringOpt &TLO) const {
19886 // Delay optimization, so we don't have to deal with illegal types, or block
19887 // optimizations.
19888 if (!TLO.LegalOps)
19889 return false;
19890
19891 // Only optimize AND for now.
19892 if (Op.getOpcode() != ISD::AND)
19893 return false;
19894
19895 EVT VT = Op.getValueType();
19896
19897 // Ignore vectors.
19898 if (VT.isVector())
19899 return false;
19900
19901 assert(VT == MVT::i32 && "Unexpected integer type")(static_cast <bool> (VT == MVT::i32 && "Unexpected integer type"
) ? void (0) : __assert_fail ("VT == MVT::i32 && \"Unexpected integer type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 19901, __extension__
__PRETTY_FUNCTION__))
;
19902
19903 // Make sure the RHS really is a constant.
19904 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
19905 if (!C)
19906 return false;
19907
19908 unsigned Mask = C->getZExtValue();
19909
19910 unsigned Demanded = DemandedBits.getZExtValue();
19911 unsigned ShrunkMask = Mask & Demanded;
19912 unsigned ExpandedMask = Mask | ~Demanded;
19913
19914 // If the mask is all zeros, let the target-independent code replace the
19915 // result with zero.
19916 if (ShrunkMask == 0)
19917 return false;
19918
19919 // If the mask is all ones, erase the AND. (Currently, the target-independent
19920 // code won't do this, so we have to do it explicitly to avoid an infinite
19921 // loop in obscure cases.)
19922 if (ExpandedMask == ~0U)
19923 return TLO.CombineTo(Op, Op.getOperand(0));
19924
19925 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
19926 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
19927 };
19928 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
19929 if (NewMask == Mask)
19930 return true;
19931 SDLoc DL(Op);
19932 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
19933 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
19934 return TLO.CombineTo(Op, NewOp);
19935 };
19936
19937 // Prefer uxtb mask.
19938 if (IsLegalMask(0xFF))
19939 return UseMask(0xFF);
19940
19941 // Prefer uxth mask.
19942 if (IsLegalMask(0xFFFF))
19943 return UseMask(0xFFFF);
19944
19945 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
19946 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
19947 if (ShrunkMask < 256)
19948 return UseMask(ShrunkMask);
19949
19950 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
19951 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
19952 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
19953 return UseMask(ExpandedMask);
19954
19955 // Potential improvements:
19956 //
19957 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
19958 // We could try to prefer Thumb1 immediates which can be lowered to a
19959 // two-instruction sequence.
19960 // We could try to recognize more legal ARM/Thumb2 immediates here.
19961
19962 return false;
19963}
19964
19965bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
19966 SDValue Op, const APInt &OriginalDemandedBits,
19967 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
19968 unsigned Depth) const {
19969 unsigned Opc = Op.getOpcode();
19970
19971 switch (Opc) {
19972 case ARMISD::ASRL:
19973 case ARMISD::LSRL: {
19974 // If this is result 0 and the other result is unused, see if the demand
19975 // bits allow us to shrink this long shift into a standard small shift in
19976 // the opposite direction.
19977 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
19978 isa<ConstantSDNode>(Op->getOperand(2))) {
19979 unsigned ShAmt = Op->getConstantOperandVal(2);
19980 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(APInt::getAllOnes(32)
19981 << (32 - ShAmt)))
19982 return TLO.CombineTo(
19983 Op, TLO.DAG.getNode(
19984 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
19985 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
19986 }
19987 break;
19988 }
19989 case ARMISD::VBICIMM: {
19990 SDValue Op0 = Op.getOperand(0);
19991 unsigned ModImm = Op.getConstantOperandVal(1);
19992 unsigned EltBits = 0;
19993 uint64_t Mask = ARM_AM::decodeVMOVModImm(ModImm, EltBits);
19994 if ((OriginalDemandedBits & Mask) == 0)
19995 return TLO.CombineTo(Op, Op0);
19996 }
19997 }
19998
19999 return TargetLowering::SimplifyDemandedBitsForTargetNode(
20000 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
20001}
20002
20003//===----------------------------------------------------------------------===//
20004// ARM Inline Assembly Support
20005//===----------------------------------------------------------------------===//
20006
20007bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
20008 // Looking for "rev" which is V6+.
20009 if (!Subtarget->hasV6Ops())
20010 return false;
20011
20012 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
20013 std::string AsmStr = IA->getAsmString();
20014 SmallVector<StringRef, 4> AsmPieces;
20015 SplitString(AsmStr, AsmPieces, ";\n");
20016
20017 switch (AsmPieces.size()) {
20018 default: return false;
20019 case 1:
20020 AsmStr = std::string(AsmPieces[0]);
20021 AsmPieces.clear();
20022 SplitString(AsmStr, AsmPieces, " \t,");
20023
20024 // rev $0, $1
20025 if (AsmPieces.size() == 3 &&
20026 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
20027 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
20028 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20029 if (Ty && Ty->getBitWidth() == 32)
20030 return IntrinsicLowering::LowerToByteSwap(CI);
20031 }
20032 break;
20033 }
20034
20035 return false;
20036}
20037
20038const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
20039 // At this point, we have to lower this constraint to something else, so we
20040 // lower it to an "r" or "w". However, by doing this we will force the result
20041 // to be in register, while the X constraint is much more permissive.
20042 //
20043 // Although we are correct (we are free to emit anything, without
20044 // constraints), we might break use cases that would expect us to be more
20045 // efficient and emit something else.
20046 if (!Subtarget->hasVFP2Base())
20047 return "r";
20048 if (ConstraintVT.isFloatingPoint())
20049 return "w";
20050 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
20051 (ConstraintVT.getSizeInBits() == 64 ||
20052 ConstraintVT.getSizeInBits() == 128))
20053 return "w";
20054
20055 return "r";
20056}
20057
20058/// getConstraintType - Given a constraint letter, return the type of
20059/// constraint it is for this target.
20060ARMTargetLowering::ConstraintType
20061ARMTargetLowering::getConstraintType(StringRef Constraint) const {
20062 unsigned S = Constraint.size();
20063 if (S == 1) {
20064 switch (Constraint[0]) {
20065 default: break;
20066 case 'l': return C_RegisterClass;
20067 case 'w': return C_RegisterClass;
20068 case 'h': return C_RegisterClass;
20069 case 'x': return C_RegisterClass;
20070 case 't': return C_RegisterClass;
20071 case 'j': return C_Immediate; // Constant for movw.
20072 // An address with a single base register. Due to the way we
20073 // currently handle addresses it is the same as an 'r' memory constraint.
20074 case 'Q': return C_Memory;
20075 }
20076 } else if (S == 2) {
20077 switch (Constraint[0]) {
20078 default: break;
20079 case 'T': return C_RegisterClass;
20080 // All 'U+' constraints are addresses.
20081 case 'U': return C_Memory;
20082 }
20083 }
20084 return TargetLowering::getConstraintType(Constraint);
20085}
20086
20087/// Examine constraint type and operand type and determine a weight value.
20088/// This object must already have been set up with the operand type
20089/// and the current alternative constraint selected.
20090TargetLowering::ConstraintWeight
20091ARMTargetLowering::getSingleConstraintMatchWeight(
20092 AsmOperandInfo &info, const char *constraint) const {
20093 ConstraintWeight weight = CW_Invalid;
20094 Value *CallOperandVal = info.CallOperandVal;
20095 // If we don't have a value, we can't do a match,
20096 // but allow it at the lowest weight.
20097 if (!CallOperandVal)
20098 return CW_Default;
20099 Type *type = CallOperandVal->getType();
20100 // Look at the constraint type.
20101 switch (*constraint) {
20102 default:
20103 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20104 break;
20105 case 'l':
20106 if (type->isIntegerTy()) {
20107 if (Subtarget->isThumb())
20108 weight = CW_SpecificReg;
20109 else
20110 weight = CW_Register;
20111 }
20112 break;
20113 case 'w':
20114 if (type->isFloatingPointTy())
20115 weight = CW_Register;
20116 break;
20117 }
20118 return weight;
20119}
20120
20121using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
20122
20123RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
20124 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
20125 switch (Constraint.size()) {
20126 case 1:
20127 // GCC ARM Constraint Letters
20128 switch (Constraint[0]) {
20129 case 'l': // Low regs or general regs.
20130 if (Subtarget->isThumb())
20131 return RCPair(0U, &ARM::tGPRRegClass);
20132 return RCPair(0U, &ARM::GPRRegClass);
20133 case 'h': // High regs or no regs.
20134 if (Subtarget->isThumb())
20135 return RCPair(0U, &ARM::hGPRRegClass);
20136 break;
20137 case 'r':
20138 if (Subtarget->isThumb1Only())
20139 return RCPair(0U, &ARM::tGPRRegClass);
20140 return RCPair(0U, &ARM::GPRRegClass);
20141 case 'w':
20142 if (VT == MVT::Other)
20143 break;
20144 if (VT == MVT::f32)
20145 return RCPair(0U, &ARM::SPRRegClass);
20146 if (VT.getSizeInBits() == 64)
20147 return RCPair(0U, &ARM::DPRRegClass);
20148 if (VT.getSizeInBits() == 128)
20149 return RCPair(0U, &ARM::QPRRegClass);
20150 break;
20151 case 'x':
20152 if (VT == MVT::Other)
20153 break;
20154 if (VT == MVT::f32)
20155 return RCPair(0U, &ARM::SPR_8RegClass);
20156 if (VT.getSizeInBits() == 64)
20157 return RCPair(0U, &ARM::DPR_8RegClass);
20158 if (VT.getSizeInBits() == 128)
20159 return RCPair(0U, &ARM::QPR_8RegClass);
20160 break;
20161 case 't':
20162 if (VT == MVT::Other)
20163 break;
20164 if (VT == MVT::f16 || VT == MVT::bf16)
20165 return RCPair(0U, &ARM::HPRRegClass);
20166 if (VT == MVT::f32 || VT == MVT::i32)
20167 return RCPair(0U, &ARM::SPRRegClass);
20168 if (VT.getSizeInBits() == 64)
20169 return RCPair(0U, &ARM::DPR_VFP2RegClass);
20170 if (VT.getSizeInBits() == 128)
20171 return RCPair(0U, &ARM::QPR_VFP2RegClass);
20172 break;
20173 }
20174 break;
20175
20176 case 2:
20177 if (Constraint[0] == 'T') {
20178 switch (Constraint[1]) {
20179 default:
20180 break;
20181 case 'e':
20182 return RCPair(0U, &ARM::tGPREvenRegClass);
20183 case 'o':
20184 return RCPair(0U, &ARM::tGPROddRegClass);
20185 }
20186 }
20187 break;
20188
20189 default:
20190 break;
20191 }
20192
20193 if (StringRef("{cc}").equals_insensitive(Constraint))
20194 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
20195
20196 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20197}
20198
20199/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20200/// vector. If it is invalid, don't add anything to Ops.
20201void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20202 std::string &Constraint,
20203 std::vector<SDValue>&Ops,
20204 SelectionDAG &DAG) const {
20205 SDValue Result;
20206
20207 // Currently only support length 1 constraints.
20208 if (Constraint.length() != 1) return;
20209
20210 char ConstraintLetter = Constraint[0];
20211 switch (ConstraintLetter) {
20212 default: break;
20213 case 'j':
20214 case 'I': case 'J': case 'K': case 'L':
20215 case 'M': case 'N': case 'O':
20216 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
20217 if (!C)
20218 return;
20219
20220 int64_t CVal64 = C->getSExtValue();
20221 int CVal = (int) CVal64;
20222 // None of these constraints allow values larger than 32 bits. Check
20223 // that the value fits in an int.
20224 if (CVal != CVal64)
20225 return;
20226
20227 switch (ConstraintLetter) {
20228 case 'j':
20229 // Constant suitable for movw, must be between 0 and
20230 // 65535.
20231 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
20232 if (CVal >= 0 && CVal <= 65535)
20233 break;
20234 return;
20235 case 'I':
20236 if (Subtarget->isThumb1Only()) {
20237 // This must be a constant between 0 and 255, for ADD
20238 // immediates.
20239 if (CVal >= 0 && CVal <= 255)
20240 break;
20241 } else if (Subtarget->isThumb2()) {
20242 // A constant that can be used as an immediate value in a
20243 // data-processing instruction.
20244 if (ARM_AM::getT2SOImmVal(CVal) != -1)
20245 break;
20246 } else {
20247 // A constant that can be used as an immediate value in a
20248 // data-processing instruction.
20249 if (ARM_AM::getSOImmVal(CVal) != -1)
20250 break;
20251 }
20252 return;
20253
20254 case 'J':
20255 if (Subtarget->isThumb1Only()) {
20256 // This must be a constant between -255 and -1, for negated ADD
20257 // immediates. This can be used in GCC with an "n" modifier that
20258 // prints the negated value, for use with SUB instructions. It is
20259 // not useful otherwise but is implemented for compatibility.
20260 if (CVal >= -255 && CVal <= -1)
20261 break;
20262 } else {
20263 // This must be a constant between -4095 and 4095. It is not clear
20264 // what this constraint is intended for. Implemented for
20265 // compatibility with GCC.
20266 if (CVal >= -4095 && CVal <= 4095)
20267 break;
20268 }
20269 return;
20270
20271 case 'K':
20272 if (Subtarget->isThumb1Only()) {
20273 // A 32-bit value where only one byte has a nonzero value. Exclude
20274 // zero to match GCC. This constraint is used by GCC internally for
20275 // constants that can be loaded with a move/shift combination.
20276 // It is not useful otherwise but is implemented for compatibility.
20277 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
20278 break;
20279 } else if (Subtarget->isThumb2()) {
20280 // A constant whose bitwise inverse can be used as an immediate
20281 // value in a data-processing instruction. This can be used in GCC
20282 // with a "B" modifier that prints the inverted value, for use with
20283 // BIC and MVN instructions. It is not useful otherwise but is
20284 // implemented for compatibility.
20285 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
20286 break;
20287 } else {
20288 // A constant whose bitwise inverse can be used as an immediate
20289 // value in a data-processing instruction. This can be used in GCC
20290 // with a "B" modifier that prints the inverted value, for use with
20291 // BIC and MVN instructions. It is not useful otherwise but is
20292 // implemented for compatibility.
20293 if (ARM_AM::getSOImmVal(~CVal) != -1)
20294 break;
20295 }
20296 return;
20297
20298 case 'L':
20299 if (Subtarget->isThumb1Only()) {
20300 // This must be a constant between -7 and 7,
20301 // for 3-operand ADD/SUB immediate instructions.
20302 if (CVal >= -7 && CVal < 7)
20303 break;
20304 } else if (Subtarget->isThumb2()) {
20305 // A constant whose negation can be used as an immediate value in a
20306 // data-processing instruction. This can be used in GCC with an "n"
20307 // modifier that prints the negated value, for use with SUB
20308 // instructions. It is not useful otherwise but is implemented for
20309 // compatibility.
20310 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
20311 break;
20312 } else {
20313 // A constant whose negation can be used as an immediate value in a
20314 // data-processing instruction. This can be used in GCC with an "n"
20315 // modifier that prints the negated value, for use with SUB
20316 // instructions. It is not useful otherwise but is implemented for
20317 // compatibility.
20318 if (ARM_AM::getSOImmVal(-CVal) != -1)
20319 break;
20320 }
20321 return;
20322
20323 case 'M':
20324 if (Subtarget->isThumb1Only()) {
20325 // This must be a multiple of 4 between 0 and 1020, for
20326 // ADD sp + immediate.
20327 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
20328 break;
20329 } else {
20330 // A power of two or a constant between 0 and 32. This is used in
20331 // GCC for the shift amount on shifted register operands, but it is
20332 // useful in general for any shift amounts.
20333 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
20334 break;
20335 }
20336 return;
20337
20338 case 'N':
20339 if (Subtarget->isThumb1Only()) {
20340 // This must be a constant between 0 and 31, for shift amounts.
20341 if (CVal >= 0 && CVal <= 31)
20342 break;
20343 }
20344 return;
20345
20346 case 'O':
20347 if (Subtarget->isThumb1Only()) {
20348 // This must be a multiple of 4 between -508 and 508, for
20349 // ADD/SUB sp = sp + immediate.
20350 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
20351 break;
20352 }
20353 return;
20354 }
20355 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
20356 break;
20357 }
20358
20359 if (Result.getNode()) {
20360 Ops.push_back(Result);
20361 return;
20362 }
20363 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20364}
20365
20366static RTLIB::Libcall getDivRemLibcall(
20367 const SDNode *N, MVT::SimpleValueType SVT) {
20368 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemLibcall"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemLibcall\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20370, __extension__
__PRETTY_FUNCTION__))
20369 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemLibcall"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemLibcall\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20370, __extension__
__PRETTY_FUNCTION__))
20370 "Unhandled Opcode in getDivRemLibcall")(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemLibcall"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemLibcall\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20370, __extension__
__PRETTY_FUNCTION__))
;
20371 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20372 N->getOpcode() == ISD::SREM;
20373 RTLIB::Libcall LC;
20374 switch (SVT) {
20375 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20375)
;
20376 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
20377 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
20378 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
20379 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
20380 }
20381 return LC;
20382}
20383
20384static TargetLowering::ArgListTy getDivRemArgList(
20385 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
20386 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemArgList"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemArgList\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20388, __extension__
__PRETTY_FUNCTION__))
20387 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemArgList"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemArgList\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20388, __extension__
__PRETTY_FUNCTION__))
20388 "Unhandled Opcode in getDivRemArgList")(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemArgList"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemArgList\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20388, __extension__
__PRETTY_FUNCTION__))
;
20389 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20390 N->getOpcode() == ISD::SREM;
20391 TargetLowering::ArgListTy Args;
20392 TargetLowering::ArgListEntry Entry;
20393 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
20394 EVT ArgVT = N->getOperand(i).getValueType();
20395 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
20396 Entry.Node = N->getOperand(i);
20397 Entry.Ty = ArgTy;
20398 Entry.IsSExt = isSigned;
20399 Entry.IsZExt = !isSigned;
20400 Args.push_back(Entry);
20401 }
20402 if (Subtarget->isTargetWindows() && Args.size() >= 2)
20403 std::swap(Args[0], Args[1]);
20404 return Args;
20405}
20406
20407SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
20408 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20411, __extension__
__PRETTY_FUNCTION__))
20409 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20411, __extension__
__PRETTY_FUNCTION__))
20410 Subtarget->isTargetWindows()) &&(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20411, __extension__
__PRETTY_FUNCTION__))
20411 "Register-based DivRem lowering only")(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20411, __extension__
__PRETTY_FUNCTION__))
;
20412 unsigned Opcode = Op->getOpcode();
20413 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&(static_cast <bool> ((Opcode == ISD::SDIVREM || Opcode ==
ISD::UDIVREM) && "Invalid opcode for Div/Rem lowering"
) ? void (0) : __assert_fail ("(Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && \"Invalid opcode for Div/Rem lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20414, __extension__
__PRETTY_FUNCTION__))
20414 "Invalid opcode for Div/Rem lowering")(static_cast <bool> ((Opcode == ISD::SDIVREM || Opcode ==
ISD::UDIVREM) && "Invalid opcode for Div/Rem lowering"
) ? void (0) : __assert_fail ("(Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && \"Invalid opcode for Div/Rem lowering\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20414, __extension__
__PRETTY_FUNCTION__))
;
20415 bool isSigned = (Opcode == ISD::SDIVREM);
20416 EVT VT = Op->getValueType(0);
20417 SDLoc dl(Op);
20418
20419 if (VT == MVT::i64 && isa<ConstantSDNode>(Op.getOperand(1))) {
20420 SmallVector<SDValue> Result;
20421 if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i32, DAG)) {
20422 SDValue Res0 =
20423 DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[0], Result[1]);
20424 SDValue Res1 =
20425 DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[2], Result[3]);
20426 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
20427 {Res0, Res1});
20428 }
20429 }
20430
20431 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
20432
20433 // If the target has hardware divide, use divide + multiply + subtract:
20434 // div = a / b
20435 // rem = a - b * div
20436 // return {div, rem}
20437 // This should be lowered into UDIV/SDIV + MLS later on.
20438 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
20439 : Subtarget->hasDivideInARMMode();
20440 if (hasDivide && Op->getValueType(0).isSimple() &&
20441 Op->getSimpleValueType(0) == MVT::i32) {
20442 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
20443 const SDValue Dividend = Op->getOperand(0);
20444 const SDValue Divisor = Op->getOperand(1);
20445 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
20446 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
20447 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
20448
20449 SDValue Values[2] = {Div, Rem};
20450 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
20451 }
20452
20453 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
20454 VT.getSimpleVT().SimpleTy);
20455 SDValue InChain = DAG.getEntryNode();
20456
20457 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
20458 DAG.getContext(),
20459 Subtarget);
20460
20461 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20462 getPointerTy(DAG.getDataLayout()));
20463
20464 Type *RetTy = StructType::get(Ty, Ty);
20465
20466 if (Subtarget->isTargetWindows())
20467 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
20468
20469 TargetLowering::CallLoweringInfo CLI(DAG);
20470 CLI.setDebugLoc(dl).setChain(InChain)
20471 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
20472 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
20473
20474 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
20475 return CallInfo.first;
20476}
20477
20478// Lowers REM using divmod helpers
20479// see RTABI section 4.2/4.3
20480SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
20481 EVT VT = N->getValueType(0);
20482
20483 if (VT == MVT::i64 && isa<ConstantSDNode>(N->getOperand(1))) {
20484 SmallVector<SDValue> Result;
20485 if (expandDIVREMByConstant(N, Result, MVT::i32, DAG))
20486 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), N->getValueType(0),
20487 Result[0], Result[1]);
20488 }
20489
20490 // Build return types (div and rem)
20491 std::vector<Type*> RetTyParams;
20492 Type *RetTyElement;
20493
20494 switch (VT.getSimpleVT().SimpleTy) {
20495 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20495)
;
20496 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
20497 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
20498 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
20499 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
20500 }
20501
20502 RetTyParams.push_back(RetTyElement);
20503 RetTyParams.push_back(RetTyElement);
20504 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
20505 Type *RetTy = StructType::get(*DAG.getContext(), ret);
20506
20507 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
20508 SimpleTy);
20509 SDValue InChain = DAG.getEntryNode();
20510 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
20511 Subtarget);
20512 bool isSigned = N->getOpcode() == ISD::SREM;
20513 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20514 getPointerTy(DAG.getDataLayout()));
20515
20516 if (Subtarget->isTargetWindows())
20517 InChain = WinDBZCheckDenominator(DAG, N, InChain);
20518
20519 // Lower call
20520 CallLoweringInfo CLI(DAG);
20521 CLI.setChain(InChain)
20522 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
20523 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
20524 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
20525
20526 // Return second (rem) result operand (first contains div)
20527 SDNode *ResNode = CallResult.first.getNode();
20528 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands")(static_cast <bool> (ResNode->getNumOperands() == 2 &&
"divmod should return two operands") ? void (0) : __assert_fail
("ResNode->getNumOperands() == 2 && \"divmod should return two operands\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20528, __extension__
__PRETTY_FUNCTION__))
;
20529 return ResNode->getOperand(1);
20530}
20531
20532SDValue
20533ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
20534 assert(Subtarget->isTargetWindows() && "unsupported target platform")(static_cast <bool> (Subtarget->isTargetWindows() &&
"unsupported target platform") ? void (0) : __assert_fail ("Subtarget->isTargetWindows() && \"unsupported target platform\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20534, __extension__
__PRETTY_FUNCTION__))
;
20535 SDLoc DL(Op);
20536
20537 // Get the inputs.
20538 SDValue Chain = Op.getOperand(0);
20539 SDValue Size = Op.getOperand(1);
20540
20541 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
20542 "no-stack-arg-probe")) {
20543 MaybeAlign Align =
20544 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
20545 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20546 Chain = SP.getValue(1);
20547 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
20548 if (Align)
20549 SP =
20550 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
20551 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
20552 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
20553 SDValue Ops[2] = { SP, Chain };
20554 return DAG.getMergeValues(Ops, DL);
20555 }
20556
20557 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
20558 DAG.getConstant(2, DL, MVT::i32));
20559
20560 SDValue Flag;
20561 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
20562 Flag = Chain.getValue(1);
20563
20564 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20565 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
20566
20567 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20568 Chain = NewSP.getValue(1);
20569
20570 SDValue Ops[2] = { NewSP, Chain };
20571 return DAG.getMergeValues(Ops, DL);
20572}
20573
20574SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20575 bool IsStrict = Op->isStrictFPOpcode();
20576 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20577 const unsigned DstSz = Op.getValueType().getSizeInBits();
20578 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
20579 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&(static_cast <bool> (DstSz > SrcSz && DstSz <=
64 && SrcSz >= 16 && "Unexpected type for custom-lowering FP_EXTEND"
) ? void (0) : __assert_fail ("DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && \"Unexpected type for custom-lowering FP_EXTEND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20580, __extension__
__PRETTY_FUNCTION__))
20580 "Unexpected type for custom-lowering FP_EXTEND")(static_cast <bool> (DstSz > SrcSz && DstSz <=
64 && SrcSz >= 16 && "Unexpected type for custom-lowering FP_EXTEND"
) ? void (0) : __assert_fail ("DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && \"Unexpected type for custom-lowering FP_EXTEND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20580, __extension__
__PRETTY_FUNCTION__))
;
20581
20582 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20583, __extension__
__PRETTY_FUNCTION__))
20583 "With both FP DP and 16, any FP conversion is legal!")(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20583, __extension__
__PRETTY_FUNCTION__))
;
20584
20585 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&(static_cast <bool> (!(DstSz == 32 && Subtarget
->hasFP16()) && "With FP16, 16 to 32 conversion is legal!"
) ? void (0) : __assert_fail ("!(DstSz == 32 && Subtarget->hasFP16()) && \"With FP16, 16 to 32 conversion is legal!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20586, __extension__
__PRETTY_FUNCTION__))
20586 "With FP16, 16 to 32 conversion is legal!")(static_cast <bool> (!(DstSz == 32 && Subtarget
->hasFP16()) && "With FP16, 16 to 32 conversion is legal!"
) ? void (0) : __assert_fail ("!(DstSz == 32 && Subtarget->hasFP16()) && \"With FP16, 16 to 32 conversion is legal!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20586, __extension__
__PRETTY_FUNCTION__))
;
20587
20588 // Converting from 32 -> 64 is valid if we have FP64.
20589 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
20590 // FIXME: Remove this when we have strict fp instruction selection patterns
20591 if (IsStrict) {
20592 SDLoc Loc(Op);
20593 SDValue Result = DAG.getNode(ISD::FP_EXTEND,
20594 Loc, Op.getValueType(), SrcVal);
20595 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
20596 }
20597 return Op;
20598 }
20599
20600 // Either we are converting from 16 -> 64, without FP16 and/or
20601 // FP.double-precision or without Armv8-fp. So we must do it in two
20602 // steps.
20603 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
20604 // without FP16. So we must do a function call.
20605 SDLoc Loc(Op);
20606 RTLIB::Libcall LC;
20607 MakeLibCallOptions CallOptions;
20608 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20609 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
20610 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
20611 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
20612 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
20613 if (Supported) {
20614 if (IsStrict) {
20615 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
20616 {DstVT, MVT::Other}, {Chain, SrcVal});
20617 Chain = SrcVal.getValue(1);
20618 } else {
20619 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
20620 }
20621 } else {
20622 LC = RTLIB::getFPEXT(SrcVT, DstVT);
20623 assert(LC != RTLIB::UNKNOWN_LIBCALL &&(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_EXTEND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_EXTEND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20624, __extension__
__PRETTY_FUNCTION__))
20624 "Unexpected type for custom-lowering FP_EXTEND")(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_EXTEND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_EXTEND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20624, __extension__
__PRETTY_FUNCTION__))
;
20625 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20626 Loc, Chain);
20627 }
20628 }
20629
20630 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
20631}
20632
20633SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
20634 bool IsStrict = Op->isStrictFPOpcode();
20635
20636 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20637 EVT SrcVT = SrcVal.getValueType();
20638 EVT DstVT = Op.getValueType();
20639 const unsigned DstSz = Op.getValueType().getSizeInBits();
20640 const unsigned SrcSz = SrcVT.getSizeInBits();
20641 (void)DstSz;
20642 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&(static_cast <bool> (DstSz < SrcSz && SrcSz <=
64 && DstSz >= 16 && "Unexpected type for custom-lowering FP_ROUND"
) ? void (0) : __assert_fail ("DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && \"Unexpected type for custom-lowering FP_ROUND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20643, __extension__
__PRETTY_FUNCTION__))
20643 "Unexpected type for custom-lowering FP_ROUND")(static_cast <bool> (DstSz < SrcSz && SrcSz <=
64 && DstSz >= 16 && "Unexpected type for custom-lowering FP_ROUND"
) ? void (0) : __assert_fail ("DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && \"Unexpected type for custom-lowering FP_ROUND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20643, __extension__
__PRETTY_FUNCTION__))
;
20644
20645 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20646, __extension__
__PRETTY_FUNCTION__))
20646 "With both FP DP and 16, any FP conversion is legal!")(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20646, __extension__
__PRETTY_FUNCTION__))
;
20647
20648 SDLoc Loc(Op);
20649
20650 // Instruction from 32 -> 16 if hasFP16 is valid
20651 if (SrcSz == 32 && Subtarget->hasFP16())
20652 return Op;
20653
20654 // Lib call from 32 -> 16 / 64 -> [32, 16]
20655 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
20656 assert(LC != RTLIB::UNKNOWN_LIBCALL &&(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_ROUND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_ROUND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20657, __extension__
__PRETTY_FUNCTION__))
20657 "Unexpected type for custom-lowering FP_ROUND")(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_ROUND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_ROUND\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20657, __extension__
__PRETTY_FUNCTION__))
;
20658 MakeLibCallOptions CallOptions;
20659 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20660 SDValue Result;
20661 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20662 Loc, Chain);
20663 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
20664}
20665
20666bool
20667ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
20668 // The ARM target isn't yet aware of offsets.
20669 return false;
20670}
20671
20672bool ARM::isBitFieldInvertedMask(unsigned v) {
20673 if (v == 0xffffffff)
20674 return false;
20675
20676 // there can be 1's on either or both "outsides", all the "inside"
20677 // bits must be 0's
20678 return isShiftedMask_32(~v);
20679}
20680
20681/// isFPImmLegal - Returns true if the target can instruction select the
20682/// specified FP immediate natively. If false, the legalizer will
20683/// materialize the FP immediate as a load from a constant pool.
20684bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
20685 bool ForCodeSize) const {
20686 if (!Subtarget->hasVFP3Base())
20687 return false;
20688 if (VT == MVT::f16 && Subtarget->hasFullFP16())
20689 return ARM_AM::getFP16Imm(Imm) != -1;
20690 if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
20691 ARM_AM::getFP32FP16Imm(Imm) != -1)
20692 return true;
20693 if (VT == MVT::f32)
20694 return ARM_AM::getFP32Imm(Imm) != -1;
20695 if (VT == MVT::f64 && Subtarget->hasFP64())
20696 return ARM_AM::getFP64Imm(Imm) != -1;
20697 return false;
20698}
20699
20700/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
20701/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
20702/// specified in the intrinsic calls.
20703bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
20704 const CallInst &I,
20705 MachineFunction &MF,
20706 unsigned Intrinsic) const {
20707 switch (Intrinsic) {
20708 case Intrinsic::arm_neon_vld1:
20709 case Intrinsic::arm_neon_vld2:
20710 case Intrinsic::arm_neon_vld3:
20711 case Intrinsic::arm_neon_vld4:
20712 case Intrinsic::arm_neon_vld2lane:
20713 case Intrinsic::arm_neon_vld3lane:
20714 case Intrinsic::arm_neon_vld4lane:
20715 case Intrinsic::arm_neon_vld2dup:
20716 case Intrinsic::arm_neon_vld3dup:
20717 case Intrinsic::arm_neon_vld4dup: {
20718 Info.opc = ISD::INTRINSIC_W_CHAIN;
20719 // Conservatively set memVT to the entire set of vectors loaded.
20720 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20721 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
20722 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20723 Info.ptrVal = I.getArgOperand(0);
20724 Info.offset = 0;
20725 Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
20726 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
20727 // volatile loads with NEON intrinsics not supported
20728 Info.flags = MachineMemOperand::MOLoad;
20729 return true;
20730 }
20731 case Intrinsic::arm_neon_vld1x2:
20732 case Intrinsic::arm_neon_vld1x3:
20733 case Intrinsic::arm_neon_vld1x4: {
20734 Info.opc = ISD::INTRINSIC_W_CHAIN;
20735 // Conservatively set memVT to the entire set of vectors loaded.
20736 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20737 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
20738 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20739 Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
20740 Info.offset = 0;
20741 Info.align.reset();
20742 // volatile loads with NEON intrinsics not supported
20743 Info.flags = MachineMemOperand::MOLoad;
20744 return true;
20745 }
20746 case Intrinsic::arm_neon_vst1:
20747 case Intrinsic::arm_neon_vst2:
20748 case Intrinsic::arm_neon_vst3:
20749 case Intrinsic::arm_neon_vst4:
20750 case Intrinsic::arm_neon_vst2lane:
20751 case Intrinsic::arm_neon_vst3lane:
20752 case Intrinsic::arm_neon_vst4lane: {
20753 Info.opc = ISD::INTRINSIC_VOID;
20754 // Conservatively set memVT to the entire set of vectors stored.
20755 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20756 unsigned NumElts = 0;
20757 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20758 Type *ArgTy = I.getArgOperand(ArgI)->getType();
20759 if (!ArgTy->isVectorTy())
20760 break;
20761 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
20762 }
20763 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20764 Info.ptrVal = I.getArgOperand(0);
20765 Info.offset = 0;
20766 Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
20767 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
20768 // volatile stores with NEON intrinsics not supported
20769 Info.flags = MachineMemOperand::MOStore;
20770 return true;
20771 }
20772 case Intrinsic::arm_neon_vst1x2:
20773 case Intrinsic::arm_neon_vst1x3:
20774 case Intrinsic::arm_neon_vst1x4: {
20775 Info.opc = ISD::INTRINSIC_VOID;
20776 // Conservatively set memVT to the entire set of vectors stored.
20777 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20778 unsigned NumElts = 0;
20779 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20780 Type *ArgTy = I.getArgOperand(ArgI)->getType();
20781 if (!ArgTy->isVectorTy())
20782 break;
20783 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
20784 }
20785 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20786 Info.ptrVal = I.getArgOperand(0);
20787 Info.offset = 0;
20788 Info.align.reset();
20789 // volatile stores with NEON intrinsics not supported
20790 Info.flags = MachineMemOperand::MOStore;
20791 return true;
20792 }
20793 case Intrinsic::arm_mve_vld2q:
20794 case Intrinsic::arm_mve_vld4q: {
20795 Info.opc = ISD::INTRINSIC_W_CHAIN;
20796 // Conservatively set memVT to the entire set of vectors loaded.
20797 Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
20798 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
20799 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
20800 Info.ptrVal = I.getArgOperand(0);
20801 Info.offset = 0;
20802 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
20803 // volatile loads with MVE intrinsics not supported
20804 Info.flags = MachineMemOperand::MOLoad;
20805 return true;
20806 }
20807 case Intrinsic::arm_mve_vst2q:
20808 case Intrinsic::arm_mve_vst4q: {
20809 Info.opc = ISD::INTRINSIC_VOID;
20810 // Conservatively set memVT to the entire set of vectors stored.
20811 Type *VecTy = I.getArgOperand(1)->getType();
20812 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
20813 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
20814 Info.ptrVal = I.getArgOperand(0);
20815 Info.offset = 0;
20816 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
20817 // volatile stores with MVE intrinsics not supported
20818 Info.flags = MachineMemOperand::MOStore;
20819 return true;
20820 }
20821 case Intrinsic::arm_mve_vldr_gather_base:
20822 case Intrinsic::arm_mve_vldr_gather_base_predicated: {
20823 Info.opc = ISD::INTRINSIC_W_CHAIN;
20824 Info.ptrVal = nullptr;
20825 Info.memVT = MVT::getVT(I.getType());
20826 Info.align = Align(1);
20827 Info.flags |= MachineMemOperand::MOLoad;
20828 return true;
20829 }
20830 case Intrinsic::arm_mve_vldr_gather_base_wb:
20831 case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
20832 Info.opc = ISD::INTRINSIC_W_CHAIN;
20833 Info.ptrVal = nullptr;
20834 Info.memVT = MVT::getVT(I.getType()->getContainedType(0));
20835 Info.align = Align(1);
20836 Info.flags |= MachineMemOperand::MOLoad;
20837 return true;
20838 }
20839 case Intrinsic::arm_mve_vldr_gather_offset:
20840 case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
20841 Info.opc = ISD::INTRINSIC_W_CHAIN;
20842 Info.ptrVal = nullptr;
20843 MVT DataVT = MVT::getVT(I.getType());
20844 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
20845 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
20846 DataVT.getVectorNumElements());
20847 Info.align = Align(1);
20848 Info.flags |= MachineMemOperand::MOLoad;
20849 return true;
20850 }
20851 case Intrinsic::arm_mve_vstr_scatter_base:
20852 case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
20853 Info.opc = ISD::INTRINSIC_VOID;
20854 Info.ptrVal = nullptr;
20855 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
20856 Info.align = Align(1);
20857 Info.flags |= MachineMemOperand::MOStore;
20858 return true;
20859 }
20860 case Intrinsic::arm_mve_vstr_scatter_base_wb:
20861 case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
20862 Info.opc = ISD::INTRINSIC_W_CHAIN;
20863 Info.ptrVal = nullptr;
20864 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
20865 Info.align = Align(1);
20866 Info.flags |= MachineMemOperand::MOStore;
20867 return true;
20868 }
20869 case Intrinsic::arm_mve_vstr_scatter_offset:
20870 case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
20871 Info.opc = ISD::INTRINSIC_VOID;
20872 Info.ptrVal = nullptr;
20873 MVT DataVT = MVT::getVT(I.getArgOperand(2)->getType());
20874 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
20875 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
20876 DataVT.getVectorNumElements());
20877 Info.align = Align(1);
20878 Info.flags |= MachineMemOperand::MOStore;
20879 return true;
20880 }
20881 case Intrinsic::arm_ldaex:
20882 case Intrinsic::arm_ldrex: {
20883 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20884 Type *ValTy = I.getParamElementType(0);
20885 Info.opc = ISD::INTRINSIC_W_CHAIN;
20886 Info.memVT = MVT::getVT(ValTy);
20887 Info.ptrVal = I.getArgOperand(0);
20888 Info.offset = 0;
20889 Info.align = DL.getABITypeAlign(ValTy);
20890 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
20891 return true;
20892 }
20893 case Intrinsic::arm_stlex:
20894 case Intrinsic::arm_strex: {
20895 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20896 Type *ValTy = I.getParamElementType(1);
20897 Info.opc = ISD::INTRINSIC_W_CHAIN;
20898 Info.memVT = MVT::getVT(ValTy);
20899 Info.ptrVal = I.getArgOperand(1);
20900 Info.offset = 0;
20901 Info.align = DL.getABITypeAlign(ValTy);
20902 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
20903 return true;
20904 }
20905 case Intrinsic::arm_stlexd:
20906 case Intrinsic::arm_strexd:
20907 Info.opc = ISD::INTRINSIC_W_CHAIN;
20908 Info.memVT = MVT::i64;
20909 Info.ptrVal = I.getArgOperand(2);
20910 Info.offset = 0;
20911 Info.align = Align(8);
20912 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
20913 return true;
20914
20915 case Intrinsic::arm_ldaexd:
20916 case Intrinsic::arm_ldrexd:
20917 Info.opc = ISD::INTRINSIC_W_CHAIN;
20918 Info.memVT = MVT::i64;
20919 Info.ptrVal = I.getArgOperand(0);
20920 Info.offset = 0;
20921 Info.align = Align(8);
20922 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
20923 return true;
20924
20925 default:
20926 break;
20927 }
20928
20929 return false;
20930}
20931
20932/// Returns true if it is beneficial to convert a load of a constant
20933/// to just the constant itself.
20934bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
20935 Type *Ty) const {
20936 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20936, __extension__ __PRETTY_FUNCTION__))
;
20937
20938 unsigned Bits = Ty->getPrimitiveSizeInBits();
20939 if (Bits == 0 || Bits > 32)
20940 return false;
20941 return true;
20942}
20943
20944bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
20945 unsigned Index) const {
20946 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
20947 return false;
20948
20949 return (Index == 0 || Index == ResVT.getVectorNumElements());
20950}
20951
20952Instruction *ARMTargetLowering::makeDMB(IRBuilderBase &Builder,
20953 ARM_MB::MemBOpt Domain) const {
20954 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20955
20956 // First, if the target has no DMB, see what fallback we can use.
20957 if (!Subtarget->hasDataBarrier()) {
20958 // Some ARMv6 cpus can support data barriers with an mcr instruction.
20959 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
20960 // here.
20961 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
20962 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
20963 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
20964 Builder.getInt32(0), Builder.getInt32(7),
20965 Builder.getInt32(10), Builder.getInt32(5)};
20966 return Builder.CreateCall(MCR, args);
20967 } else {
20968 // Instead of using barriers, atomic accesses on these subtargets use
20969 // libcalls.
20970 llvm_unreachable("makeDMB on a target so old that it has no barriers")::llvm::llvm_unreachable_internal("makeDMB on a target so old that it has no barriers"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20970)
;
20971 }
20972 } else {
20973 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
20974 // Only a full system barrier exists in the M-class architectures.
20975 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
20976 Constant *CDomain = Builder.getInt32(Domain);
20977 return Builder.CreateCall(DMB, CDomain);
20978 }
20979}
20980
20981// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
20982Instruction *ARMTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
20983 Instruction *Inst,
20984 AtomicOrdering Ord) const {
20985 switch (Ord) {
20986 case AtomicOrdering::NotAtomic:
20987 case AtomicOrdering::Unordered:
20988 llvm_unreachable("Invalid fence: unordered/non-atomic")::llvm::llvm_unreachable_internal("Invalid fence: unordered/non-atomic"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 20988)
;
20989 case AtomicOrdering::Monotonic:
20990 case AtomicOrdering::Acquire:
20991 return nullptr; // Nothing to do
20992 case AtomicOrdering::SequentiallyConsistent:
20993 if (!Inst->hasAtomicStore())
20994 return nullptr; // Nothing to do
20995 [[fallthrough]];
20996 case AtomicOrdering::Release:
20997 case AtomicOrdering::AcquireRelease:
20998 if (Subtarget->preferISHSTBarriers())
20999 return makeDMB(Builder, ARM_MB::ISHST);
21000 // FIXME: add a comment with a link to documentation justifying this.
21001 else
21002 return makeDMB(Builder, ARM_MB::ISH);
21003 }
21004 llvm_unreachable("Unknown fence ordering in emitLeadingFence")::llvm::llvm_unreachable_internal("Unknown fence ordering in emitLeadingFence"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21004)
;
21005}
21006
21007Instruction *ARMTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
21008 Instruction *Inst,
21009 AtomicOrdering Ord) const {
21010 switch (Ord) {
21011 case AtomicOrdering::NotAtomic:
21012 case AtomicOrdering::Unordered:
21013 llvm_unreachable("Invalid fence: unordered/not-atomic")::llvm::llvm_unreachable_internal("Invalid fence: unordered/not-atomic"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21013)
;
21014 case AtomicOrdering::Monotonic:
21015 case AtomicOrdering::Release:
21016 return nullptr; // Nothing to do
21017 case AtomicOrdering::Acquire:
21018 case AtomicOrdering::AcquireRelease:
21019 case AtomicOrdering::SequentiallyConsistent:
21020 return makeDMB(Builder, ARM_MB::ISH);
21021 }
21022 llvm_unreachable("Unknown fence ordering in emitTrailingFence")::llvm::llvm_unreachable_internal("Unknown fence ordering in emitTrailingFence"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21022)
;
21023}
21024
21025// Loads and stores less than 64-bits are already atomic; ones above that
21026// are doomed anyway, so defer to the default libcall and blame the OS when
21027// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21028// anything for those.
21029TargetLoweringBase::AtomicExpansionKind
21030ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
21031 bool has64BitAtomicStore;
21032 if (Subtarget->isMClass())
21033 has64BitAtomicStore = false;
21034 else if (Subtarget->isThumb())
21035 has64BitAtomicStore = Subtarget->hasV7Ops();
21036 else
21037 has64BitAtomicStore = Subtarget->hasV6Ops();
21038
21039 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
21040 return Size == 64 && has64BitAtomicStore ? AtomicExpansionKind::Expand
21041 : AtomicExpansionKind::None;
21042}
21043
21044// Loads and stores less than 64-bits are already atomic; ones above that
21045// are doomed anyway, so defer to the default libcall and blame the OS when
21046// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21047// anything for those.
21048// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
21049// guarantee, see DDI0406C ARM architecture reference manual,
21050// sections A8.8.72-74 LDRD)
21051TargetLowering::AtomicExpansionKind
21052ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
21053 bool has64BitAtomicLoad;
21054 if (Subtarget->isMClass())
21055 has64BitAtomicLoad = false;
21056 else if (Subtarget->isThumb())
21057 has64BitAtomicLoad = Subtarget->hasV7Ops();
21058 else
21059 has64BitAtomicLoad = Subtarget->hasV6Ops();
21060
21061 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
21062 return (Size == 64 && has64BitAtomicLoad) ? AtomicExpansionKind::LLOnly
21063 : AtomicExpansionKind::None;
21064}
21065
21066// For the real atomic operations, we have ldrex/strex up to 32 bits,
21067// and up to 64 bits on the non-M profiles
21068TargetLowering::AtomicExpansionKind
21069ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
21070 if (AI->isFloatingPointOperation())
21071 return AtomicExpansionKind::CmpXChg;
21072
21073 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
21074 bool hasAtomicRMW;
21075 if (Subtarget->isMClass())
21076 hasAtomicRMW = Subtarget->hasV8MBaselineOps();
21077 else if (Subtarget->isThumb())
21078 hasAtomicRMW = Subtarget->hasV7Ops();
21079 else
21080 hasAtomicRMW = Subtarget->hasV6Ops();
21081 if (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) {
21082 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21083 // implement atomicrmw without spilling. If the target address is also on
21084 // the stack and close enough to the spill slot, this can lead to a
21085 // situation where the monitor always gets cleared and the atomic operation
21086 // can never succeed. So at -O0 lower this operation to a CAS loop.
21087 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
21088 return AtomicExpansionKind::CmpXChg;
21089 return AtomicExpansionKind::LLSC;
21090 }
21091 return AtomicExpansionKind::None;
21092}
21093
21094// Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used up to 32
21095// bits, and up to 64 bits on the non-M profiles.
21096TargetLowering::AtomicExpansionKind
21097ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
21098 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21099 // implement cmpxchg without spilling. If the address being exchanged is also
21100 // on the stack and close enough to the spill slot, this can lead to a
21101 // situation where the monitor always gets cleared and the atomic operation
21102 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
21103 unsigned Size = AI->getOperand(1)->getType()->getPrimitiveSizeInBits();
21104 bool HasAtomicCmpXchg;
21105 if (Subtarget->isMClass())
21106 HasAtomicCmpXchg = Subtarget->hasV8MBaselineOps();
21107 else if (Subtarget->isThumb())
21108 HasAtomicCmpXchg = Subtarget->hasV7Ops();
21109 else
21110 HasAtomicCmpXchg = Subtarget->hasV6Ops();
21111 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg &&
21112 Size <= (Subtarget->isMClass() ? 32U : 64U))
21113 return AtomicExpansionKind::LLSC;
21114 return AtomicExpansionKind::None;
21115}
21116
21117bool ARMTargetLowering::shouldInsertFencesForAtomic(
21118 const Instruction *I) const {
21119 return InsertFencesForAtomic;
21120}
21121
21122bool ARMTargetLowering::useLoadStackGuardNode() const {
21123 // ROPI/RWPI are not supported currently.
21124 return !Subtarget->isROPI() && !Subtarget->isRWPI();
21125}
21126
21127void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
21128 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21129 return TargetLowering::insertSSPDeclarations(M);
21130
21131 // MSVC CRT has a global variable holding security cookie.
21132 M.getOrInsertGlobal("__security_cookie",
21133 Type::getInt8PtrTy(M.getContext()));
21134
21135 // MSVC CRT has a function to validate security cookie.
21136 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
21137 "__security_check_cookie", Type::getVoidTy(M.getContext()),
21138 Type::getInt8PtrTy(M.getContext()));
21139 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
21140 F->addParamAttr(0, Attribute::AttrKind::InReg);
21141}
21142
21143Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
21144 // MSVC CRT has a global variable holding security cookie.
21145 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21146 return M.getGlobalVariable("__security_cookie");
21147 return TargetLowering::getSDagStackGuard(M);
21148}
21149
21150Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
21151 // MSVC CRT has a function to validate security cookie.
21152 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21153 return M.getFunction("__security_check_cookie");
21154 return TargetLowering::getSSPStackGuardCheck(M);
21155}
21156
21157bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
21158 unsigned &Cost) const {
21159 // If we do not have NEON, vector types are not natively supported.
21160 if (!Subtarget->hasNEON())
21161 return false;
21162
21163 // Floating point values and vector values map to the same register file.
21164 // Therefore, although we could do a store extract of a vector type, this is
21165 // better to leave at float as we have more freedom in the addressing mode for
21166 // those.
21167 if (VectorTy->isFPOrFPVectorTy())
21168 return false;
21169
21170 // If the index is unknown at compile time, this is very expensive to lower
21171 // and it is not possible to combine the store with the extract.
21172 if (!isa<ConstantInt>(Idx))
21173 return false;
21174
21175 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type")(static_cast <bool> (VectorTy->isVectorTy() &&
"VectorTy is not a vector type") ? void (0) : __assert_fail (
"VectorTy->isVectorTy() && \"VectorTy is not a vector type\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21175, __extension__
__PRETTY_FUNCTION__))
;
21176 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
21177 // We can do a store + vector extract on any vector that fits perfectly in a D
21178 // or Q register.
21179 if (BitWidth == 64 || BitWidth == 128) {
21180 Cost = 0;
21181 return true;
21182 }
21183 return false;
21184}
21185
21186bool ARMTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
21187 return Subtarget->hasV6T2Ops();
21188}
21189
21190bool ARMTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
21191 return Subtarget->hasV6T2Ops();
21192}
21193
21194bool ARMTargetLowering::isMaskAndCmp0FoldingBeneficial(
21195 const Instruction &AndI) const {
21196 if (!Subtarget->hasV7Ops())
21197 return false;
21198
21199 // Sink the `and` instruction only if the mask would fit into a modified
21200 // immediate operand.
21201 ConstantInt *Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
21202 if (!Mask || Mask->getValue().getBitWidth() > 32u)
21203 return false;
21204 auto MaskVal = unsigned(Mask->getValue().getZExtValue());
21205 return (Subtarget->isThumb2() ? ARM_AM::getT2SOImmVal(MaskVal)
21206 : ARM_AM::getSOImmVal(MaskVal)) != -1;
21207}
21208
21209bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
21210 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
21211}
21212
21213Value *ARMTargetLowering::emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
21214 Value *Addr,
21215 AtomicOrdering Ord) const {
21216 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21217 bool IsAcquire = isAcquireOrStronger(Ord);
21218
21219 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
21220 // intrinsic must return {i32, i32} and we have to recombine them into a
21221 // single i64 here.
21222 if (ValueTy->getPrimitiveSizeInBits() == 64) {
21223 Intrinsic::ID Int =
21224 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
21225 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
21226
21227 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
21228 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
21229
21230 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21231 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21232 if (!Subtarget->isLittle())
21233 std::swap (Lo, Hi);
21234 Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
21235 Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
21236 return Builder.CreateOr(
21237 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 32)), "val64");
21238 }
21239
21240 Type *Tys[] = { Addr->getType() };
21241 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
21242 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
21243 CallInst *CI = Builder.CreateCall(Ldrex, Addr);
21244
21245 CI->addParamAttr(
21246 0, Attribute::get(M->getContext(), Attribute::ElementType, ValueTy));
21247 return Builder.CreateTruncOrBitCast(CI, ValueTy);
21248}
21249
21250void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
21251 IRBuilderBase &Builder) const {
21252 if (!Subtarget->hasV7Ops())
21253 return;
21254 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21255 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
21256}
21257
21258Value *ARMTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
21259 Value *Val, Value *Addr,
21260 AtomicOrdering Ord) const {
21261 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21262 bool IsRelease = isReleaseOrStronger(Ord);
21263
21264 // Since the intrinsics must have legal type, the i64 intrinsics take two
21265 // parameters: "i32, i32". We must marshal Val into the appropriate form
21266 // before the call.
21267 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
21268 Intrinsic::ID Int =
21269 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
21270 Function *Strex = Intrinsic::getDeclaration(M, Int);
21271 Type *Int32Ty = Type::getInt32Ty(M->getContext());
21272
21273 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
21274 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
21275 if (!Subtarget->isLittle())
21276 std::swap(Lo, Hi);
21277 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
21278 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
21279 }
21280
21281 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
21282 Type *Tys[] = { Addr->getType() };
21283 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
21284
21285 CallInst *CI = Builder.CreateCall(
21286 Strex, {Builder.CreateZExtOrBitCast(
21287 Val, Strex->getFunctionType()->getParamType(0)),
21288 Addr});
21289 CI->addParamAttr(1, Attribute::get(M->getContext(), Attribute::ElementType,
21290 Val->getType()));
21291 return CI;
21292}
21293
21294
21295bool ARMTargetLowering::alignLoopsWithOptSize() const {
21296 return Subtarget->isMClass();
21297}
21298
21299/// A helper function for determining the number of interleaved accesses we
21300/// will generate when lowering accesses of the given type.
21301unsigned
21302ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
21303 const DataLayout &DL) const {
21304 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
21305}
21306
21307bool ARMTargetLowering::isLegalInterleavedAccessType(
21308 unsigned Factor, FixedVectorType *VecTy, Align Alignment,
21309 const DataLayout &DL) const {
21310
21311 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
21312 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
21313
21314 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
21315 return false;
21316
21317 // Ensure the vector doesn't have f16 elements. Even though we could do an
21318 // i16 vldN, we can't hold the f16 vectors and will end up converting via
21319 // f32.
21320 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
21321 return false;
21322 if (Subtarget->hasMVEIntegerOps() && Factor == 3)
21323 return false;
21324
21325 // Ensure the number of vector elements is greater than 1.
21326 if (VecTy->getNumElements() < 2)
21327 return false;
21328
21329 // Ensure the element type is legal.
21330 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
21331 return false;
21332 // And the alignment if high enough under MVE.
21333 if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
21334 return false;
21335
21336 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
21337 // 128 will be split into multiple interleaved accesses.
21338 if (Subtarget->hasNEON() && VecSize == 64)
21339 return true;
21340 return VecSize % 128 == 0;
21341}
21342
21343unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
21344 if (Subtarget->hasNEON())
21345 return 4;
21346 if (Subtarget->hasMVEIntegerOps())
21347 return MVEMaxSupportedInterleaveFactor;
21348 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
21349}
21350
21351/// Lower an interleaved load into a vldN intrinsic.
21352///
21353/// E.g. Lower an interleaved load (Factor = 2):
21354/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
21355/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
21356/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
21357///
21358/// Into:
21359/// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
21360/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
21361/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
21362bool ARMTargetLowering::lowerInterleavedLoad(
21363 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
21364 ArrayRef<unsigned> Indices, unsigned Factor) const {
21365 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21366, __extension__
__PRETTY_FUNCTION__))
21366 "Invalid interleave factor")(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21366, __extension__
__PRETTY_FUNCTION__))
;
21367 assert(!Shuffles.empty() && "Empty shufflevector input")(static_cast <bool> (!Shuffles.empty() && "Empty shufflevector input"
) ? void (0) : __assert_fail ("!Shuffles.empty() && \"Empty shufflevector input\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21367, __extension__
__PRETTY_FUNCTION__))
;
21368 assert(Shuffles.size() == Indices.size() &&(static_cast <bool> (Shuffles.size() == Indices.size() &&
"Unmatched number of shufflevectors and indices") ? void (0)
: __assert_fail ("Shuffles.size() == Indices.size() && \"Unmatched number of shufflevectors and indices\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21369, __extension__
__PRETTY_FUNCTION__))
21369 "Unmatched number of shufflevectors and indices")(static_cast <bool> (Shuffles.size() == Indices.size() &&
"Unmatched number of shufflevectors and indices") ? void (0)
: __assert_fail ("Shuffles.size() == Indices.size() && \"Unmatched number of shufflevectors and indices\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21369, __extension__
__PRETTY_FUNCTION__))
;
21370
21371 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
21372 Type *EltTy = VecTy->getElementType();
21373
21374 const DataLayout &DL = LI->getModule()->getDataLayout();
21375 Align Alignment = LI->getAlign();
21376
21377 // Skip if we do not have NEON and skip illegal vector types. We can
21378 // "legalize" wide vector types into multiple interleaved accesses as long as
21379 // the vector types are divisible by 128.
21380 if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
21381 return false;
21382
21383 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
21384
21385 // A pointer vector can not be the return type of the ldN intrinsics. Need to
21386 // load integer vectors first and then convert to pointer vectors.
21387 if (EltTy->isPointerTy())
21388 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
21389
21390 IRBuilder<> Builder(LI);
21391
21392 // The base address of the load.
21393 Value *BaseAddr = LI->getPointerOperand();
21394
21395 if (NumLoads > 1) {
21396 // If we're going to generate more than one load, reset the sub-vector type
21397 // to something legal.
21398 VecTy = FixedVectorType::get(VecTy->getElementType(),
21399 VecTy->getNumElements() / NumLoads);
21400
21401 // We will compute the pointer operand of each load from the original base
21402 // address using GEPs. Cast the base address to a pointer to the scalar
21403 // element type.
21404 BaseAddr = Builder.CreateBitCast(
21405 BaseAddr,
21406 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
21407 }
21408
21409 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!")(static_cast <bool> (isTypeLegal(EVT::getEVT(VecTy)) &&
"Illegal vldN vector type!") ? void (0) : __assert_fail ("isTypeLegal(EVT::getEVT(VecTy)) && \"Illegal vldN vector type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21409, __extension__
__PRETTY_FUNCTION__))
;
21410
21411 auto createLoadIntrinsic = [&](Value *BaseAddr) {
21412 if (Subtarget->hasNEON()) {
21413 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
21414 Type *Tys[] = {VecTy, Int8Ptr};
21415 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
21416 Intrinsic::arm_neon_vld3,
21417 Intrinsic::arm_neon_vld4};
21418 Function *VldnFunc =
21419 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
21420
21421 SmallVector<Value *, 2> Ops;
21422 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
21423 Ops.push_back(Builder.getInt32(LI->getAlign().value()));
21424
21425 return Builder.CreateCall(VldnFunc, Ops, "vldN");
21426 } else {
21427 assert((Factor == 2 || Factor == 4) &&(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21428, __extension__
__PRETTY_FUNCTION__))
21428 "expected interleave factor of 2 or 4 for MVE")(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21428, __extension__
__PRETTY_FUNCTION__))
;
21429 Intrinsic::ID LoadInts =
21430 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
21431 Type *VecEltTy =
21432 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
21433 Type *Tys[] = {VecTy, VecEltTy};
21434 Function *VldnFunc =
21435 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
21436
21437 SmallVector<Value *, 2> Ops;
21438 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
21439 return Builder.CreateCall(VldnFunc, Ops, "vldN");
21440 }
21441 };
21442
21443 // Holds sub-vectors extracted from the load intrinsic return values. The
21444 // sub-vectors are associated with the shufflevector instructions they will
21445 // replace.
21446 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
21447
21448 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
21449 // If we're generating more than one load, compute the base address of
21450 // subsequent loads as an offset from the previous.
21451 if (LoadCount > 0)
21452 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
21453 VecTy->getNumElements() * Factor);
21454
21455 CallInst *VldN = createLoadIntrinsic(BaseAddr);
21456
21457 // Replace uses of each shufflevector with the corresponding vector loaded
21458 // by ldN.
21459 for (unsigned i = 0; i < Shuffles.size(); i++) {
21460 ShuffleVectorInst *SV = Shuffles[i];
21461 unsigned Index = Indices[i];
21462
21463 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
21464
21465 // Convert the integer vector to pointer vector if the element is pointer.
21466 if (EltTy->isPointerTy())
21467 SubVec = Builder.CreateIntToPtr(
21468 SubVec,
21469 FixedVectorType::get(SV->getType()->getElementType(), VecTy));
21470
21471 SubVecs[SV].push_back(SubVec);
21472 }
21473 }
21474
21475 // Replace uses of the shufflevector instructions with the sub-vectors
21476 // returned by the load intrinsic. If a shufflevector instruction is
21477 // associated with more than one sub-vector, those sub-vectors will be
21478 // concatenated into a single wide vector.
21479 for (ShuffleVectorInst *SVI : Shuffles) {
21480 auto &SubVec = SubVecs[SVI];
21481 auto *WideVec =
21482 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
21483 SVI->replaceAllUsesWith(WideVec);
21484 }
21485
21486 return true;
21487}
21488
21489/// Lower an interleaved store into a vstN intrinsic.
21490///
21491/// E.g. Lower an interleaved store (Factor = 3):
21492/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
21493/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
21494/// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
21495///
21496/// Into:
21497/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
21498/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
21499/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
21500/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21501///
21502/// Note that the new shufflevectors will be removed and we'll only generate one
21503/// vst3 instruction in CodeGen.
21504///
21505/// Example for a more general valid mask (Factor 3). Lower:
21506/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
21507/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
21508/// store <12 x i32> %i.vec, <12 x i32>* %ptr
21509///
21510/// Into:
21511/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
21512/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
21513/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
21514/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21515bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
21516 ShuffleVectorInst *SVI,
21517 unsigned Factor) const {
21518 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21519, __extension__
__PRETTY_FUNCTION__))
21519 "Invalid interleave factor")(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21519, __extension__
__PRETTY_FUNCTION__))
;
21520
21521 auto *VecTy = cast<FixedVectorType>(SVI->getType());
21522 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store")(static_cast <bool> (VecTy->getNumElements() % Factor
== 0 && "Invalid interleaved store") ? void (0) : __assert_fail
("VecTy->getNumElements() % Factor == 0 && \"Invalid interleaved store\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21522, __extension__
__PRETTY_FUNCTION__))
;
21523
21524 unsigned LaneLen = VecTy->getNumElements() / Factor;
21525 Type *EltTy = VecTy->getElementType();
21526 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
21527
21528 const DataLayout &DL = SI->getModule()->getDataLayout();
21529 Align Alignment = SI->getAlign();
21530
21531 // Skip if we do not have NEON and skip illegal vector types. We can
21532 // "legalize" wide vector types into multiple interleaved accesses as long as
21533 // the vector types are divisible by 128.
21534 if (!isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
21535 return false;
21536
21537 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
21538
21539 Value *Op0 = SVI->getOperand(0);
21540 Value *Op1 = SVI->getOperand(1);
21541 IRBuilder<> Builder(SI);
21542
21543 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
21544 // vectors to integer vectors.
21545 if (EltTy->isPointerTy()) {
21546 Type *IntTy = DL.getIntPtrType(EltTy);
21547
21548 // Convert to the corresponding integer vector.
21549 auto *IntVecTy =
21550 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
21551 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
21552 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
21553
21554 SubVecTy = FixedVectorType::get(IntTy, LaneLen);
21555 }
21556
21557 // The base address of the store.
21558 Value *BaseAddr = SI->getPointerOperand();
21559
21560 if (NumStores > 1) {
21561 // If we're going to generate more than one store, reset the lane length
21562 // and sub-vector type to something legal.
21563 LaneLen /= NumStores;
21564 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
21565
21566 // We will compute the pointer operand of each store from the original base
21567 // address using GEPs. Cast the base address to a pointer to the scalar
21568 // element type.
21569 BaseAddr = Builder.CreateBitCast(
21570 BaseAddr,
21571 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
21572 }
21573
21574 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!")(static_cast <bool> (isTypeLegal(EVT::getEVT(SubVecTy))
&& "Illegal vstN vector type!") ? void (0) : __assert_fail
("isTypeLegal(EVT::getEVT(SubVecTy)) && \"Illegal vstN vector type!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21574, __extension__
__PRETTY_FUNCTION__))
;
21575
21576 auto Mask = SVI->getShuffleMask();
21577
21578 auto createStoreIntrinsic = [&](Value *BaseAddr,
21579 SmallVectorImpl<Value *> &Shuffles) {
21580 if (Subtarget->hasNEON()) {
21581 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
21582 Intrinsic::arm_neon_vst3,
21583 Intrinsic::arm_neon_vst4};
21584 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
21585 Type *Tys[] = {Int8Ptr, SubVecTy};
21586
21587 Function *VstNFunc = Intrinsic::getDeclaration(
21588 SI->getModule(), StoreInts[Factor - 2], Tys);
21589
21590 SmallVector<Value *, 6> Ops;
21591 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
21592 append_range(Ops, Shuffles);
21593 Ops.push_back(Builder.getInt32(SI->getAlign().value()));
21594 Builder.CreateCall(VstNFunc, Ops);
21595 } else {
21596 assert((Factor == 2 || Factor == 4) &&(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21597, __extension__
__PRETTY_FUNCTION__))
21597 "expected interleave factor of 2 or 4 for MVE")(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21597, __extension__
__PRETTY_FUNCTION__))
;
21598 Intrinsic::ID StoreInts =
21599 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
21600 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
21601 SI->getPointerAddressSpace());
21602 Type *Tys[] = {EltPtrTy, SubVecTy};
21603 Function *VstNFunc =
21604 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
21605
21606 SmallVector<Value *, 6> Ops;
21607 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
21608 append_range(Ops, Shuffles);
21609 for (unsigned F = 0; F < Factor; F++) {
21610 Ops.push_back(Builder.getInt32(F));
21611 Builder.CreateCall(VstNFunc, Ops);
21612 Ops.pop_back();
21613 }
21614 }
21615 };
21616
21617 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
21618 // If we generating more than one store, we compute the base address of
21619 // subsequent stores as an offset from the previous.
21620 if (StoreCount > 0)
21621 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
21622 BaseAddr, LaneLen * Factor);
21623
21624 SmallVector<Value *, 4> Shuffles;
21625
21626 // Split the shufflevector operands into sub vectors for the new vstN call.
21627 for (unsigned i = 0; i < Factor; i++) {
21628 unsigned IdxI = StoreCount * LaneLen * Factor + i;
21629 if (Mask[IdxI] >= 0) {
21630 Shuffles.push_back(Builder.CreateShuffleVector(
21631 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
21632 } else {
21633 unsigned StartMask = 0;
21634 for (unsigned j = 1; j < LaneLen; j++) {
21635 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
21636 if (Mask[IdxJ * Factor + IdxI] >= 0) {
21637 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
21638 break;
21639 }
21640 }
21641 // Note: If all elements in a chunk are undefs, StartMask=0!
21642 // Note: Filling undef gaps with random elements is ok, since
21643 // those elements were being written anyway (with undefs).
21644 // In the case of all undefs we're defaulting to using elems from 0
21645 // Note: StartMask cannot be negative, it's checked in
21646 // isReInterleaveMask
21647 Shuffles.push_back(Builder.CreateShuffleVector(
21648 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
21649 }
21650 }
21651
21652 createStoreIntrinsic(BaseAddr, Shuffles);
21653 }
21654 return true;
21655}
21656
21657enum HABaseType {
21658 HA_UNKNOWN = 0,
21659 HA_FLOAT,
21660 HA_DOUBLE,
21661 HA_VECT64,
21662 HA_VECT128
21663};
21664
21665static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
21666 uint64_t &Members) {
21667 if (auto *ST = dyn_cast<StructType>(Ty)) {
21668 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
21669 uint64_t SubMembers = 0;
21670 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
21671 return false;
21672 Members += SubMembers;
21673 }
21674 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
21675 uint64_t SubMembers = 0;
21676 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
21677 return false;
21678 Members += SubMembers * AT->getNumElements();
21679 } else if (Ty->isFloatTy()) {
21680 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
21681 return false;
21682 Members = 1;
21683 Base = HA_FLOAT;
21684 } else if (Ty->isDoubleTy()) {
21685 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
21686 return false;
21687 Members = 1;
21688 Base = HA_DOUBLE;
21689 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
21690 Members = 1;
21691 switch (Base) {
21692 case HA_FLOAT:
21693 case HA_DOUBLE:
21694 return false;
21695 case HA_VECT64:
21696 return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
21697 case HA_VECT128:
21698 return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
21699 case HA_UNKNOWN:
21700 switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
21701 case 64:
21702 Base = HA_VECT64;
21703 return true;
21704 case 128:
21705 Base = HA_VECT128;
21706 return true;
21707 default:
21708 return false;
21709 }
21710 }
21711 }
21712
21713 return (Members > 0 && Members <= 4);
21714}
21715
21716/// Return the correct alignment for the current calling convention.
21717Align ARMTargetLowering::getABIAlignmentForCallingConv(
21718 Type *ArgTy, const DataLayout &DL) const {
21719 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
21720 if (!ArgTy->isVectorTy())
21721 return ABITypeAlign;
21722
21723 // Avoid over-aligning vector parameters. It would require realigning the
21724 // stack and waste space for no real benefit.
21725 return std::min(ABITypeAlign, DL.getStackAlignment());
21726}
21727
21728/// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
21729/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
21730/// passing according to AAPCS rules.
21731bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
21732 Type *Ty, CallingConv::ID CallConv, bool isVarArg,
21733 const DataLayout &DL) const {
21734 if (getEffectiveCallingConv(CallConv, isVarArg) !=
21735 CallingConv::ARM_AAPCS_VFP)
21736 return false;
21737
21738 HABaseType Base = HA_UNKNOWN;
21739 uint64_t Members = 0;
21740 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
21741 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "isHA: " << IsHA <<
" "; Ty->dump(); } } while (false)
;
21742
21743 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
21744 return IsHA || IsIntArray;
21745}
21746
21747Register ARMTargetLowering::getExceptionPointerRegister(
21748 const Constant *PersonalityFn) const {
21749 // Platforms which do not use SjLj EH may return values in these registers
21750 // via the personality function.
21751 return Subtarget->useSjLjEH() ? Register() : ARM::R0;
21752}
21753
21754Register ARMTargetLowering::getExceptionSelectorRegister(
21755 const Constant *PersonalityFn) const {
21756 // Platforms which do not use SjLj EH may return values in these registers
21757 // via the personality function.
21758 return Subtarget->useSjLjEH() ? Register() : ARM::R1;
21759}
21760
21761void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
21762 // Update IsSplitCSR in ARMFunctionInfo.
21763 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
21764 AFI->setIsSplitCSR(true);
21765}
21766
21767void ARMTargetLowering::insertCopiesSplitCSR(
21768 MachineBasicBlock *Entry,
21769 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
21770 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
21771 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
21772 if (!IStart)
21773 return;
21774
21775 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21776 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
21777 MachineBasicBlock::iterator MBBI = Entry->begin();
21778 for (const MCPhysReg *I = IStart; *I; ++I) {
21779 const TargetRegisterClass *RC = nullptr;
21780 if (ARM::GPRRegClass.contains(*I))
21781 RC = &ARM::GPRRegClass;
21782 else if (ARM::DPRRegClass.contains(*I))
21783 RC = &ARM::DPRRegClass;
21784 else
21785 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21785)
;
21786
21787 Register NewVR = MRI->createVirtualRegister(RC);
21788 // Create copy from CSR to a virtual register.
21789 // FIXME: this currently does not emit CFI pseudo-instructions, it works
21790 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
21791 // nounwind. If we want to generalize this later, we may need to emit
21792 // CFI pseudo-instructions.
21793 assert(Entry->getParent()->getFunction().hasFnAttribute((static_cast <bool> (Entry->getParent()->getFunction
().hasFnAttribute( Attribute::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? void (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute( Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21795, __extension__
__PRETTY_FUNCTION__))
21794 Attribute::NoUnwind) &&(static_cast <bool> (Entry->getParent()->getFunction
().hasFnAttribute( Attribute::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? void (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute( Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21795, __extension__
__PRETTY_FUNCTION__))
21795 "Function should be nounwind in insertCopiesSplitCSR!")(static_cast <bool> (Entry->getParent()->getFunction
().hasFnAttribute( Attribute::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? void (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute( Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "llvm/lib/Target/ARM/ARMISelLowering.cpp", 21795, __extension__
__PRETTY_FUNCTION__))
;
21796 Entry->addLiveIn(*I);
21797 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
21798 .addReg(*I);
21799
21800 // Insert the copy-back instructions right before the terminator.
21801 for (auto *Exit : Exits)
21802 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
21803 TII->get(TargetOpcode::COPY), *I)
21804 .addReg(NewVR);
21805 }
21806}
21807
21808void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
21809 MF.getFrameInfo().computeMaxCallFrameSize(MF);
21810 TargetLoweringBase::finalizeLowering(MF);
21811}